@archilogic/floor-plan-sdk 5.2.0 → 5.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/fpe.d.ts +4 -0
- package/dist/fpe.js +1 -1
- package/dist/fpe.umd.cjs +1 -1
- package/package.json +1 -1
package/dist/fpe.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const t=3.28084,e=(t,e=1/64)=>{const i=1/e;return Math.round(t*i)/i};function i(t){return Math.sign(t)*Math.floor(Math.abs(t))}function s(t,e){return typeof t<"u"&&null!==t&&Number.isFinite(t)&&t>=-e&&t<=e}const r=" ",n="m",o="′",a="″",l="m²",h="ft²";function u(t,e=.5,i=1/64){return!(t%e)||e<=i?[t/e,1/e]:u(t,e/2)}const c=(s=0,l="metric",h=3)=>{if("imperial"===l){const{feet:n,inches:l,fraction:h,isNegative:c}=function(s){const r=s*t,n=Math.abs(r),o=e(n%1*12);return{feet:i(n),inches:i(o),fraction:e(o%1),isNegative:Math.sign(s)<0}}(s);let d="";if(h>0){const[t,i]=u(e(h));d=`${r}${t}/${i}`}return`${c?"-":""}${n}${o}${r}${l}${d}${a}`}const c=Math.pow(10,h);return`${Math.round(s*c)/c}${r}${n}`},d=(e=0,i="metric",s=0,n=!0)=>{let o="",a="";const u=Math.pow(10,s);if("imperial"===i){const i=function(e){return e*t*t}(e);o=""+Math.round(i*u)/u,a=`${r}${h}`}else o=""+Math.round(e*u)/u,a=`${r}${l}`;return n&&(o+=a),o};["US","USA","United States","U.S","U.S.A","England","UK","U.K","United Kingdom","Liberia","Myanmar"].map(t=>t.toLowerCase());const p=(t,e)=>{const i=`.${e}`;return(t=>t.replace(/[/\\]/g,"_"))((t=>t.replace(/[.,\s]/g,"_"))(t.endsWith(i)?t.split(i)[0]:t))+i};function f(t){const e=function(t){return"#"===t.slice(0,1)&&(t=t.slice(1)),t}(t);return 3===e.length?`#${e.split("").map(t=>t+t).join("")}`:t}function m(t){return t>=0&&t<=255}function g(t){const e=f(t),i={r:parseInt(e.substring(1,3),16),g:parseInt(e.substring(3,5),16),b:parseInt(e.substring(5,7),16)};if(function({r:t,g:e,b:i}){return m(t)&&m(e)&&m(i)}(i))return i;throw"invalid hex color input"}function y(t){return JSON.parse(JSON.stringify(t))}function v(...t){let e={};for(const i of t)if(i instanceof Array)e instanceof Array||(e=[]),e=[...e,...i];else if(i instanceof Object)for(const t of Object.entries(i)){const i=t[0];let s=t[1];s instanceof Object&&i in e&&(s=v(e[i],s)),e={...e,[i]:s}}return e}function x(){return typeof window<"u"&&typeof navigator<"u"&&typeof document<"u"}!x()||window.self===window.top||window.location.ancestorOrigins&&window.location.ancestorOrigins[0]||document.referrer,x()&&navigator.platform.toUpperCase().indexOf("MAC");var b={exports:{}};function w(){}w.prototype={on:function(t,e,i){var s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var s=this;function r(){s.off(t,r),e.apply(i,arguments)}return r._=e,this.on(t,r,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),s=0,r=i.length;s<r;s++)i[s].fn.apply(i[s].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),s=i[t],r=[];if(s&&e)for(var n=0,o=s.length;n<o;n++)s[n].fn!==e&&s[n].fn._!==e&&r.push(s[n]);return r.length?i[t]=r:delete i[t],this}},b.exports=w;var _=b.exports.TinyEmitter=w;const P=["info","warnings","errors"];class E extends _{constructor(t){super(),this.levels=P.slice(),this.info=this.log,t&&this.setLevels(t),this.levelStack=[]}setLevels(t){const e=this.levels.slice();if("string"==typeof t)switch(t){case"none":this.levels=[];break;case"all":this.levels=["debug","info","warnings","errors"];break;case"debug":this.levels=["debug"];break;case"info":this.levels=["info"];break;case"warnings":this.levels=["warnings"];break;case"errors":this.levels=["errors"];break;default:console.error(`Unknown setting '${t}'.`)}else this.levels=t.slice();return e}push(){this.levelStack.push(this.levels)}pushAndSetLevels(t){return this.push(),this.setLevels(t)}pop(){if(this.levelStack.length>0){const t=this.levelStack.pop();this.setLevels(t)}}debug(...t){this.levels.includes("debug")&&(console.debug(...t),this.emit("debug",...t))}log(...t){this.levels.includes("info")&&(console.log(...t),this.emit("info",...t))}warn(...t){this.levels.includes("warnings")&&(console.warn(...t),this.emit("warning",...t))}error(...t){this.levels.includes("errors")&&(console.error(...t),this.emit("error",...t))}}for(var T,A=[],I=0;I<256;++I)A.push((I+256).toString(16).slice(1));var S=new Uint8Array(16);function C(){if(!T&&!(T="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return T(S)}const M={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function O(t,e,i){if(M.randomUUID&&!t)return M.randomUUID();var s=(t=t||{}).random||(t.rng||C)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(t,e=0){return(A[t[e+0]]+A[t[e+1]]+A[t[e+2]]+A[t[e+3]]+"-"+A[t[e+4]]+A[t[e+5]]+"-"+A[t[e+6]]+A[t[e+7]]+"-"+A[t[e+8]]+A[t[e+9]]+"-"+A[t[e+10]]+A[t[e+11]]+A[t[e+12]]+A[t[e+13]]+A[t[e+14]]+A[t[e+15]]).toLowerCase()}(s)}const N=t=>{const e=[];for(const[i,s]of Object.entries(t))void 0!==s&&e.push(`${i}=${String(s)}`);return e.length?`?${e.join("&")}`:""};class L extends Error{code;data;constructor(t,e,i){super(t||"There was a problem. Please check your internet connection and try again."),this.name="SpaceApiError",this.stack=(new Error).stack,this.code=e,this.data=i}}let R="https://api.archilogic.com";function B(t){let e;if(t.secretAccessToken)e={type:"secret",secretAccessToken:t.secretAccessToken};else if(t.temporaryAccessToken||t.temporaryAccessTokenFunction)e={type:"temporary",temporaryAccessToken:t.temporaryAccessToken};else{if(!t.publishableAccessToken)throw new L("Programming error: token is not provided.",void 0,void 0);e={type:"publishable",publishableAccessToken:t.publishableAccessToken}}return t.sdkVersion&&(e.sdkVersion=t.sdkVersion),e}function k(t){return t.status>=200&&t.status<400?t:t.json().then(e=>{const i=e?.message||e?.error||e;switch(typeof i){case"string":return Promise.reject(new L(i,t.status,void 0));case"object":return Promise.reject(new L(i.message,t.status,i.data));default:return Promise.reject(new L(null,null,e))}})}async function F(t,e,i={},s){const r=new URL(R+e),n=function(t){const e=new Headers;switch(t.type){case"secret":e.set("authorization",`AL-Secret-Token ${t.secretAccessToken}`);break;case"temporary":e.set("authorization",`${t.temporaryAccessToken?.authorization}`)}return t.sdkVersion&&e.set("x-sdk-version",t.sdkVersion),e}(s);let o=!1;switch("publishable"===s.type&&r.searchParams.set("pubtoken",s.publishableAccessToken),t){case"GET":i&&"object"==typeof i&&Object.entries(i).forEach(([t,e])=>{void 0!==e&&r.searchParams.set(t,e.toString())});break;case"POST":case"PUT":case"PATCH":n.set("content-type","application/json"),o=!0;break;case"DELETE":break;default:return Promise.reject(new L("Programming error, unsupported method: "+t,void 0,void 0))}return fetch(r.toString(),{method:t,headers:n,body:o?JSON.stringify(i):void 0}).then(k,t=>{throw t}).then(t=>t.json()).catch(t=>Promise.reject(t))}class D{config;temporaryAccessTokenFunction;tempScopes=[{resource:"floor",action:"readPublic"},{resource:"floor",action:"readPrivate"},{resource:"floor",action:"queryPublic"},{resource:"floor",action:"queryPrivate"},{resource:"floor",action:"archive"},{resource:"customFields",action:"readPublic"},{resource:"customFields",action:"readPrivate"},{resource:"customFields",action:"write"}];temporaryAccessToken;temporaryAccessTokenPromise;durationSeconds=3600;constructor(t){this.config=B(t),(t.temporaryAccessToken||t.temporaryAccessTokenFunction)&&(this.temporaryAccessTokenFunction=t.temporaryAccessTokenFunction,this.temporaryAccessToken=t.temporaryAccessToken),t.temporaryAccessTokenScopes&&(this.tempScopes=t.temporaryAccessTokenScopes)}get isAccessTokenActive(){const t=/* @__PURE__ */(new Date).getTime()/1e3;return!!this.temporaryAccessToken&&this.temporaryAccessToken.expiresAt>t}async getTemporaryAccessToken(){if(this.isAccessTokenActive&&this.temporaryAccessToken)return this.temporaryAccessToken;this.temporaryAccessTokenPromise||(this.temporaryAccessTokenPromise=new Promise(async(t,e)=>{if(this.temporaryAccessTokenFunction&&(this.temporaryAccessToken=await this.temporaryAccessTokenFunction({scopes:this.tempScopes,durationSeconds:this.durationSeconds}),this.isAccessTokenActive&&t(this.temporaryAccessToken)),this.temporaryAccessToken){const t=/* @__PURE__ */new Date;t.setTime(1e3*this.temporaryAccessToken.expiresAt),e(new L(`Temporary access token expired at ${t.toString()}`,void 0,void 0))}else e(new L("Temporary access token not defined",void 0,void 0))}));try{return await this.temporaryAccessTokenPromise}catch(t){throw this.temporaryAccessTokenPromise=void 0,t}finally{this.isAccessTokenActive&&(this.temporaryAccessTokenPromise=void 0)}}async callSpaceAPI(t,e,i={},s=this.config){switch(s.type){case"secret":case"publishable":return F(t,e,i,s);case"temporary":{const r=await this.getTemporaryAccessToken();return F(t,e,i,{...s,temporaryAccessToken:r})}}}}class U{connection;constructor(t,e={}){this.connection=new D(t);for(const[i,s]of Object.entries(e))this[i]=s}async getTemporaryAccessToken(){return this.connection.getTemporaryAccessToken()}async createFloor(t){return this.connection.callSpaceAPI("POST","/v2/floor",t)}async duplicateFloor(t,e){const i=e.revisionId?`?revisionId=${e.revisionId}`:"";return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/duplicate${i}`)}async updateFloor(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/floor/${t}`,e)}async archiveFloor(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/archive`)}async unarchiveFloor(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/unarchive`)}async searchFloorsBasic(t){const{name:e,id:i,paginationInput:s,teamId:r}=t,n=((t,e,i,s)=>{const r={};return t&&(r.name={contains:`${t}`}),e&&(r.ids=[e]),s&&(r.team={id:{eq:s}}),{query:"query ($floorFilter: FloorFilter!, $paginationInput: PaginationInput) { getFloors(where: $floorFilter, paginationInput: $paginationInput) { floors { id name area createdAt updatedAt labels { name color } }, paginationInfo { currentPage limit offset totalCount totalPageCount} } }",variables:{floorFilter:r,paginationInput:i}}})(e,i,s,r);return this.connection.callSpaceAPI("POST","/graphql",n)}async searchFloorsAdvanced(t,e){const i=((t,e)=>({query:t,variables:{paginationInput:e}}))(t,e);return this.connection.callSpaceAPI("POST","/graphql",i)}async getFloorById(t,e=!1,i=!0,s=!1,r,n=!1){const o=N({includeAddress:s,includeRelations:i,includeCustomAttributes:n}),a=await this.connection.callSpaceAPI("GET",`/v2/floor/${t}${e?"/geo-json":""}${o}`);let l={};if(a.properties?.defaultLayoutId){const{layout:t,id:e,lastRevision:i,categories:s}=await this.getLayout(a.properties.defaultLayoutId,r);l={layout:{id:e,layout:t,lastRevision:i,categories:s}}}return{...a,...l}}async getFloorGeoJson(t,e){const i=N(e??{}),s=await this.connection.callSpaceAPI("GET",`/v2/floor/${t}/geo-json${i}`);let r;if(e?.includeAllElements){const t=s.features.find(t=>"Floor"===t.properties.resourceType);r=t?.properties.defaultLayoutId}else{r=s.properties.defaultLayoutId}if(r){const{layout:t,id:e,lastRevision:i,categories:n}=await this.getLayout(r);return{...s,layout:{id:e,layout:t,lastRevision:i,categories:n}}}return s}getFloorStatistics(t){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/statistics`)}queryFloors(t){return this.connection.callSpaceAPI("GET","/v2/floor",t)}async getAllFloors(t=!1,e=!1,i=!1,s,r){const n=t||i?1e3:1e4,o=await this.queryFloors({geometry:t,includeArchived:e,includeRelations:i,includeCustomAttributes:r,teamId:s,limit:n});let a=o.features||[];if(a.length<n)return o;for(;a?.length;)a=(await this.queryFloors({geometry:t,includeArchived:e,includeRelations:i,includeCustomAttributes:r,teamId:s,offset:o.features.length,limit:n})).features||[],o.features.push(...a);return o}getFloorplanImage(t,e){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/2d-image`,e)}getSceneStructure(t,e=!1){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/scene-structure`,{includeMetadata:e})}assignLabel(t,e){return this.connection.callSpaceAPI("PUT",`/v2/floor/${t}/label/${e}`)}removeLabel(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/floor/${t}/label/${e}`)}getSpaceById(t,e=!1,i=!0){const s=`?includeRelations=${i}`;return this.connection.callSpaceAPI("GET",`/v2/space/${t}/${e?"geo-json":""}${s}`)}querySpaces(t){return this.connection.callSpaceAPI("GET","/v2/space",t)}async getAllSpacesByFloorId(t,e=!1,i,s){const r=1e3,n=await this.querySpaces({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:s,limit:r});let o=n.features||[];if(o.length<r)return n;for(;o?.length;)o=(await this.querySpaces({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:s,offset:n.features.length,limit:r})).features||[],n.features.push(...o);return n}getAssetById(t,e=!1,i=!0,s=!1){const r=N({includeRelations:i,includeCustomAttributes:s});return this.connection.callSpaceAPI("GET",`/v2/asset/${t}/${e?"geo-json":""}${r}`)}queryAssets(t){return this.connection.callSpaceAPI("GET","/v2/asset",t)}async getAllAssets(t){const{limit:e=1e4,...i}=t,s=await this.queryAssets({...i,limit:e});let r=s.features||[];if(r.length<e)return s;for(;r?.length;)r=(await this.queryAssets({...t,offset:(t.offset||0)+s.features.length,limit:e})).features||[],s.features.push(...r);return s}getAllAssetsByFloorId(t,e=!1,i,s){return this.getAllAssets({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:s})}getAllAssetsBySpaceId(t,e=!1,i,s){return this.getAllAssets({spaceId:t,geometry:e,includeRelations:i,includeCustomAttributes:s})}getCustomField(t,e,i){return this.connection.callSpaceAPI("GET",`/v2/${t}/${e}/custom-field/${i}`)}getAllCustomFields(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t}/${e}/custom-field`)}setCustomField(t,e,i,s){return this.connection.callSpaceAPI("PUT",`/v2/${t}/${e}/custom-field/${i}`,s)}deleteCustomField(t,e,i){return this.connection.callSpaceAPI("DELETE",`/v2/${t}/${e}/custom-field/${i}`)}getLabel(t){return this.connection.callSpaceAPI("GET",`/v2/label/${t}`)}listLabels(){return this.connection.callSpaceAPI("GET","/v2/label/")}createOrUpdateLabel(t,e){return this.connection.callSpaceAPI("PUT",`/v2/label/${t}`,e)}deleteLabel(t){return this.connection.callSpaceAPI("DELETE",`/v2/label/${t}`)}getCustomAttributes(){return this.connection.callSpaceAPI("GET","/v2/custom-attributes")}getCustomAttribute(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/custom-attributes/${e}`)}getCustomAttributesForResourceType(t){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/custom-attributes`)}createCustomAttribute(t){const{resourceType:e,...i}=t;return this.connection.callSpaceAPI("POST",`/v2/${e.toLowerCase()}/custom-attributes`,i)}updateCustomAttribute(t){const{apiFieldName:e,resourceType:i,...s}=t;return this.connection.callSpaceAPI("PATCH",`/v2/${i.toLowerCase()}/custom-attributes/${e}`,s)}deleteCustomAttribute(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/${t.toLowerCase()}/custom-attributes/${e}`)}getCustomAttributeValues(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/${e}/custom-attributes`)}createCustomAttributeValue(t){const{apiFieldName:e,resourceId:i,resourceType:s,...r}=t;return this.connection.callSpaceAPI("POST",`/v2/${s.toLowerCase()}/${i}/custom-attributes/${e}`,r)}updateCustomAttributeValue(t){const{apiFieldName:e,resourceId:i,resourceType:s,...r}=t;return this.connection.callSpaceAPI("PATCH",`/v2/${s.toLowerCase()}/${i}/custom-attributes/${e}`,r)}deleteCustomAttributeValue(t,e,i){return this.connection.callSpaceAPI("DELETE",`/v2/${e.toLowerCase()}/${t}/custom-attributes/${i}`)}createLayout(t,e,i){return this.connection.callSpaceAPI("POST","/v2/layout",{floorId:t,layout:e,isDefault:i})}duplicateLayout(t,e){const i=N({revisionId:e});return this.connection.callSpaceAPI("POST",`/v2/layout/${t}/duplicate${i}`,{layoutId:t,revisionId:e})}getLayout(t,e){const i=N(e?{filter:e}:{});return this.connection.callSpaceAPI("GET",`/v2/layout/${t}${i}`)}getLayouts(t,e){const i=N({floorId:t,isDefault:e});return this.connection.callSpaceAPI("GET",`/v2/layout/${i}`)}updateLayout(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/layout/${t}`,e)}deleteLayout(t){return this.connection.callSpaceAPI("DELETE",`/v2/layout/${t}`)}createLayoutRevision(t,e){return this.connection.callSpaceAPI("POST",`/v2/layout/${t}/revisions`,e)}updateLayoutRevision(t,e,i){return this.connection.callSpaceAPI("PATCH",`/v2/layout/${t}/revisions/${e}`,i)}getLayoutRevisions(t,e){const i=N(e?{filter:e}:{});return this.connection.callSpaceAPI("GET",`/v2/layout/${t}/revisions${i}`)}getLayoutRevision(t,e){return this.connection.callSpaceAPI("GET",`/v2/layout/${t}/revisions/${e}`)}convertLanguageToQuery(t){return this.connection.callSpaceAPI("POST","/v2/language/graphql",t)}convertLanguageToAgentResponse(t){return this.connection.callSpaceAPI("POST","/v2/language/query-floors",t)}getDxf(t){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/dxf`)}getIfc(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/ifc`)}getGltf(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/gltf`)}getImdf(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/imdf`)}getImdfs(t){return this.connection.callSpaceAPI("POST","/v2/floor/imdf",t)}listExtensions(t){return this.connection.callSpaceAPI("GET","/v2/extensions",t)}createExtension(t){return this.connection.callSpaceAPI("POST","/v2/extensions",t)}updateExtension(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/extensions/${t}`,e)}deleteExtension(t){return this.connection.callSpaceAPI("DELETE",`/v2/extensions/${t}`)}listExtensionAccess(t){return this.connection.callSpaceAPI("GET",`/v2/extensions/${t}/access`)}grantExtensionAccess(t,e){return this.connection.callSpaceAPI("PUT",`/v2/extensions/${t}/access/${e}`)}revokeExtensionAccess(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/extensions/${t}/access/${e}`)}listBuildings(){return this.connection.callSpaceAPI("GET","/v2/buildings")}createBuilding(t){return this.connection.callSpaceAPI("POST","/v2/buildings",t)}getBuildingById(t){return this.connection.callSpaceAPI("GET",`/v2/buildings/${t}`)}updateBuilding(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/buildings/${t}`,e)}deleteBuilding(t){return this.connection.callSpaceAPI("DELETE",`/v2/buildings/${t}`)}}var G;(t=>{t.version="6.4.2.3",t.use_lines=!0;class e{m_Parent=null;m_polygon=[];m_Index=0;m_jointype=0;m_endtype=0;m_Children=[];IsOpen=!1;IsHoleNode(){for(var t=!0,e=this.m_Parent;null!==e;)t=!t,e=e.m_Parent;return t}ChildCount(){return this.m_Children.length}Contour(){return this.m_polygon}AddChild(t){var e=this.m_Children.length;this.m_Children.push(t),t.m_Parent=this,t.m_Index=e}GetNext(){return this.m_Children.length>0?this.m_Children[0]:this.GetNextSiblingUp()}GetNextSiblingUp(){return null===this.m_Parent?null:this.m_Index===this.m_Parent.m_Children.length-1?this.m_Parent.GetNextSiblingUp():this.m_Parent.m_Children[this.m_Index+1]}Children(){return this.m_Children}Parent(){return this.m_Parent}IsHole(){return this.IsHoleNode()}}t.PolyNode=e;t.PolyTree=class extends e{m_AllPolys=[];constructor(){super()}Clear(){for(var t=0,e=this.m_AllPolys.length;t<e;t++)this.m_AllPolys[t]=null;this.m_AllPolys.length=0,this.m_Children.length=0}GetFirst(){return this.m_Children.length>0?this.m_Children[0]:null}Total(){var t=this.m_AllPolys.length;return t>0&&this.m_Children[0]!==this.m_AllPolys[0]&&t--,t}},t.Clear=function(t){t.length=0},t.PI=3.141592653589793,t.PI2=6.283185307179586;t.FPoint=class{X=0;Y=0;constructor(...e){var i=e,s=e.length;if(this.X=0,this.Y=0,2===s)this.X=i[0],this.Y=i[1];else if(1===s)if(i[0]instanceof t.FPoint){var r=i[0];this.X=r.X,this.Y=r.Y}else{var n=i[0];this.X=n.X,this.Y=n.Y}else this.X=0,this.Y=0}static op_Equality(t,e){return t.X===e.X&&t.Y===e.Y}static op_Inequality(t,e){return t.X!==e.X||t.Y!==e.Y}};var i,s,r,n,o,a,l,h;t.FRect=class{left;top;right;bottom;constructor(...t){var e=t,i=t.length;if(4===i)this.left=e[0],this.top=e[1],this.right=e[2],this.bottom=e[3];else if(1===i){var s=e[0];this.left=s.left,this.top=s.top,this.right=s.right,this.bottom=s.bottom}else this.left=0,this.top=0,this.right=0,this.bottom=0}},(i=t.ClipType||(t.ClipType={}))[i.ctIntersection=0]="ctIntersection",i[i.ctUnion=1]="ctUnion",i[i.ctDifference=2]="ctDifference",i[i.ctXor=3]="ctXor",(s=t.PolyType||(t.PolyType={}))[s.ptSubject=0]="ptSubject",s[s.ptClip=1]="ptClip",(r=t.PolyFillType||(t.PolyFillType={}))[r.pftEvenOdd=0]="pftEvenOdd",r[r.pftNonZero=1]="pftNonZero",r[r.pftPositive=2]="pftPositive",r[r.pftNegative=3]="pftNegative",(n=t.JoinType||(t.JoinType={}))[n.jtSquare=0]="jtSquare",n[n.jtRound=1]="jtRound",n[n.jtMiter=2]="jtMiter",(o=t.EndType||(t.EndType={}))[o.etOpenSquare=0]="etOpenSquare",o[o.etOpenRound=1]="etOpenRound",o[o.etOpenButt=2]="etOpenButt",o[o.etClosedLine=3]="etClosedLine",o[o.etClosedPolygon=4]="etClosedPolygon",(a=t.EdgeSide||(t.EdgeSide={}))[a.esLeft=0]="esLeft",a[a.esRight=1]="esRight",(l=t.Direction||(t.Direction={}))[l.dRightToLeft=0]="dRightToLeft",l[l.dLeftToRight=1]="dLeftToRight",(h=t.NodeType||(t.NodeType={}))[h.ntAny=0]="ntAny",h[h.ntOpen=1]="ntOpen",h[h.ntClosed=2]="ntClosed";t.TEdge=class{Bot=new t.FPoint;Curr=new t.FPoint;Top=new t.FPoint;Delta=new t.FPoint;Dx=0;PolyTyp=0;Side=0;WindDelta=0;WindCnt=0;WindCnt2=0;OutIdx=0;Next=null;Prev=null;NextInLML=null;NextInAEL=null;PrevInAEL=null;NextInSEL=null;PrevInSEL=null};t.IntersectNode=class{Edge1=null;Edge2=null;Pt=new t.FPoint},t.Compare=function(t,e){var i=e.Pt.Y-t.Pt.Y;return i>0?1:i<0?-1:0};t.LocalMinima=class{Y=0;LeftBound=null;RightBound=null;Next=null};t.Scanbeam=class{Y=0;Next=null};t.Maxima=class{X=0;Next=null;Prev=null};t.OutRec=class{Idx=0;IsHole=!1;IsOpen=!1;FirstLeft=null;Pts=null;BottomPt=null;PolyNode=null};t.OutPt=class{Idx=0;Pt=new t.FPoint;Next=null;Prev=null};t.Join=class{OutPt1=null;OutPt2=null;OffPt=new t.FPoint};class u{m_MinimaList=null;m_CurrentLM=null;m_edges=new Array;m_HasOpenPaths=!1;PreserveCollinear=!1;m_Scanbeam=null;m_PolyOuts=null;m_ActiveEdges=null;static horizontal=-34e37;static Skip=-2;static Unassigned=-1;static tolerance=1e-20;static maxValue=Math.sqrt(Number.MAX_VALUE);static minValue=Math.sqrt(Number.MIN_VALUE);static near_zero(e){return e>-t.ClipperBase.tolerance&&e<t.ClipperBase.tolerance}static IsHorizontal(t){return 0===t.Delta.Y}PointIsVertex(e,i){var s=i;do{if(t.FPoint.op_Equality(s.Pt,e))return!0;s=s.Next}while(s!==i);return!1}PointOnLineSegment(t,e,i){return t.X===e.X&&t.Y===e.Y||t.X===i.X&&t.Y===i.Y||t.X>e.X==t.X<i.X&&t.Y>e.Y==t.Y<i.Y&&(t.X-e.X)*(i.Y-e.Y)===(i.X-e.X)*(t.Y-e.Y)}PointOnPolygon(t,e){for(var i=e;;){if(this.PointOnLineSegment(t,i.Pt,i.Next.Pt))return!0;if((i=i.Next)===e)break}return!1}static SlopesEqual(){var t,e,i,s,r,n,o=arguments,a=o.length;return 2===a?(e=o[1],(t=o[0]).Delta.Y*e.Delta.X===t.Delta.X*e.Delta.Y):3===a?(s=o[1],r=o[2],((i=o[0]).Y-s.Y)*(s.X-r.X)-(i.X-s.X)*(s.Y-r.Y)===0):(s=o[1],r=o[2],n=o[3],((i=o[0]).Y-s.Y)*(r.X-n.X)-(i.X-s.X)*(r.Y-n.Y)===0)}static SlopesEqual3(t,e){return t.Delta.Y*e.Delta.X===t.Delta.X*e.Delta.Y}static SlopesEqual4(t,e,i){return(t.Y-e.Y)*(e.X-i.X)-(t.X-e.X)*(e.Y-i.Y)===0}static SlopesEqual5(t,e,i,s){return(t.Y-e.Y)*(i.X-s.X)-(t.X-e.X)*(i.Y-s.Y)===0}Clear(){this.DisposeLocalMinimaList();for(var e=0,i=this.m_edges.length;e<i;++e){for(var s=0,r=this.m_edges[e].length;s<r;++s)this.m_edges[e][s]=null;t.Clear(this.m_edges[e])}t.Clear(this.m_edges),this.m_HasOpenPaths=!1}DisposeLocalMinimaList(){for(;null!==this.m_MinimaList;){var t=this.m_MinimaList.Next;this.m_MinimaList=null,this.m_MinimaList=t}this.m_CurrentLM=null}RangeTest(e){(e.X>t.ClipperBase.maxValue||e.X<-t.ClipperBase.maxValue||e.Y>t.ClipperBase.maxValue||e.Y<-t.ClipperBase.maxValue||e.X>0&&e.X<t.ClipperBase.minValue||e.Y>0&&e.Y<t.ClipperBase.minValue||e.X<0&&e.X>-t.ClipperBase.minValue||e.Y<0&&e.Y>-t.ClipperBase.minValue)&&t.Error("Coordinate outside allowed range in RangeTest().")}InitEdge(t,e,i,s){t.Next=e,t.Prev=i,t.Curr.X=s.X,t.Curr.Y=s.Y,t.OutIdx=-1}InitEdge2(t,e){t.Curr.Y>=t.Next.Curr.Y?(t.Bot.X=t.Curr.X,t.Bot.Y=t.Curr.Y,t.Top.X=t.Next.Curr.X,t.Top.Y=t.Next.Curr.Y):(t.Top.X=t.Curr.X,t.Top.Y=t.Curr.Y,t.Bot.X=t.Next.Curr.X,t.Bot.Y=t.Next.Curr.Y),this.SetDx(t),t.PolyTyp=e}FindNextLocMin(e){for(var i;;){for(;t.FPoint.op_Inequality(e.Bot,e.Prev.Bot)||t.FPoint.op_Equality(e.Curr,e.Top);)e=e.Next;if(e.Dx!==t.ClipperBase.horizontal&&e.Prev.Dx!==t.ClipperBase.horizontal)break;for(;e.Prev.Dx===t.ClipperBase.horizontal;)e=e.Prev;for(i=e;e.Dx===t.ClipperBase.horizontal;)e=e.Next;if(e.Top.Y!==e.Prev.Bot.Y){i.Prev.Bot.X<e.Bot.X&&(e=i);break}}return e}ProcessBound(e,i){var s,r,n=e;if(n.OutIdx===t.ClipperBase.Skip){if(e=n,i){for(;e.Top.Y===e.Next.Bot.Y;)e=e.Next;for(;e!==n&&e.Dx===t.ClipperBase.horizontal;)e=e.Prev}else{for(;e.Top.Y===e.Prev.Bot.Y;)e=e.Prev;for(;e!==n&&e.Dx===t.ClipperBase.horizontal;)e=e.Next}if(e===n)n=i?e.Next:e.Prev;else{e=i?n.Next:n.Prev;var o=new t.LocalMinima;o.Next=null,o.Y=e.Bot.Y,o.LeftBound=null,o.RightBound=e,e.WindDelta=0,n=this.ProcessBound(e,i),this.InsertLocalMinima(o)}return n}if(e.Dx===t.ClipperBase.horizontal&&((s=i?e.Prev:e.Next).Dx===t.ClipperBase.horizontal?s.Bot.X!==e.Bot.X&&s.Top.X!==e.Bot.X&&this.ReverseHorizontal(e):s.Bot.X!==e.Bot.X&&this.ReverseHorizontal(e)),s=e,i){for(;n.Top.Y===n.Next.Bot.Y&&n.Next.OutIdx!==t.ClipperBase.Skip;)n=n.Next;if(n.Dx===t.ClipperBase.horizontal&&n.Next.OutIdx!==t.ClipperBase.Skip){for(r=n;r.Prev.Dx===t.ClipperBase.horizontal;)r=r.Prev;r.Prev.Top.X>n.Next.Top.X&&(n=r.Prev)}for(;e!==n;)e.NextInLML=e.Next,e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Prev.Top.X&&this.ReverseHorizontal(e),e=e.Next;e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Prev.Top.X&&this.ReverseHorizontal(e),n=n.Next}else{for(;n.Top.Y===n.Prev.Bot.Y&&n.Prev.OutIdx!==t.ClipperBase.Skip;)n=n.Prev;if(n.Dx===t.ClipperBase.horizontal&&n.Prev.OutIdx!==t.ClipperBase.Skip){for(r=n;r.Next.Dx===t.ClipperBase.horizontal;)r=r.Next;(r.Next.Top.X===n.Prev.Top.X||r.Next.Top.X>n.Prev.Top.X)&&(n=r.Next)}for(;e!==n;)e.NextInLML=e.Prev,e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Next.Top.X&&this.ReverseHorizontal(e),e=e.Prev;e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Next.Top.X&&this.ReverseHorizontal(e),n=n.Prev}return n}AddPath(e,i,s){t.use_lines?s||1!==i||t.Error("AddPath: Open paths must be subject."):s||t.Error("AddPath: Open paths have been disabled.");var r=e.length-1;if(s)for(;r>0&&t.FPoint.op_Equality(e[r],e[0]);)--r;for(;r>0&&t.FPoint.op_Equality(e[r],e[r-1]);)--r;if(s&&r<2||!s&&r<1)return!1;for(var n=new Array,o=0;o<=r;o++)n.push(new t.TEdge);var a=!0;n[1].Curr.X=e[1].X,n[1].Curr.Y=e[1].Y,this.RangeTest(e[0]),this.RangeTest(e[r]),this.InitEdge(n[0],n[1],n[r],e[0]),this.InitEdge(n[r],n[0],n[r-1],e[r]);for(o=r-1;o>=1;--o)this.RangeTest(e[o]),this.InitEdge(n[o],n[o+1],n[o-1],e[o]);for(var l,h=n[0],u=h,c=h;;)if(u.Curr!==u.Next.Curr||!s&&u.Next===h){if(u.Prev===u.Next)break;if(!s||!t.ClipperBase.SlopesEqual4(u.Prev.Curr,u.Curr,u.Next.Curr)||this.PreserveCollinear&&this.Pt2IsBetweenPt1AndPt3(u.Prev.Curr,u.Curr,u.Next.Curr)){if((u=u.Next)===c||!s&&u.Next===h)break}else u===h&&(h=u.Next),c=u=(u=this.RemoveEdge(u)).Prev}else{if(u===u.Next)break;u===h&&(h=u.Next),c=u=this.RemoveEdge(u)}if(!s&&u===u.Next||s&&u.Prev===u.Next)return!1;s||(this.m_HasOpenPaths=!0,h.Prev.OutIdx=t.ClipperBase.Skip),u=h;do{this.InitEdge2(u,i),u=u.Next,a&&u.Curr.Y!==h.Curr.Y&&(a=!1)}while(u!==h);if(a){if(s)return!1;for(u.Prev.OutIdx=t.ClipperBase.Skip,(p=new t.LocalMinima).Next=null,p.Y=u.Bot.Y,p.LeftBound=null,p.RightBound=u,p.RightBound.Side=1,p.RightBound.WindDelta=0;u.Bot.X!==u.Prev.Top.X&&this.ReverseHorizontal(u),u.Next.OutIdx!==t.ClipperBase.Skip;)u.NextInLML=u.Next,u=u.Next;return this.InsertLocalMinima(p),this.m_edges.push(n),!0}this.m_edges.push(n);var d=null;for(t.FPoint.op_Equality(u.Prev.Bot,u.Prev.Top)&&(u=u.Next);(u=this.FindNextLocMin(u))!==d;){var p;null===d&&(d=u),(p=new t.LocalMinima).Next=null,p.Y=u.Bot.Y,u.Dx<u.Prev.Dx?(p.LeftBound=u.Prev,p.RightBound=u,l=!1):(p.LeftBound=u,p.RightBound=u.Prev,l=!0),p.LeftBound.Side=0,p.RightBound.Side=1,s?p.LeftBound.Next===p.RightBound?p.LeftBound.WindDelta=-1:p.LeftBound.WindDelta=1:p.LeftBound.WindDelta=0,p.RightBound.WindDelta=-p.LeftBound.WindDelta,(u=this.ProcessBound(p.LeftBound,l)).OutIdx===t.ClipperBase.Skip&&(u=this.ProcessBound(u,l));var f=this.ProcessBound(p.RightBound,!l);f.OutIdx===t.ClipperBase.Skip&&(f=this.ProcessBound(f,!l)),p.LeftBound.OutIdx===t.ClipperBase.Skip?p.LeftBound=null:p.RightBound.OutIdx===t.ClipperBase.Skip&&(p.RightBound=null),this.InsertLocalMinima(p),l||(u=f)}return!0}AddPaths(t,e,i){for(var s=!1,r=0,n=t.length;r<n;++r)this.AddPath(t[r],e,i)&&(s=!0);return s}Pt2IsBetweenPt1AndPt3(e,i,s){return!(t.FPoint.op_Equality(e,s)||t.FPoint.op_Equality(e,i)||t.FPoint.op_Equality(s,i))&&(e.X!==s.X?i.X>e.X==i.X<s.X:i.Y>e.Y==i.Y<s.Y)}RemoveEdge(t){t.Prev.Next=t.Next,t.Next.Prev=t.Prev;var e=t.Next;return t.Prev=null,e}SetDx(e){e.Delta.X=e.Top.X-e.Bot.X,e.Delta.Y=e.Top.Y-e.Bot.Y,0===e.Delta.Y?e.Dx=t.ClipperBase.horizontal:e.Dx=e.Delta.X/e.Delta.Y}InsertLocalMinima(t){if(null===this.m_MinimaList)this.m_MinimaList=t;else if(t.Y>=this.m_MinimaList.Y)t.Next=this.m_MinimaList,this.m_MinimaList=t;else{for(var e=this.m_MinimaList;null!==e.Next&&t.Y<e.Next.Y;)e=e.Next;t.Next=e.Next,e.Next=t}}PopLocalMinima(t,e){return e.v=this.m_CurrentLM,null!==this.m_CurrentLM&&this.m_CurrentLM.Y===t&&(this.m_CurrentLM=this.m_CurrentLM.Next,!0)}ReverseHorizontal(t){var e=t.Top.X;t.Top.X=t.Bot.X,t.Bot.X=e}Reset(){if(this.m_CurrentLM=this.m_MinimaList,null!==this.m_CurrentLM){this.m_Scanbeam=null;for(var e=this.m_MinimaList;null!==e;){this.InsertScanbeam(e.Y);var i=e.LeftBound;null!==i&&(i.Curr.X=i.Bot.X,i.Curr.Y=i.Bot.Y,i.OutIdx=t.ClipperBase.Unassigned),null!==(i=e.RightBound)&&(i.Curr.X=i.Bot.X,i.Curr.Y=i.Bot.Y,i.OutIdx=t.ClipperBase.Unassigned),e=e.Next}this.m_ActiveEdges=null}}InsertScanbeam(e){if(null===this.m_Scanbeam)this.m_Scanbeam=new t.Scanbeam,this.m_Scanbeam.Next=null,this.m_Scanbeam.Y=e;else if(e>this.m_Scanbeam.Y){var i=new t.Scanbeam;i.Y=e,i.Next=this.m_Scanbeam,this.m_Scanbeam=i}else{for(var s=this.m_Scanbeam;null!==s.Next&&e<=s.Next.Y;)s=s.Next;if(e===s.Y)return;var r=new t.Scanbeam;r.Y=e,r.Next=s.Next,s.Next=r}}PopScanbeam(t){return null===this.m_Scanbeam?(t.v=0,!1):(t.v=this.m_Scanbeam.Y,this.m_Scanbeam=this.m_Scanbeam.Next,!0)}LocalMinimaPending(){return null!==this.m_CurrentLM}CreateOutRec(){var e=new t.OutRec;return e.Idx=t.ClipperBase.Unassigned,e.IsHole=!1,e.IsOpen=!1,e.FirstLeft=null,e.Pts=null,e.BottomPt=null,e.PolyNode=null,this.m_PolyOuts.push(e),e.Idx=this.m_PolyOuts.length-1,e}DisposeOutRec(t){var e=this.m_PolyOuts[t];e.Pts=null,e=null,this.m_PolyOuts[t]=null}UpdateEdgeIntoAEL(e){null===e.NextInLML&&t.Error("UpdateEdgeIntoAEL: invalid call");var i=e.PrevInAEL,s=e.NextInAEL;return e.NextInLML.OutIdx=e.OutIdx,null!==i?i.NextInAEL=e.NextInLML:this.m_ActiveEdges=e.NextInLML,null!==s&&(s.PrevInAEL=e.NextInLML),e.NextInLML.Side=e.Side,e.NextInLML.WindDelta=e.WindDelta,e.NextInLML.WindCnt=e.WindCnt,e.NextInLML.WindCnt2=e.WindCnt2,(e=e.NextInLML).Curr.X=e.Bot.X,e.Curr.Y=e.Bot.Y,e.PrevInAEL=i,e.NextInAEL=s,t.ClipperBase.IsHorizontal(e)||this.InsertScanbeam(e.Top.Y),e}SwapPositionsInAEL(t,e){if(t.NextInAEL!==t.PrevInAEL&&e.NextInAEL!==e.PrevInAEL){if(t.NextInAEL===e){var i=e.NextInAEL;null!==i&&(i.PrevInAEL=t);var s=t.PrevInAEL;null!==s&&(s.NextInAEL=e),e.PrevInAEL=s,e.NextInAEL=t,t.PrevInAEL=e,t.NextInAEL=i}else if(e.NextInAEL===t){var r=t.NextInAEL;null!==r&&(r.PrevInAEL=e);var n=e.PrevInAEL;null!==n&&(n.NextInAEL=t),t.PrevInAEL=n,t.NextInAEL=e,e.PrevInAEL=t,e.NextInAEL=r}else{var o=t.NextInAEL,a=t.PrevInAEL;t.NextInAEL=e.NextInAEL,null!==t.NextInAEL&&(t.NextInAEL.PrevInAEL=t),t.PrevInAEL=e.PrevInAEL,null!==t.PrevInAEL&&(t.PrevInAEL.NextInAEL=t),e.NextInAEL=o,null!==e.NextInAEL&&(e.NextInAEL.PrevInAEL=e),e.PrevInAEL=a,null!==e.PrevInAEL&&(e.PrevInAEL.NextInAEL=e)}null===t.PrevInAEL?this.m_ActiveEdges=t:null===e.PrevInAEL&&(this.m_ActiveEdges=e)}}DeleteFromAEL(t){var e=t.PrevInAEL,i=t.NextInAEL;null===e&&null===i&&t!==this.m_ActiveEdges||(null!==e?e.NextInAEL=i:this.m_ActiveEdges=i,null!==i&&(i.PrevInAEL=e),t.NextInAEL=null,t.PrevInAEL=null)}}t.ClipperBase=u;t.Clipper=class extends u{m_SortedEdges=null;m_IntersectList=null;m_IntersectNodeComparer=null;m_ExecuteLocked=!1;m_ClipFillType=0;m_SubjFillType=0;m_Joins=null;m_GhostJoins=null;m_UsingPolyTree=!1;ReverseSolution=!1;StrictlySimple=!1;m_ClipType=0;m_Maxima=null;ZFillFunction;constructor(e){super(),void 0===e&&(e=0),this.m_PolyOuts=null,this.m_Scanbeam=null,this.m_ActiveEdges=null,this.m_Scanbeam=null,this.m_Maxima=null,this.m_ActiveEdges=null,this.m_SortedEdges=null,this.m_IntersectList=new Array,this.m_IntersectNodeComparer=t.Compare,this.m_ExecuteLocked=!1,this.m_UsingPolyTree=!1,this.m_PolyOuts=new Array,this.m_Joins=new Array,this.m_GhostJoins=new Array,this.ReverseSolution=!!(1&e),this.StrictlySimple=!!(2&e),this.PreserveCollinear=!!(4&e)}static ioReverseSolution=1;static ioStrictlySimple=2;static ioPreserveCollinear=4;Clear(){0!==this.m_edges.length&&(this.DisposeAllPolyPts(),super.Clear())}InsertMaxima(e){var i=new t.Maxima;if(i.X=e,null===this.m_Maxima)this.m_Maxima=i,this.m_Maxima.Next=null,this.m_Maxima.Prev=null;else if(e<this.m_Maxima.X)i.Next=this.m_Maxima,i.Prev=null,this.m_Maxima=i;else{for(var s=this.m_Maxima;null!==s.Next&&e>=s.Next.X;)s=s.Next;if(e===s.X)return;i.Next=s.Next,i.Prev=s,null!==s.Next&&(s.Next.Prev=i),s.Next=i}}Execute(...e){var i=e,s=i.length,r=i[1]instanceof t.PolyTree;if(4===s&&!r){var n=i[0],o=i[1],a=i[2],l=i[3];if(this.m_ExecuteLocked)return!1;this.m_HasOpenPaths&&t.Error("Error: PolyTree struct is needed for open path clipping."),this.m_ExecuteLocked=!0,t.Clear(o),this.m_SubjFillType=a,this.m_ClipFillType=l,this.m_ClipType=n,this.m_UsingPolyTree=!1;try{(u=this.ExecuteInternal())&&this.BuildResult(o)}finally{this.DisposeAllPolyPts(),this.m_ExecuteLocked=!1}return u}if(4===s&&r){n=i[0];var h=i[1];a=i[2],l=i[3];if(this.m_ExecuteLocked)return!1;this.m_ExecuteLocked=!0,this.m_SubjFillType=a,this.m_ClipFillType=l,this.m_ClipType=n,this.m_UsingPolyTree=!0;try{var u;(u=this.ExecuteInternal())&&this.BuildResult2(h)}finally{this.DisposeAllPolyPts(),this.m_ExecuteLocked=!1}return u}if(2===s&&!r){n=i[0],o=i[1];return this.Execute(n,o,0,0)}if(2===s&&r){n=i[0],h=i[1];return this.Execute(n,h,0,0)}}FixHoleLinkage(t){if(null!==t.FirstLeft&&(t.IsHole===t.FirstLeft.IsHole||null===t.FirstLeft.Pts)){for(var e=t.FirstLeft;null!==e&&(e.IsHole===t.IsHole||null===e.Pts);)e=e.FirstLeft;t.FirstLeft=e}}ExecuteInternal(){try{this.Reset(),this.m_SortedEdges=null,this.m_Maxima=null;var t,e,i,s={},r={};if(!this.PopScanbeam(s))return!1;for(this.InsertLocalMinimaIntoAEL(s.v);this.PopScanbeam(r)||this.LocalMinimaPending();){if(this.ProcessHorizontals(),this.m_GhostJoins.length=0,!this.ProcessIntersections(r.v))return!1;this.ProcessEdgesAtTopOfScanbeam(r.v),s.v=r.v,this.InsertLocalMinimaIntoAEL(s.v)}for(e=0,i=this.m_PolyOuts.length;e<i;e++)null===(t=this.m_PolyOuts[e]).Pts||t.IsOpen||(t.IsHole^this.ReverseSolution)==this.Area$1(t)>0&&this.ReversePolyPtLinks(t.Pts);for(this.JoinCommonEdges(),e=0,i=this.m_PolyOuts.length;e<i;e++)null!==(t=this.m_PolyOuts[e]).Pts&&(t.IsOpen?this.FixupOutPolyline(t):this.FixupOutPolygon(t));return this.StrictlySimple&&this.DoSimplePolygons(),!0}finally{this.m_Joins.length=0,this.m_GhostJoins.length=0}}DisposeAllPolyPts(){for(var e=0,i=this.m_PolyOuts.length;e<i;++e)this.DisposeOutRec(e);t.Clear(this.m_PolyOuts)}AddJoin(e,i,s){var r=new t.Join;r.OutPt1=e,r.OutPt2=i,r.OffPt.X=s.X,r.OffPt.Y=s.Y,this.m_Joins.push(r)}AddGhostJoin(e,i){var s=new t.Join;s.OutPt1=e,s.OffPt.X=i.X,s.OffPt.Y=i.Y,this.m_GhostJoins.push(s)}InsertLocalMinimaIntoAEL(e){for(var i,s,r={};this.PopLocalMinima(e,r);){i=r.v.LeftBound,s=r.v.RightBound;var n=null;if(null===i?(this.InsertEdgeIntoAEL(s,null),this.SetWindingCount(s),this.IsContributing(s)&&(n=this.AddOutPt(s,s.Bot))):null===s?(this.InsertEdgeIntoAEL(i,null),this.SetWindingCount(i),this.IsContributing(i)&&(n=this.AddOutPt(i,i.Bot)),this.InsertScanbeam(i.Top.Y)):(this.InsertEdgeIntoAEL(i,null),this.InsertEdgeIntoAEL(s,i),this.SetWindingCount(i),s.WindCnt=i.WindCnt,s.WindCnt2=i.WindCnt2,this.IsContributing(i)&&(n=this.AddLocalMinPoly(i,s,i.Bot)),this.InsertScanbeam(i.Top.Y)),null!==s&&(t.ClipperBase.IsHorizontal(s)?(null!==s.NextInLML&&this.InsertScanbeam(s.NextInLML.Top.Y),this.AddEdgeToSEL(s)):this.InsertScanbeam(s.Top.Y)),null!==i&&null!==s){if(null!==n&&t.ClipperBase.IsHorizontal(s)&&this.m_GhostJoins.length>0&&0!==s.WindDelta)for(var o=0,a=this.m_GhostJoins.length;o<a;o++){var l=this.m_GhostJoins[o];this.HorzSegmentsOverlap(l.OutPt1.Pt.X,l.OffPt.X,s.Bot.X,s.Top.X)&&this.AddJoin(l.OutPt1,n,l.OffPt)}if(i.OutIdx>=0&&null!==i.PrevInAEL&&i.PrevInAEL.Curr.X===i.Bot.X&&i.PrevInAEL.OutIdx>=0&&t.ClipperBase.SlopesEqual5(i.PrevInAEL.Curr,i.PrevInAEL.Top,i.Curr,i.Top)&&0!==i.WindDelta&&0!==i.PrevInAEL.WindDelta){var h=this.AddOutPt(i.PrevInAEL,i.Bot);this.AddJoin(n,h,i.Top)}if(i.NextInAEL!==s){if(s.OutIdx>=0&&s.PrevInAEL.OutIdx>=0&&t.ClipperBase.SlopesEqual5(s.PrevInAEL.Curr,s.PrevInAEL.Top,s.Curr,s.Top)&&0!==s.WindDelta&&0!==s.PrevInAEL.WindDelta){h=this.AddOutPt(s.PrevInAEL,s.Bot);this.AddJoin(n,h,s.Top)}var u=i.NextInAEL;if(null!==u)for(;u!==s;)this.IntersectEdges(s,u,i.Curr),u=u.NextInAEL}}}}InsertEdgeIntoAEL(t,e){if(null===this.m_ActiveEdges)t.PrevInAEL=null,t.NextInAEL=null,this.m_ActiveEdges=t;else if(null===e&&this.E2InsertsBeforeE1(this.m_ActiveEdges,t))t.PrevInAEL=null,t.NextInAEL=this.m_ActiveEdges,this.m_ActiveEdges.PrevInAEL=t,this.m_ActiveEdges=t;else{for(null===e&&(e=this.m_ActiveEdges);null!==e.NextInAEL&&!this.E2InsertsBeforeE1(e.NextInAEL,t);)e=e.NextInAEL;t.NextInAEL=e.NextInAEL,null!==e.NextInAEL&&(e.NextInAEL.PrevInAEL=t),t.PrevInAEL=e,e.NextInAEL=t}}E2InsertsBeforeE1(e,i){return i.Curr.X===e.Curr.X?i.Top.Y>e.Top.Y?i.Top.X<t.Clipper.TopX(e,i.Top.Y):e.Top.X>t.Clipper.TopX(i,e.Top.Y):i.Curr.X<e.Curr.X}IsEvenOddFillType(t){return 0===t.PolyTyp?0===this.m_SubjFillType:0===this.m_ClipFillType}IsEvenOddAltFillType(t){return 0===t.PolyTyp?0===this.m_ClipFillType:0===this.m_SubjFillType}IsContributing(t){var e,i;switch(0===t.PolyTyp?(e=this.m_SubjFillType,i=this.m_ClipFillType):(e=this.m_ClipFillType,i=this.m_SubjFillType),e){case 0:if(0===t.WindDelta&&1!==t.WindCnt)return!1;break;case 1:if(1!==Math.abs(t.WindCnt))return!1;break;case 2:if(1!==t.WindCnt)return!1;break;default:if(-1!==t.WindCnt)return!1}switch(this.m_ClipType){case 0:switch(i){case 0:case 1:return 0!==t.WindCnt2;case 2:return t.WindCnt2>0;default:return t.WindCnt2<0}case 1:switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}case 2:if(0===t.PolyTyp)switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}else switch(i){case 0:case 1:return 0!==t.WindCnt2;case 2:return t.WindCnt2>0;default:return t.WindCnt2<0}case 3:if(0!==t.WindDelta)return!0;switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}}return!0}SetWindingCount(t){for(var e=t.PrevInAEL;null!==e&&(e.PolyTyp!==t.PolyTyp||0===e.WindDelta);)e=e.PrevInAEL;if(null===e){var i=0===t.PolyTyp?this.m_SubjFillType:this.m_ClipFillType;0===t.WindDelta?t.WindCnt=3===i?-1:1:t.WindCnt=t.WindDelta,t.WindCnt2=0,e=this.m_ActiveEdges}else if(0===t.WindDelta&&1!==this.m_ClipType)t.WindCnt=1,t.WindCnt2=e.WindCnt2,e=e.NextInAEL;else if(this.IsEvenOddFillType(t)){if(0===t.WindDelta){for(var s=!0,r=e.PrevInAEL;null!==r;)r.PolyTyp===e.PolyTyp&&0!==r.WindDelta&&(s=!s),r=r.PrevInAEL;t.WindCnt=s?0:1}else t.WindCnt=t.WindDelta;t.WindCnt2=e.WindCnt2,e=e.NextInAEL}else e.WindCnt*e.WindDelta<0?Math.abs(e.WindCnt)>1?e.WindDelta*t.WindDelta<0?t.WindCnt=e.WindCnt:t.WindCnt=e.WindCnt+t.WindDelta:t.WindCnt=0===t.WindDelta?1:t.WindDelta:0===t.WindDelta?t.WindCnt=e.WindCnt<0?e.WindCnt-1:e.WindCnt+1:e.WindDelta*t.WindDelta<0?t.WindCnt=e.WindCnt:t.WindCnt=e.WindCnt+t.WindDelta,t.WindCnt2=e.WindCnt2,e=e.NextInAEL;if(this.IsEvenOddAltFillType(t))for(;e!==t;)0!==e.WindDelta&&(t.WindCnt2=0===t.WindCnt2?1:0),e=e.NextInAEL;else for(;e!==t;)t.WindCnt2+=e.WindDelta,e=e.NextInAEL}AddEdgeToSEL(t){null===this.m_SortedEdges?(this.m_SortedEdges=t,t.PrevInSEL=null,t.NextInSEL=null):(t.NextInSEL=this.m_SortedEdges,t.PrevInSEL=null,this.m_SortedEdges.PrevInSEL=t,this.m_SortedEdges=t)}PopEdgeFromSEL(t){if(t.v=this.m_SortedEdges,null===t.v)return!1;var e=t.v;return this.m_SortedEdges=t.v.NextInSEL,null!==this.m_SortedEdges&&(this.m_SortedEdges.PrevInSEL=null),e.NextInSEL=null,e.PrevInSEL=null,!0}CopyAELToSEL(){var t=this.m_ActiveEdges;for(this.m_SortedEdges=t;null!==t;)t.PrevInSEL=t.PrevInAEL,t.NextInSEL=t.NextInAEL,t=t.NextInAEL}SwapPositionsInSEL(t,e){if(!(null===t.NextInSEL&&null===t.PrevInSEL||null===e.NextInSEL&&null===e.PrevInSEL)){if(t.NextInSEL===e)null!==(i=e.NextInSEL)&&(i.PrevInSEL=t),null!==(s=t.PrevInSEL)&&(s.NextInSEL=e),e.PrevInSEL=s,e.NextInSEL=t,t.PrevInSEL=e,t.NextInSEL=i;else if(e.NextInSEL===t){null!==(i=t.NextInSEL)&&(i.PrevInSEL=e),null!==(s=e.PrevInSEL)&&(s.NextInSEL=t),t.PrevInSEL=s,t.NextInSEL=e,e.PrevInSEL=t,e.NextInSEL=i}else{var i=t.NextInSEL,s=t.PrevInSEL;t.NextInSEL=e.NextInSEL,null!==t.NextInSEL&&(t.NextInSEL.PrevInSEL=t),t.PrevInSEL=e.PrevInSEL,null!==t.PrevInSEL&&(t.PrevInSEL.NextInSEL=t),e.NextInSEL=i,null!==e.NextInSEL&&(e.NextInSEL.PrevInSEL=e),e.PrevInSEL=s,null!==e.PrevInSEL&&(e.PrevInSEL.NextInSEL=e)}null===t.PrevInSEL?this.m_SortedEdges=t:null===e.PrevInSEL&&(this.m_SortedEdges=e)}}AddLocalMaxPoly(t,e,i){this.AddOutPt(t,i),0===e.WindDelta&&this.AddOutPt(e,i),t.OutIdx===e.OutIdx?(t.OutIdx=-1,e.OutIdx=-1):t.OutIdx<e.OutIdx?this.AppendPolygon(t,e):this.AppendPolygon(e,t)}AddLocalMinPoly(e,i,s){var r,n,o;if(t.ClipperBase.IsHorizontal(i)||e.Dx>i.Dx?(r=this.AddOutPt(e,s),i.OutIdx=e.OutIdx,e.Side=0,i.Side=1,o=(n=e).PrevInAEL===i?i.PrevInAEL:n.PrevInAEL):(r=this.AddOutPt(i,s),e.OutIdx=i.OutIdx,e.Side=1,i.Side=0,o=(n=i).PrevInAEL===e?e.PrevInAEL:n.PrevInAEL),null!==o&&o.OutIdx>=0&&o.Top.Y<s.Y&&n.Top.Y<s.Y){var a=t.Clipper.TopX(o,s.Y),l=t.Clipper.TopX(n,s.Y);if(a===l&&0!==n.WindDelta&&0!==o.WindDelta&&t.ClipperBase.SlopesEqual5(new t.FPoint(a,s.Y),o.Top,new t.FPoint(l,s.Y),n.Top)){var h=this.AddOutPt(o,s);this.AddJoin(r,h,n.Top)}}return r}AddOutPt(e,i){if(e.OutIdx<0){let r=this.CreateOutRec();r.IsOpen=0===e.WindDelta;var s=new t.OutPt;return r.Pts=s,s.Idx=r.Idx,s.Pt.X=i.X,s.Pt.Y=i.Y,s.Next=s,s.Prev=s,r.IsOpen||this.SetHoleState(e,r),e.OutIdx=r.Idx,s}{let o=this.m_PolyOuts[e.OutIdx];var r=o.Pts,n=0===e.Side;return n&&t.FPoint.op_Equality(i,r.Pt)?r:!n&&t.FPoint.op_Equality(i,r.Prev.Pt)?r.Prev:((s=new t.OutPt).Idx=o.Idx,s.Pt.X=i.X,s.Pt.Y=i.Y,s.Next=r,s.Prev=r.Prev,s.Prev.Next=s,r.Prev=s,n&&(o.Pts=s),s)}}GetLastOutPt(t){var e=this.m_PolyOuts[t.OutIdx];return 0===t.Side?e.Pts:e.Pts.Prev}SwapPoints(e,i){var s=new t.FPoint(e.Value);e.Value.X=i.Value.X,e.Value.Y=i.Value.Y,i.Value.X=s.X,i.Value.Y=s.Y}HorzSegmentsOverlap(t,e,i,s){var r;return t>e&&(r=t,t=e,e=r),i>s&&(r=i,i=s,s=r),t<s&&i<e}SetHoleState(t,e){for(var i=t.PrevInAEL,s=null;null!==i;)i.OutIdx>=0&&0!==i.WindDelta&&(null===s?s=i:s.OutIdx===i.OutIdx&&(s=null)),i=i.PrevInAEL;null===s?(e.FirstLeft=null,e.IsHole=!1):(e.FirstLeft=this.m_PolyOuts[s.OutIdx],e.IsHole=!e.FirstLeft.IsHole)}GetDx(e,i){return e.Y===i.Y?t.ClipperBase.horizontal:(i.X-e.X)/(i.Y-e.Y)}FirstIsBottomPt(e,i){for(var s=e.Prev;t.FPoint.op_Equality(s.Pt,e.Pt)&&s!==e;)s=s.Prev;var r=Math.abs(this.GetDx(e.Pt,s.Pt));for(s=e.Next;t.FPoint.op_Equality(s.Pt,e.Pt)&&s!==e;)s=s.Next;var n=Math.abs(this.GetDx(e.Pt,s.Pt));for(s=i.Prev;t.FPoint.op_Equality(s.Pt,i.Pt)&&s!==i;)s=s.Prev;var o=Math.abs(this.GetDx(i.Pt,s.Pt));for(s=i.Next;t.FPoint.op_Equality(s.Pt,i.Pt)&&s!==i;)s=s.Next;var a=Math.abs(this.GetDx(i.Pt,s.Pt));return Math.max(r,n)===Math.max(o,a)&&Math.min(r,n)===Math.min(o,a)?this.Area(e)>0:r>=o&&r>=a||n>=o&&n>=a}GetBottomPt(e){for(var i=null,s=e.Next;s!==e;)s.Pt.Y>e.Pt.Y?(e=s,i=null):s.Pt.Y===e.Pt.Y&&s.Pt.X<=e.Pt.X&&(s.Pt.X<e.Pt.X?(i=null,e=s):s.Next!==e&&s.Prev!==e&&(i=s)),s=s.Next;if(null!==i)for(;i!==s;)for(this.FirstIsBottomPt(s,i)||(e=i),i=i.Next;t.FPoint.op_Inequality(i.Pt,e.Pt);)i=i.Next;return e}GetLowermostRec(t,e){null===t.BottomPt&&(t.BottomPt=this.GetBottomPt(t.Pts)),null===e.BottomPt&&(e.BottomPt=this.GetBottomPt(e.Pts));var i=t.BottomPt,s=e.BottomPt;return i.Pt.Y>s.Pt.Y?t:i.Pt.Y<s.Pt.Y?e:i.Pt.X<s.Pt.X?t:i.Pt.X>s.Pt.X||i.Next===i?e:s.Next===s||this.FirstIsBottomPt(i,s)?t:e}OutRec1RightOfOutRec2(t,e){do{if((t=t.FirstLeft)===e)return!0}while(null!==t);return!1}GetOutRec(t){for(var e=this.m_PolyOuts[t];e!==this.m_PolyOuts[e.Idx];)e=this.m_PolyOuts[e.Idx];return e}AppendPolygon(t,e){var i,s=this.m_PolyOuts[t.OutIdx],r=this.m_PolyOuts[e.OutIdx];i=this.OutRec1RightOfOutRec2(s,r)?r:this.OutRec1RightOfOutRec2(r,s)?s:this.GetLowermostRec(s,r);var n=s.Pts,o=n.Prev,a=r.Pts,l=a.Prev;0===t.Side?0===e.Side?(this.ReversePolyPtLinks(a),a.Next=n,n.Prev=a,o.Next=l,l.Prev=o,s.Pts=l):(l.Next=n,n.Prev=l,a.Prev=o,o.Next=a,s.Pts=a):1===e.Side?(this.ReversePolyPtLinks(a),o.Next=l,l.Prev=o,a.Next=n,n.Prev=a):(o.Next=a,a.Prev=o,n.Prev=l,l.Next=n),s.BottomPt=null,i===r&&(r.FirstLeft!==s&&(s.FirstLeft=r.FirstLeft),s.IsHole=r.IsHole),r.Pts=null,r.BottomPt=null,r.FirstLeft=s;var h=t.OutIdx,u=e.OutIdx;t.OutIdx=-1,e.OutIdx=-1;for(var c=this.m_ActiveEdges;null!==c;){if(c.OutIdx===u){c.OutIdx=h,c.Side=t.Side;break}c=c.NextInAEL}r.Idx=s.Idx}ReversePolyPtLinks(t){if(null!==t){var e,i;e=t;do{i=e.Next,e.Next=e.Prev,e.Prev=i,e=i}while(e!==t)}}static SwapSides(t,e){var i=t.Side;t.Side=e.Side,e.Side=i}static SwapPolyIndexes(t,e){var i=t.OutIdx;t.OutIdx=e.OutIdx,e.OutIdx=i}IntersectEdges(e,i,s){var r=e.OutIdx>=0,n=i.OutIdx>=0;if(!t.use_lines||0!==e.WindDelta&&0!==i.WindDelta){if(e.PolyTyp===i.PolyTyp)if(this.IsEvenOddFillType(e)){var o=e.WindCnt;e.WindCnt=i.WindCnt,i.WindCnt=o}else e.WindCnt+i.WindDelta===0?e.WindCnt=-e.WindCnt:e.WindCnt+=i.WindDelta,i.WindCnt-e.WindDelta===0?i.WindCnt=-i.WindCnt:i.WindCnt-=e.WindDelta;else this.IsEvenOddFillType(i)?e.WindCnt2=0===e.WindCnt2?1:0:e.WindCnt2+=i.WindDelta,this.IsEvenOddFillType(e)?i.WindCnt2=0===i.WindCnt2?1:0:i.WindCnt2-=e.WindDelta;var a,l,h,u,c,d;switch(0===e.PolyTyp?(a=this.m_SubjFillType,h=this.m_ClipFillType):(a=this.m_ClipFillType,h=this.m_SubjFillType),0===i.PolyTyp?(l=this.m_SubjFillType,u=this.m_ClipFillType):(l=this.m_ClipFillType,u=this.m_SubjFillType),a){case 2:c=e.WindCnt;break;case 3:c=-e.WindCnt;break;default:c=Math.abs(e.WindCnt)}switch(l){case 2:d=i.WindCnt;break;case 3:d=-i.WindCnt;break;default:d=Math.abs(i.WindCnt)}if(r&&n)0!==c&&1!==c||0!==d&&1!==d||e.PolyTyp!==i.PolyTyp&&3!==this.m_ClipType?this.AddLocalMaxPoly(e,i,s):(this.AddOutPt(e,s),this.AddOutPt(i,s),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(r)0!==d&&1!==d||(this.AddOutPt(e,s),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(n)0!==c&&1!==c||(this.AddOutPt(i,s),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(!(0!==c&&1!==c||0!==d&&1!==d)){var p,f;switch(h){case 2:p=e.WindCnt2;break;case 3:p=-e.WindCnt2;break;default:p=Math.abs(e.WindCnt2)}switch(u){case 2:f=i.WindCnt2;break;case 3:f=-i.WindCnt2;break;default:f=Math.abs(i.WindCnt2)}if(e.PolyTyp!==i.PolyTyp)this.AddLocalMinPoly(e,i,s);else if(1===c&&1===d)switch(this.m_ClipType){case 0:p>0&&f>0&&this.AddLocalMinPoly(e,i,s);break;case 1:p<=0&&f<=0&&this.AddLocalMinPoly(e,i,s);break;case 2:(1===e.PolyTyp&&p>0&&f>0||0===e.PolyTyp&&p<=0&&f<=0)&&this.AddLocalMinPoly(e,i,s);break;case 3:this.AddLocalMinPoly(e,i,s)}else t.Clipper.SwapSides(e,i)}}else{if(0===e.WindDelta&&0===i.WindDelta)return;e.PolyTyp===i.PolyTyp&&e.WindDelta!==i.WindDelta&&1===this.m_ClipType?0===e.WindDelta?n&&(this.AddOutPt(e,s),r&&(e.OutIdx=-1)):r&&(this.AddOutPt(i,s),n&&(i.OutIdx=-1)):e.PolyTyp!==i.PolyTyp&&(0!==e.WindDelta||1!==Math.abs(i.WindCnt)||1===this.m_ClipType&&0!==i.WindCnt2?0!==i.WindDelta||1!==Math.abs(e.WindCnt)||1===this.m_ClipType&&0!==e.WindCnt2||(this.AddOutPt(i,s),n&&(i.OutIdx=-1)):(this.AddOutPt(e,s),r&&(e.OutIdx=-1)))}}DeleteFromSEL(t){var e=t.PrevInSEL,i=t.NextInSEL;null===e&&null===i&&t!==this.m_SortedEdges||(null!==e?e.NextInSEL=i:this.m_SortedEdges=i,null!==i&&(i.PrevInSEL=e),t.NextInSEL=null,t.PrevInSEL=null)}ProcessHorizontals(){for(var t={};this.PopEdgeFromSEL(t);)this.ProcessHorizontal(t.v)}GetHorzDirection(t,e){t.Bot.X<t.Top.X?(e.Left=t.Bot.X,e.Right=t.Top.X,e.Dir=1):(e.Left=t.Top.X,e.Right=t.Bot.X,e.Dir=0)}ProcessHorizontal(e){var i={Dir:null,Left:null,Right:null};this.GetHorzDirection(e,i);for(var s=i.Dir,r=i.Left,n=i.Right,o=0===e.WindDelta,a=e,l=null;null!==a.NextInLML&&t.ClipperBase.IsHorizontal(a.NextInLML);)a=a.NextInLML;null===a.NextInLML&&(l=this.GetMaximaPair(a));var h=this.m_Maxima;if(null!==h)if(1===s){for(;null!==h&&h.X<=e.Bot.X;)h=h.Next;null!==h&&h.X>=a.Top.X&&(h=null)}else{for(;null!==h.Next&&h.Next.X<e.Bot.X;)h=h.Next;h.X<=a.Top.X&&(h=null)}for(var u=null;;){for(var c=e===a,d=this.GetNextInAEL(e,s);null!==d;){if(null!==h)if(1===s)for(;null!==h&&h.X<d.Curr.X;)e.OutIdx>=0&&!o&&this.AddOutPt(e,new t.FPoint(h.X,e.Bot.Y)),h=h.Next;else for(;null!==h&&h.X>d.Curr.X;)e.OutIdx>=0&&!o&&this.AddOutPt(e,new t.FPoint(h.X,e.Bot.Y)),h=h.Prev;if(1===s&&d.Curr.X>n||0===s&&d.Curr.X<r)break;if(d.Curr.X===e.Top.X&&null!==e.NextInLML&&d.Dx<e.NextInLML.Dx)break;if(e.OutIdx>=0&&!o){u=this.AddOutPt(e,d.Curr);for(var p=this.m_SortedEdges;null!==p;){if(p.OutIdx>=0&&this.HorzSegmentsOverlap(e.Bot.X,e.Top.X,p.Bot.X,p.Top.X)){var f=this.GetLastOutPt(p);this.AddJoin(f,u,p.Top)}p=p.NextInSEL}this.AddGhostJoin(u,e.Bot)}if(d===l&&c)return e.OutIdx>=0&&this.AddLocalMaxPoly(e,l,e.Top),this.DeleteFromAEL(e),void this.DeleteFromAEL(l);if(1===s){var m=new t.FPoint(d.Curr.X,e.Curr.Y);this.IntersectEdges(e,d,m)}else{m=new t.FPoint(d.Curr.X,e.Curr.Y);this.IntersectEdges(d,e,m)}var g=this.GetNextInAEL(d,s);this.SwapPositionsInAEL(e,d),d=g}if(null===e.NextInLML||!t.ClipperBase.IsHorizontal(e.NextInLML))break;(e=this.UpdateEdgeIntoAEL(e)).OutIdx>=0&&this.AddOutPt(e,e.Bot),i={Dir:s,Left:r,Right:n},this.GetHorzDirection(e,i),s=i.Dir,r=i.Left,n=i.Right}if(e.OutIdx>=0&&null===u){u=this.GetLastOutPt(e);for(p=this.m_SortedEdges;null!==p;){if(p.OutIdx>=0&&this.HorzSegmentsOverlap(e.Bot.X,e.Top.X,p.Bot.X,p.Top.X)){f=this.GetLastOutPt(p);this.AddJoin(f,u,p.Top)}p=p.NextInSEL}this.AddGhostJoin(u,e.Top)}if(null!==e.NextInLML)if(e.OutIdx>=0){if(u=this.AddOutPt(e,e.Top),0===(e=this.UpdateEdgeIntoAEL(e)).WindDelta)return;var y=e.PrevInAEL;g=e.NextInAEL;if(null!==y&&y.Curr.X===e.Bot.X&&y.Curr.Y===e.Bot.Y&&0===y.WindDelta&&y.OutIdx>=0&&y.Curr.Y>y.Top.Y&&t.ClipperBase.SlopesEqual3(e,y)){let t=this.AddOutPt(y,e.Bot);this.AddJoin(u,t,e.Top)}else if(null!==g&&g.Curr.X===e.Bot.X&&g.Curr.Y===e.Bot.Y&&0!==g.WindDelta&&g.OutIdx>=0&&g.Curr.Y>g.Top.Y&&t.ClipperBase.SlopesEqual3(e,g)){let t=this.AddOutPt(g,e.Bot);this.AddJoin(u,t,e.Top)}}else e=this.UpdateEdgeIntoAEL(e);else e.OutIdx>=0&&this.AddOutPt(e,e.Top),this.DeleteFromAEL(e)}GetNextInAEL(t,e){return 1===e?t.NextInAEL:t.PrevInAEL}IsMinima(t){return null!==t&&t.Prev.NextInLML!==t&&t.Next.NextInLML!==t}IsMaxima(t,e){return null!==t&&t.Top.Y===e&&null===t.NextInLML}IsIntermediate(t,e){return t.Top.Y===e&&null!==t.NextInLML}GetMaximaPair(e){return t.FPoint.op_Equality(e.Next.Top,e.Top)&&null===e.Next.NextInLML?e.Next:t.FPoint.op_Equality(e.Prev.Top,e.Top)&&null===e.Prev.NextInLML?e.Prev:null}GetMaximaPairEx(e){var i=this.GetMaximaPair(e);return null===i||i.OutIdx===t.ClipperBase.Skip||i.NextInAEL===i.PrevInAEL&&!t.ClipperBase.IsHorizontal(i)?null:i}ProcessIntersections(e){if(null===this.m_ActiveEdges)return!0;try{if(this.BuildIntersectList(e),0===this.m_IntersectList.length)return!0;if(1!==this.m_IntersectList.length&&!this.FixupIntersectionOrder())return!1;this.ProcessIntersectList()}catch(i){this.m_SortedEdges=null,this.m_IntersectList.length=0,t.Error("ProcessIntersections error")}return this.m_SortedEdges=null,!0}BuildIntersectList(e){if(null!==this.m_ActiveEdges){var i=this.m_ActiveEdges;for(this.m_SortedEdges=i;null!==i;)i.PrevInSEL=i.PrevInAEL,i.NextInSEL=i.NextInAEL,i.Curr.X=t.Clipper.TopX(i,e),i=i.NextInAEL;for(var s=!0;s&&null!==this.m_SortedEdges;){for(s=!1,i=this.m_SortedEdges;null!==i.NextInSEL;){var r=i.NextInSEL,n=new t.FPoint;if(i.Curr.X>r.Curr.X){this.IntersectPoint(i,r,n),n.Y<e&&(n=new t.FPoint(t.Clipper.TopX(i,e),e));var o=new t.IntersectNode;o.Edge1=i,o.Edge2=r,o.Pt.X=n.X,o.Pt.Y=n.Y,this.m_IntersectList.push(o),this.SwapPositionsInSEL(i,r),s=!0}else i=r}if(null===i.PrevInSEL)break;i.PrevInSEL.NextInSEL=null}this.m_SortedEdges=null}}EdgesAdjacent(t){return t.Edge1.NextInSEL===t.Edge2||t.Edge1.PrevInSEL===t.Edge2}static IntersectNodeSort(t,e){return e.Pt.Y-t.Pt.Y}FixupIntersectionOrder(){this.m_IntersectList.sort(this.m_IntersectNodeComparer),this.CopyAELToSEL();for(var t=this.m_IntersectList.length,e=0;e<t;e++){if(!this.EdgesAdjacent(this.m_IntersectList[e])){for(var i=e+1;i<t&&!this.EdgesAdjacent(this.m_IntersectList[i]);)i++;if(i===t)return!1;var s=this.m_IntersectList[e];this.m_IntersectList[e]=this.m_IntersectList[i],this.m_IntersectList[i]=s}this.SwapPositionsInSEL(this.m_IntersectList[e].Edge1,this.m_IntersectList[e].Edge2)}return!0}ProcessIntersectList(){for(var t=0,e=this.m_IntersectList.length;t<e;t++){var i=this.m_IntersectList[t];this.IntersectEdges(i.Edge1,i.Edge2,i.Pt),this.SwapPositionsInAEL(i.Edge1,i.Edge2)}this.m_IntersectList.length=0}static TopX(t,e){return e===t.Top.Y?t.Top.X:t.Bot.X+t.Dx*(e-t.Bot.Y)}IntersectPoint(e,i,s){var r,n;if(s.X=0,s.Y=0,e.Dx===i.Dx)return s.Y=e.Curr.Y,void(s.X=t.Clipper.TopX(e,s.Y));if(0===e.Delta.X)s.X=e.Bot.X,t.ClipperBase.IsHorizontal(i)?s.Y=i.Bot.Y:(n=i.Bot.Y-i.Bot.X/i.Dx,s.Y=s.X/i.Dx+n);else if(0===i.Delta.X)s.X=i.Bot.X,t.ClipperBase.IsHorizontal(e)?s.Y=e.Bot.Y:(r=e.Bot.Y-e.Bot.X/e.Dx,s.Y=s.X/e.Dx+r);else{r=e.Bot.X-e.Bot.Y*e.Dx;var o=((n=i.Bot.X-i.Bot.Y*i.Dx)-r)/(e.Dx-i.Dx);s.Y=o,Math.abs(e.Dx)<Math.abs(i.Dx)?s.X=e.Dx*o+r:s.X=i.Dx*o+n}if(s.Y<e.Top.Y||s.Y<i.Top.Y){if(e.Top.Y>i.Top.Y)return s.Y=e.Top.Y,s.X=t.Clipper.TopX(i,e.Top.Y),s.X<e.Top.X;s.Y=i.Top.Y,Math.abs(e.Dx)<Math.abs(i.Dx)?s.X=t.Clipper.TopX(e,s.Y):s.X=t.Clipper.TopX(i,s.Y)}s.Y>e.Curr.Y&&(s.Y=e.Curr.Y,Math.abs(e.Dx)>Math.abs(i.Dx)?s.X=t.Clipper.TopX(i,s.Y):s.X=t.Clipper.TopX(e,s.Y))}ProcessEdgesAtTopOfScanbeam(e){for(var i=this.m_ActiveEdges;null!==i;){var s=this.IsMaxima(i,e);if(s){var r=this.GetMaximaPairEx(i);s=null===r||!t.ClipperBase.IsHorizontal(r)}if(s){this.StrictlySimple&&this.InsertMaxima(i.Top.X);var n=i.PrevInAEL;this.DoMaxima(i),i=null===n?this.m_ActiveEdges:n.NextInAEL}else{if(this.IsIntermediate(i,e)&&t.ClipperBase.IsHorizontal(i.NextInLML)?((i=this.UpdateEdgeIntoAEL(i)).OutIdx>=0&&this.AddOutPt(i,i.Bot),this.AddEdgeToSEL(i)):(i.Curr.X=t.Clipper.TopX(i,e),i.Curr.Y=e),this.StrictlySimple){n=i.PrevInAEL;if(i.OutIdx>=0&&0!==i.WindDelta&&null!==n&&n.OutIdx>=0&&n.Curr.X===i.Curr.X&&0!==n.WindDelta){var o=new t.FPoint(i.Curr),a=this.AddOutPt(n,o),l=this.AddOutPt(i,o);this.AddJoin(a,l,o)}}i=i.NextInAEL}}for(this.ProcessHorizontals(),this.m_Maxima=null,i=this.m_ActiveEdges;null!==i;){if(this.IsIntermediate(i,e)){a=null;i.OutIdx>=0&&(a=this.AddOutPt(i,i.Top));n=(i=this.UpdateEdgeIntoAEL(i)).PrevInAEL;var h=i.NextInAEL;if(null!==n&&n.Curr.X===i.Bot.X&&n.Curr.Y===i.Bot.Y&&null!==a&&n.OutIdx>=0&&n.Curr.Y===n.Top.Y&&t.ClipperBase.SlopesEqual5(i.Curr,i.Top,n.Curr,n.Top)&&0!==i.WindDelta&&0!==n.WindDelta){l=this.AddOutPt(n,i.Bot);this.AddJoin(a,l,i.Top)}else if(null!==h&&h.Curr.X===i.Bot.X&&h.Curr.Y===i.Bot.Y&&null!==a&&h.OutIdx>=0&&h.Curr.Y===h.Top.Y&&t.ClipperBase.SlopesEqual5(i.Curr,i.Top,h.Curr,h.Top)&&0!==i.WindDelta&&0!==h.WindDelta){l=this.AddOutPt(h,i.Bot);this.AddJoin(a,l,i.Top)}}i=i.NextInAEL}}DoMaxima(e){var i=this.GetMaximaPairEx(e);if(null===i)return e.OutIdx>=0&&this.AddOutPt(e,e.Top),void this.DeleteFromAEL(e);for(var s=e.NextInAEL;null!==s&&s!==i;)this.IntersectEdges(e,s,e.Top),this.SwapPositionsInAEL(e,s),s=e.NextInAEL;-1===e.OutIdx&&-1===i.OutIdx?(this.DeleteFromAEL(e),this.DeleteFromAEL(i)):e.OutIdx>=0&&i.OutIdx>=0?(e.OutIdx>=0&&this.AddLocalMaxPoly(e,i,e.Top),this.DeleteFromAEL(e),this.DeleteFromAEL(i)):t.use_lines&&0===e.WindDelta?(e.OutIdx>=0&&(this.AddOutPt(e,e.Top),e.OutIdx=t.ClipperBase.Unassigned),this.DeleteFromAEL(e),i.OutIdx>=0&&(this.AddOutPt(i,e.Top),i.OutIdx=t.ClipperBase.Unassigned),this.DeleteFromAEL(i)):t.Error("DoMaxima error")}static ReversePaths(t){for(var e=0,i=t.length;e<i;e++)t[e].reverse()}static Orientation(e){return t.Clipper.Area(e)>=0}PointCount(t){if(null===t)return 0;var e=0,i=t;do{e++,i=i.Next}while(i!==t);return e}BuildResult(e){t.Clear(e);for(var i=0,s=this.m_PolyOuts.length;i<s;i++){var r=this.m_PolyOuts[i];if(null!==r.Pts){var n=r.Pts.Prev,o=this.PointCount(n);if(!(o<2)){for(var a=new Array(o),l=0;l<o;l++)a[l]=n.Pt,n=n.Prev;e.push(a)}}}}BuildResult2(e){e.Clear();for(var i=0,s=this.m_PolyOuts.length;i<s;i++){var r=this.m_PolyOuts[i],n=this.PointCount(r.Pts);if(!(r.IsOpen&&n<2||!r.IsOpen&&n<3)){this.FixHoleLinkage(r);var o=new t.PolyNode;e.m_AllPolys.push(o),r.PolyNode=o,o.m_polygon.length=n;for(var a=r.Pts.Prev,l=0;l<n;l++)o.m_polygon[l]=a.Pt,a=a.Prev}}for(i=0,s=this.m_PolyOuts.length;i<s;i++){null!==(r=this.m_PolyOuts[i]).PolyNode&&(r.IsOpen?(r.PolyNode.IsOpen=!0,e.AddChild(r.PolyNode)):null!==r.FirstLeft&&null!==r.FirstLeft.PolyNode?r.FirstLeft.PolyNode.AddChild(r.PolyNode):e.AddChild(r.PolyNode))}}FixupOutPolyline(e){for(var i=e.Pts,s=i.Prev;i!==s;)if(i=i.Next,t.FPoint.op_Equality(i.Pt,i.Prev.Pt)){i===s&&(s=i.Prev);var r=i.Prev;r.Next=i.Next,i.Next.Prev=r,i=r}i===i.Prev&&(e.Pts=null)}FixupOutPolygon(e){var i=null;e.BottomPt=null;for(var s=e.Pts,r=this.PreserveCollinear||this.StrictlySimple;;){if(s.Prev===s||s.Prev===s.Next)return void(e.Pts=null);if(t.FPoint.op_Equality(s.Pt,s.Next.Pt)||t.FPoint.op_Equality(s.Pt,s.Prev.Pt)||t.ClipperBase.SlopesEqual4(s.Prev.Pt,s.Pt,s.Next.Pt)&&(!r||!this.Pt2IsBetweenPt1AndPt3(s.Prev.Pt,s.Pt,s.Next.Pt)))i=null,s.Prev.Next=s.Next,s.Next.Prev=s.Prev,s=s.Prev;else{if(s===i)break;null===i&&(i=s),s=s.Next}}e.Pts=s}DupOutPt(e,i){var s=new t.OutPt;return s.Pt.X=e.Pt.X,s.Pt.Y=e.Pt.Y,s.Idx=e.Idx,i?(s.Next=e.Next,s.Prev=e,e.Next.Prev=s,e.Next=s):(s.Prev=e.Prev,s.Next=e,e.Prev.Next=s,e.Prev=s),s}GetOverlap(t,e,i,s,r){return t<e?i<s?(r.Left=Math.max(t,i),r.Right=Math.min(e,s)):(r.Left=Math.max(t,s),r.Right=Math.min(e,i)):i<s?(r.Left=Math.max(e,i),r.Right=Math.min(t,s)):(r.Left=Math.max(e,s),r.Right=Math.min(t,i)),r.Left<r.Right}JoinHorz(e,i,s,r,n,o){var a=e.Pt.X>i.Pt.X?0:1,l=s.Pt.X>r.Pt.X?0:1;if(a===l)return!1;if(1===a){for(;e.Next.Pt.X<=n.X&&e.Next.Pt.X>=e.Pt.X&&e.Next.Pt.Y===n.Y;)e=e.Next;o&&e.Pt.X!==n.X&&(e=e.Next),i=this.DupOutPt(e,!o),t.FPoint.op_Inequality(i.Pt,n)&&((e=i).Pt.X=n.X,e.Pt.Y=n.Y,i=this.DupOutPt(e,!o))}else{for(;e.Next.Pt.X>=n.X&&e.Next.Pt.X<=e.Pt.X&&e.Next.Pt.Y===n.Y;)e=e.Next;o||e.Pt.X===n.X||(e=e.Next),i=this.DupOutPt(e,o),t.FPoint.op_Inequality(i.Pt,n)&&((e=i).Pt.X=n.X,e.Pt.Y=n.Y,i=this.DupOutPt(e,o))}if(1===l){for(;s.Next.Pt.X<=n.X&&s.Next.Pt.X>=s.Pt.X&&s.Next.Pt.Y===n.Y;)s=s.Next;o&&s.Pt.X!==n.X&&(s=s.Next),r=this.DupOutPt(s,!o),t.FPoint.op_Inequality(r.Pt,n)&&((s=r).Pt.X=n.X,s.Pt.Y=n.Y,r=this.DupOutPt(s,!o))}else{for(;s.Next.Pt.X>=n.X&&s.Next.Pt.X<=s.Pt.X&&s.Next.Pt.Y===n.Y;)s=s.Next;o||s.Pt.X===n.X||(s=s.Next),r=this.DupOutPt(s,o),t.FPoint.op_Inequality(r.Pt,n)&&((s=r).Pt.X=n.X,s.Pt.Y=n.Y,r=this.DupOutPt(s,o))}return 1===a===o?(e.Prev=s,s.Next=e,i.Next=r,r.Prev=i):(e.Next=s,s.Prev=e,i.Prev=r,r.Next=i),!0}JoinPoints(e,i,s){var r=e.OutPt1,n=new t.OutPt,o=e.OutPt2,a=new t.OutPt,l=e.OutPt1.Pt.Y===e.OffPt.Y;if(l&&t.FPoint.op_Equality(e.OffPt,e.OutPt1.Pt)&&t.FPoint.op_Equality(e.OffPt,e.OutPt2.Pt)){if(i!==s)return!1;for(n=e.OutPt1.Next;n!==r&&t.FPoint.op_Equality(n.Pt,e.OffPt);)n=n.Next;var h=n.Pt.Y>e.OffPt.Y;for(a=e.OutPt2.Next;a!==o&&t.FPoint.op_Equality(a.Pt,e.OffPt);)a=a.Next;return h!==a.Pt.Y>e.OffPt.Y&&(h?(n=this.DupOutPt(r,!1),a=this.DupOutPt(o,!0),r.Prev=o,o.Next=r,n.Next=a,a.Prev=n,e.OutPt1=r,e.OutPt2=n,!0):(n=this.DupOutPt(r,!0),a=this.DupOutPt(o,!1),r.Next=o,o.Prev=r,n.Prev=a,a.Next=n,e.OutPt1=r,e.OutPt2=n,!0))}if(l){for(n=r;r.Prev.Pt.Y===r.Pt.Y&&r.Prev!==n&&r.Prev!==o;)r=r.Prev;for(;n.Next.Pt.Y===n.Pt.Y&&n.Next!==r&&n.Next!==o;)n=n.Next;if(n.Next===r||n.Next===o)return!1;for(a=o;o.Prev.Pt.Y===o.Pt.Y&&o.Prev!==a&&o.Prev!==n;)o=o.Prev;for(;a.Next.Pt.Y===a.Pt.Y&&a.Next!==o&&a.Next!==r;)a=a.Next;if(a.Next===o||a.Next===r)return!1;var u={Left:null,Right:null};if(!this.GetOverlap(r.Pt.X,n.Pt.X,o.Pt.X,a.Pt.X,u))return!1;var c,d=u.Left,p=u.Right,f=new t.FPoint;return r.Pt.X>=d&&r.Pt.X<=p?(f.X=r.Pt.X,f.Y=r.Pt.Y,c=r.Pt.X>n.Pt.X):o.Pt.X>=d&&o.Pt.X<=p?(f.X=o.Pt.X,f.Y=o.Pt.Y,c=o.Pt.X>a.Pt.X):n.Pt.X>=d&&n.Pt.X<=p?(f.X=n.Pt.X,f.Y=n.Pt.Y,c=n.Pt.X>r.Pt.X):(f.X=a.Pt.X,f.Y=a.Pt.Y,c=a.Pt.X>o.Pt.X),e.OutPt1=r,e.OutPt2=o,this.JoinHorz(r,n,o,a,f,c)}for(n=r.Next;t.FPoint.op_Equality(n.Pt,r.Pt)&&n!==r;)n=n.Next;var m=n.Pt.Y>r.Pt.Y||!t.ClipperBase.SlopesEqual4(r.Pt,n.Pt,e.OffPt);if(m){for(n=r.Prev;t.FPoint.op_Equality(n.Pt,r.Pt)&&n!==r;)n=n.Prev;if(n.Pt.Y>r.Pt.Y||!t.ClipperBase.SlopesEqual4(r.Pt,n.Pt,e.OffPt))return!1}for(a=o.Next;t.FPoint.op_Equality(a.Pt,o.Pt)&&a!==o;)a=a.Next;var g=a.Pt.Y>o.Pt.Y||!t.ClipperBase.SlopesEqual4(o.Pt,a.Pt,e.OffPt);if(g){for(a=o.Prev;t.FPoint.op_Equality(a.Pt,o.Pt)&&a!==o;)a=a.Prev;if(a.Pt.Y>o.Pt.Y||!t.ClipperBase.SlopesEqual4(o.Pt,a.Pt,e.OffPt))return!1}return n!==r&&a!==o&&n!==a&&(i!==s||m!==g)&&(m?(n=this.DupOutPt(r,!1),a=this.DupOutPt(o,!0),r.Prev=o,o.Next=r,n.Next=a,a.Prev=n,e.OutPt1=r,e.OutPt2=n,!0):(n=this.DupOutPt(r,!0),a=this.DupOutPt(o,!1),r.Next=o,o.Prev=r,n.Prev=a,a.Next=n,e.OutPt1=r,e.OutPt2=n,!0))}static GetBounds(e){for(var i=0,s=e.length;i<s&&0===e[i].length;)i++;if(i===s)return new t.FRect(0,0,0,0);var r=new t.FRect;for(r.left=e[i][0].X,r.right=r.left,r.top=e[i][0].Y,r.bottom=r.top;i<s;i++)for(var n=0,o=e[i].length;n<o;n++)e[i][n].X<r.left?r.left=e[i][n].X:e[i][n].X>r.right&&(r.right=e[i][n].X),e[i][n].Y<r.top?r.top=e[i][n].Y:e[i][n].Y>r.bottom&&(r.bottom=e[i][n].Y);return r}GetBounds2(e){var i=e,s=new t.FRect;for(s.left=e.Pt.X,s.right=e.Pt.X,s.top=e.Pt.Y,s.bottom=e.Pt.Y,e=e.Next;e!==i;)e.Pt.X<s.left&&(s.left=e.Pt.X),e.Pt.X>s.right&&(s.right=e.Pt.X),e.Pt.Y<s.top&&(s.top=e.Pt.Y),e.Pt.Y>s.bottom&&(s.bottom=e.Pt.Y),e=e.Next;return s}static PointInPolygon(t,e){var i=0,s=e.length;if(s<3)return 0;for(var r=e[0],n=1;n<=s;++n){var o=n===s?e[0]:e[n];if(o.Y===t.Y&&(o.X===t.X||r.Y===t.Y&&o.X>t.X==r.X<t.X))return-1;if(r.Y<t.Y!=o.Y<t.Y)if(r.X>=t.X)if(o.X>t.X)i=1-i;else{if(0===(a=(r.X-t.X)*(o.Y-t.Y)-(o.X-t.X)*(r.Y-t.Y)))return-1;a>0==o.Y>r.Y&&(i=1-i)}else if(o.X>t.X){var a;if(0===(a=(r.X-t.X)*(o.Y-t.Y)-(o.X-t.X)*(r.Y-t.Y)))return-1;a>0==o.Y>r.Y&&(i=1-i)}r=o}return i}PointInPolygon(t,e){var i=0,s=e,r=t.X,n=t.Y,o=e.Pt.X,a=e.Pt.Y;do{var l=(e=e.Next).Pt.X,h=e.Pt.Y;if(h===n&&(l===r||a===n&&l>r==o<r))return-1;if(a<n!=h<n)if(o>=r)if(l>r)i=1-i;else{if(0===(u=(o-r)*(h-n)-(l-r)*(a-n)))return-1;u>0==h>a&&(i=1-i)}else if(l>r){var u;if(0===(u=(o-r)*(h-n)-(l-r)*(a-n)))return-1;u>0==h>a&&(i=1-i)}o=l,a=h}while(s!==e);return i}Poly2ContainsPoly1(t,e){var i=t;do{var s=this.PointInPolygon(i.Pt,e);if(s>=0)return s>0;i=i.Next}while(i!==t);return!0}FixupFirstLefts1(e,i){for(var s,r,n=0,o=this.m_PolyOuts.length;n<o;n++)s=this.m_PolyOuts[n],r=t.Clipper.ParseFirstLeft(s.FirstLeft),null!==s.Pts&&r===e&&this.Poly2ContainsPoly1(s.Pts,i.Pts)&&(s.FirstLeft=i)}FixupFirstLefts2(e,i){for(var s,r,n=i.FirstLeft,o=0,a=this.m_PolyOuts.length;o<a;o++)null!==(s=this.m_PolyOuts[o]).Pts&&s!==i&&s!==e&&((r=t.Clipper.ParseFirstLeft(s.FirstLeft))!==n&&r!==e&&r!==i||(this.Poly2ContainsPoly1(s.Pts,e.Pts)?s.FirstLeft=e:this.Poly2ContainsPoly1(s.Pts,i.Pts)?s.FirstLeft=i:s.FirstLeft!==e&&s.FirstLeft!==i||(s.FirstLeft=n)))}FixupFirstLefts3(e,i){for(var s,r,n=0,o=this.m_PolyOuts.length;n<o;n++)s=this.m_PolyOuts[n],r=t.Clipper.ParseFirstLeft(s.FirstLeft),null!==s.Pts&&r===e&&(s.FirstLeft=i)}static ParseFirstLeft(t){for(;null!==t&&null===t.Pts;)t=t.FirstLeft;return t}JoinCommonEdges(){for(var t=0,e=this.m_Joins.length;t<e;t++){var i,s=this.m_Joins[t],r=this.GetOutRec(s.OutPt1.Idx),n=this.GetOutRec(s.OutPt2.Idx);if(null!==r.Pts&&null!==n.Pts)if(!r.IsOpen&&!n.IsOpen)i=r===n?r:this.OutRec1RightOfOutRec2(r,n)?n:this.OutRec1RightOfOutRec2(n,r)?r:this.GetLowermostRec(r,n),this.JoinPoints(s,r,n)&&(r===n?(r.Pts=s.OutPt1,r.BottomPt=null,(n=this.CreateOutRec()).Pts=s.OutPt2,this.UpdateOutPtIdxs(n),this.Poly2ContainsPoly1(n.Pts,r.Pts)?(n.IsHole=!r.IsHole,n.FirstLeft=r,this.m_UsingPolyTree&&this.FixupFirstLefts2(n,r),(n.IsHole^this.ReverseSolution)==this.Area$1(n)>0&&this.ReversePolyPtLinks(n.Pts)):this.Poly2ContainsPoly1(r.Pts,n.Pts)?(n.IsHole=r.IsHole,r.IsHole=!n.IsHole,n.FirstLeft=r.FirstLeft,r.FirstLeft=n,this.m_UsingPolyTree&&this.FixupFirstLefts2(r,n),(r.IsHole^this.ReverseSolution)==this.Area$1(r)>0&&this.ReversePolyPtLinks(r.Pts)):(n.IsHole=r.IsHole,n.FirstLeft=r.FirstLeft,this.m_UsingPolyTree&&this.FixupFirstLefts1(r,n))):(n.Pts=null,n.BottomPt=null,n.Idx=r.Idx,r.IsHole=i.IsHole,i===n&&(r.FirstLeft=n.FirstLeft),n.FirstLeft=r,this.m_UsingPolyTree&&this.FixupFirstLefts3(n,r)))}}UpdateOutPtIdxs(t){var e=t.Pts;do{e.Idx=t.Idx,e=e.Prev}while(e!==t.Pts)}DoSimplePolygons(){for(var e=0;e<this.m_PolyOuts.length;){var i=this.m_PolyOuts[e++],s=i.Pts;if(null!==s&&!i.IsOpen)do{for(var r=s.Next;r!==i.Pts;){if(t.FPoint.op_Equality(s.Pt,r.Pt)&&r.Next!==s&&r.Prev!==s){var n=s.Prev,o=r.Prev;s.Prev=o,o.Next=s,r.Prev=n,n.Next=r,i.Pts=s;var a=this.CreateOutRec();a.Pts=r,this.UpdateOutPtIdxs(a),this.Poly2ContainsPoly1(a.Pts,i.Pts)?(a.IsHole=!i.IsHole,a.FirstLeft=i,this.m_UsingPolyTree&&this.FixupFirstLefts2(a,i)):this.Poly2ContainsPoly1(i.Pts,a.Pts)?(a.IsHole=i.IsHole,i.IsHole=!a.IsHole,a.FirstLeft=i.FirstLeft,i.FirstLeft=a,this.m_UsingPolyTree&&this.FixupFirstLefts2(i,a)):(a.IsHole=i.IsHole,a.FirstLeft=i.FirstLeft,this.m_UsingPolyTree&&this.FixupFirstLefts1(i,a)),r=s}r=r.Next}s=s.Next}while(s!==i.Pts)}}static Area(t){if(!Array.isArray(t))return 0;var e=t.length;if(e<3)return 0;for(var i=0,s=0,r=e-1;s<e;++s)i+=(t[r].X+t[s].X)*(t[r].Y-t[s].Y),r=s;return.5*-i}Area(t){var e=t;if(null===t)return 0;var i=0;do{i+=(t.Prev.Pt.X+t.Pt.X)*(t.Prev.Pt.Y-t.Pt.Y),t=t.Next}while(t!==e);return.5*i}Area$1(t){return this.Area(t.Pts)}static SimplifyPolygon(e,i){var s=new Array,r=new t.Clipper(0);return r.StrictlySimple=!0,r.AddPath(e,0,!0),r.Execute(1,s,i,i),s}static SimplifyPolygons(e,i){void 0===i&&(i=0);var s=new Array,r=new t.Clipper(0);return r.StrictlySimple=!0,r.AddPaths(e,0,!0),r.Execute(1,s,i,i),s}static DistanceSqrd(t,e){var i=t.X-e.X,s=t.Y-e.Y;return i*i+s*s}static DistanceFromLineSqrd(t,e,i){var s=e.Y-i.Y,r=i.X-e.X,n=s*e.X+r*e.Y;return(n=s*t.X+r*t.Y-n)*n/(s*s+r*r)}static SlopesNearCollinear(e,i,s,r){return Math.abs(e.X-i.X)>Math.abs(e.Y-i.Y)?e.X>i.X==e.X<s.X?t.Clipper.DistanceFromLineSqrd(e,i,s)<r:i.X>e.X==i.X<s.X?t.Clipper.DistanceFromLineSqrd(i,e,s)<r:t.Clipper.DistanceFromLineSqrd(s,e,i)<r:e.Y>i.Y==e.Y<s.Y?t.Clipper.DistanceFromLineSqrd(e,i,s)<r:i.Y>e.Y==i.Y<s.Y?t.Clipper.DistanceFromLineSqrd(i,e,s)<r:t.Clipper.DistanceFromLineSqrd(s,e,i)<r}static PointsAreClose(t,e,i){var s=t.X-e.X,r=t.Y-e.Y;return s*s+r*r<=i}static ExcludeOp(t){var e=t.Prev;return e.Next=t.Next,t.Next.Prev=e,e.Idx=0,e}static CleanPolygon(e,i){void 0===i&&(i=1.415);var s=e.length;if(0===s)return new Array;for(var r=new Array(s),n=0;n<s;++n)r[n]=new t.OutPt;for(n=0;n<s;++n)r[n].Pt=e[n],r[n].Next=r[(n+1)%s],r[n].Next.Prev=r[n],r[n].Idx=0;for(var o=i*i,a=r[0];0===a.Idx&&a.Next!==a.Prev;)t.Clipper.PointsAreClose(a.Pt,a.Prev.Pt,o)?(a=t.Clipper.ExcludeOp(a),s--):t.Clipper.PointsAreClose(a.Prev.Pt,a.Next.Pt,o)?(t.Clipper.ExcludeOp(a.Next),a=t.Clipper.ExcludeOp(a),s-=2):t.Clipper.SlopesNearCollinear(a.Prev.Pt,a.Pt,a.Next.Pt,o)?(a=t.Clipper.ExcludeOp(a),s--):(a.Idx=1,a=a.Next);s<3&&(s=0);var l=new Array(s);for(n=0;n<s;++n)l[n]=new t.FPoint(a.Pt),a=a.Next;return r=null,l}static CleanPolygons(e,i){for(var s=new Array(e.length),r=0,n=e.length;r<n;r++)s[r]=t.Clipper.CleanPolygon(e[r],i);return s}static Minkowski(e,i,s,r){var n=r?1:0,o=e.length,a=i.length,l=new Array;if(s)for(var h=0;h<a;h++){for(var u=new Array(o),c=0,d=e.length,p=e[c];c<d;p=e[++c])u[c]=new t.FPoint(i[h].X+p.X,i[h].Y+p.Y);l.push(u)}else for(h=0;h<a;h++){for(u=new Array(o),c=0,d=e.length,p=e[c];c<d;p=e[++c])u[c]=new t.FPoint(i[h].X-p.X,i[h].Y-p.Y);l.push(u)}var f=new Array;for(h=0;h<a-1+n;h++)for(c=0;c<o;c++){var m=new Array;m.push(l[h%a][c%o]),m.push(l[(h+1)%a][c%o]),m.push(l[(h+1)%a][(c+1)%o]),m.push(l[h%a][(c+1)%o]),t.Clipper.Orientation(m)||m.reverse(),f.push(m)}return f}static MinkowskiSum(e,i,s){if(i[0]instanceof Array){let l=i;for(var r=[],n=(a=new t.Clipper,0);n<l.length;++n){var o=t.Clipper.Minkowski(e,l[n],!0,s);if(a.AddPaths(o,0,!0),s){let i=t.Clipper.TranslatePath(l[n],e[0]);a.AddPath(i,1,!0)}}return a.Execute(1,r,1,1),r}{let r=i,n=t.Clipper.Minkowski(e,r,!0,s);var a;return(a=new t.Clipper).AddPaths(n,0,!0),a.Execute(1,n,1,1),n}}static TranslatePath(e,i){for(var s=[],r=0;r<e.length;r++)s.push(new t.FPoint(e[r].X+i.X,e[r].Y+i.Y));return s}static MinkowskiDiff(e,i){var s=t.Clipper.Minkowski(e,i,!1,!0),r=new t.Clipper;return r.AddPaths(s,0,!0),r.Execute(1,s,1,1),s}static PolyTreeToPaths(e){var i=new Array;return t.Clipper.AddPolyNodeToPaths(e,0,i),i}static AddPolyNodeToPaths(e,i,s){var r=!0;switch(i){case 1:return;case 2:r=!e.IsOpen}e.m_polygon.length>0&&r&&s.push(e.m_polygon);for(var n=0,o=e.Children(),a=o.length,l=o[n];n<a;l=o[++n])t.Clipper.AddPolyNodeToPaths(l,i,s)}static OpenPathsFromPolyTree(t){for(var e=[],i=0,s=t.ChildCount();i<s;i++)t.Children()[i].IsOpen&&e.push(t.Children()[i].m_polygon);return e}static ClosedPathsFromPolyTree(e){var i=[];return t.Clipper.AddPolyNodeToPaths(e,2,i),i}};t.ClipperOffset=class{m_destPolys=[];m_srcPoly=[];m_destPoly=[];m_normals=new Array;m_delta=0;m_sinA=0;m_sin=0;m_cos=0;m_miterLim=0;m_StepsPerRad=0;m_lowest=new t.FPoint;m_polyNodes=new t.PolyNode;MiterLimit;ArcTolerance;constructor(e,i){void 0===e&&(e=2),void 0===i&&(i=t.ClipperOffset.def_arc_tolerance),this.MiterLimit=e,this.ArcTolerance=i,this.m_lowest.X=-1}static two_pi=6.28318530717959;static def_arc_tolerance=.25;Clear(){t.Clear(this.m_polyNodes.Children()),this.m_lowest.X=-1}AddPath(e,i,s){var r=e.length-1;if(!(r<0)){var n=new t.PolyNode;if(n.m_jointype=i,n.m_endtype=s,3===s||4===s)for(;r>0&&t.FPoint.op_Equality(e[0],e[r]);)r--;n.m_polygon.push(e[0]);for(var o=0,a=0,l=1;l<=r;l++)t.FPoint.op_Inequality(n.m_polygon[o],e[l])&&(o++,n.m_polygon.push(e[l]),(e[l].Y>n.m_polygon[a].Y||e[l].Y===n.m_polygon[a].Y&&e[l].X<n.m_polygon[a].X)&&(a=o));if(!(4===s&&o<2)&&(this.m_polyNodes.AddChild(n),4===s))if(this.m_lowest.X<0)this.m_lowest=new t.FPoint(this.m_polyNodes.ChildCount()-1,a);else{var h=this.m_polyNodes.Children()[this.m_lowest.X].m_polygon[this.m_lowest.Y];(n.m_polygon[a].Y>h.Y||n.m_polygon[a].Y===h.Y&&n.m_polygon[a].X<h.X)&&(this.m_lowest=new t.FPoint(this.m_polyNodes.ChildCount()-1,a))}}}AddPaths(t,e,i){for(var s=0,r=t.length;s<r;s++)this.AddPath(t[s],e,i)}FixOrientations(){if(this.m_lowest.X>=0&&!t.Clipper.Orientation(this.m_polyNodes.Children()[this.m_lowest.X].m_polygon))for(var e=0;e<this.m_polyNodes.ChildCount();e++){(4===(i=this.m_polyNodes.Children()[e]).m_endtype||3===i.m_endtype&&t.Clipper.Orientation(i.m_polygon))&&i.m_polygon.reverse()}else for(e=0;e<this.m_polyNodes.ChildCount();e++){var i;3!==(i=this.m_polyNodes.Children()[e]).m_endtype||t.Clipper.Orientation(i.m_polygon)||i.m_polygon.reverse()}}static GetUnitNormal(e,i){var s=i.X-e.X,r=i.Y-e.Y;if(0===s&&0===r)return new t.FPoint(0,0);var n=1/Math.sqrt(s*s+r*r);return s*=n,r*=n,new t.FPoint(r,-s)}DoOffset(e){if(this.m_destPolys=new Array,this.m_delta=e,t.ClipperBase.near_zero(e))for(var i=0;i<this.m_polyNodes.ChildCount();i++){4===(n=this.m_polyNodes.Children()[i]).m_endtype&&this.m_destPolys.push(n.m_polygon)}else{var s;this.MiterLimit>2?this.m_miterLim=2/(this.MiterLimit*this.MiterLimit):this.m_miterLim=.5,s=this.ArcTolerance<=0?t.ClipperOffset.def_arc_tolerance:this.ArcTolerance>Math.abs(e)*t.ClipperOffset.def_arc_tolerance?Math.abs(e)*t.ClipperOffset.def_arc_tolerance:this.ArcTolerance;var r=3.14159265358979/Math.acos(1-s/Math.abs(e));this.m_sin=Math.sin(t.ClipperOffset.two_pi/r),this.m_cos=Math.cos(t.ClipperOffset.two_pi/r),this.m_StepsPerRad=r/t.ClipperOffset.two_pi,e<0&&(this.m_sin=-this.m_sin);for(i=0;i<this.m_polyNodes.ChildCount();i++){var n=this.m_polyNodes.Children()[i];this.m_srcPoly=n.m_polygon;var o=this.m_srcPoly.length;if(!(0===o||e<=0&&(o<3||4!==n.m_endtype)))if(this.m_destPoly=new Array,1!==o){this.m_normals.length=0;for(d=0;d<o-1;d++)this.m_normals.push(t.ClipperOffset.GetUnitNormal(this.m_srcPoly[d],this.m_srcPoly[d+1]));if(3===n.m_endtype||4===n.m_endtype?this.m_normals.push(t.ClipperOffset.GetUnitNormal(this.m_srcPoly[o-1],this.m_srcPoly[0])):this.m_normals.push(new t.FPoint(this.m_normals[o-2])),4===n.m_endtype){var a=o-1;for(d=0;d<o;d++)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly)}else if(3===n.m_endtype){for(a=o-1,d=0;d<o;d++)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly),this.m_destPoly=new Array;var l=this.m_normals[o-1];for(d=o-1;d>0;d--)this.m_normals[d]=new t.FPoint(-this.m_normals[d-1].X,-this.m_normals[d-1].Y);this.m_normals[0]=new t.FPoint(-l.X,-l.Y),a=0;for(d=o-1;d>=0;d--)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly)}else{var h;for(a=0,d=1;d<o-1;++d)a=this.OffsetPoint(d,a,n.m_jointype);if(2===n.m_endtype){d=o-1;h=new t.FPoint(this.m_srcPoly[d].X+this.m_normals[d].X*e,this.m_srcPoly[d].Y+this.m_normals[d].Y*e),this.m_destPoly.push(h),h=new t.FPoint(this.m_srcPoly[d].X-this.m_normals[d].X*e,this.m_srcPoly[d].Y-this.m_normals[d].Y*e),this.m_destPoly.push(h)}else{d=o-1;a=o-2,this.m_sinA=0,this.m_normals[d]=new t.FPoint(-this.m_normals[d].X,-this.m_normals[d].Y),0===n.m_endtype?this.DoSquare(d,a):this.DoRound(d,a)}for(d=o-1;d>0;d--)this.m_normals[d]=new t.FPoint(-this.m_normals[d-1].X,-this.m_normals[d-1].Y);this.m_normals[0]=new t.FPoint(-this.m_normals[1].X,-this.m_normals[1].Y);for(d=(a=o-1)-1;d>0;--d)a=this.OffsetPoint(d,a,n.m_jointype);2===n.m_endtype?(h=new t.FPoint(this.m_srcPoly[0].X-this.m_normals[0].X*e,this.m_srcPoly[0].Y-this.m_normals[0].Y*e),this.m_destPoly.push(h),h=new t.FPoint(this.m_srcPoly[0].X+this.m_normals[0].X*e,this.m_srcPoly[0].Y+this.m_normals[0].Y*e),this.m_destPoly.push(h)):(a=1,this.m_sinA=0,0===n.m_endtype?this.DoSquare(0,1):this.DoRound(0,1)),this.m_destPolys.push(this.m_destPoly)}}else{if(1===n.m_jointype)for(var u=1,c=0,d=1;d<=r;d++){this.m_destPoly.push(new t.FPoint(this.m_srcPoly[0].X+u*e,this.m_srcPoly[0].Y+c*e));var p=u;u=u*this.m_cos-this.m_sin*c,c=p*this.m_sin+c*this.m_cos}else{u=-1,c=-1;for(var d=0;d<4;++d)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[0].X+u*e,this.m_srcPoly[0].Y+c*e)),u<0?u=1:c<0?c=1:u=-1}this.m_destPolys.push(this.m_destPoly)}}}}Execute(...e){var i=e;if(i[0]instanceof t.PolyTree){o=i[0],a=i[1];if(o.Clear(),this.FixOrientations(),this.DoOffset(a),(n=new t.Clipper(0)).AddPaths(this.m_destPolys,0,!0),a>0)n.Execute(1,o,2,2);else{h=t.Clipper.GetBounds(this.m_destPolys);if((l=[]).push(new t.FPoint(h.left-10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.top-10)),l.push(new t.FPoint(h.left-10,h.top-10)),n.AddPath(l,0,!0),n.ReverseSolution=!0,n.Execute(1,o,3,3),1===o.ChildCount()&&o.Children()[0].ChildCount()>0){var s=o.Children()[0];o.Children()[0]=s.Children()[0],o.Children()[0].m_Parent=o;for(var r=1;r<s.ChildCount();r++)o.AddChild(s.Children()[r])}else o.Clear()}}else{var n,o=i[0],a=i[1];if(t.Clear(o),this.FixOrientations(),this.DoOffset(a),(n=new t.Clipper(0)).AddPaths(this.m_destPolys,0,!0),a>0)n.Execute(1,o,2,2);else{var l,h=t.Clipper.GetBounds(this.m_destPolys);(l=[]).push(new t.FPoint(h.left-10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.top-10)),l.push(new t.FPoint(h.left-10,h.top-10)),n.AddPath(l,0,!0),n.ReverseSolution=!0,n.Execute(1,o,3,3),o.length>0&&o.splice(0,1)}}}OffsetPoint(e,i,s){if(this.m_sinA=this.m_normals[i].X*this.m_normals[e].Y-this.m_normals[e].X*this.m_normals[i].Y,0===this.m_sinA)return i;if(this.m_sinA>1?this.m_sinA=1:this.m_sinA<-1&&(this.m_sinA=-1),this.m_sinA*this.m_delta<0)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[i].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[i].Y*this.m_delta)),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e])),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[e].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[e].Y*this.m_delta));else switch(s){case 2:var r=this.m_normals[e].X*this.m_normals[i].X+this.m_normals[e].Y*this.m_normals[i].Y+1;r>=this.m_miterLim?this.DoMiter(e,i,r):this.DoSquare(e,i);break;case 0:this.DoSquare(e,i);break;case 1:this.DoRound(e,i)}return i=e}DoSquare(e,i){var s=Math.tan(Math.atan2(this.m_sinA,this.m_normals[i].X*this.m_normals[e].X+this.m_normals[i].Y*this.m_normals[e].Y)/4);this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_delta*(this.m_normals[i].X-this.m_normals[i].Y*s),this.m_srcPoly[e].Y+this.m_delta*(this.m_normals[i].Y+this.m_normals[i].X*s))),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_delta*(this.m_normals[e].X+this.m_normals[e].Y*s),this.m_srcPoly[e].Y+this.m_delta*(this.m_normals[e].Y-this.m_normals[e].X*s)))}DoMiter(e,i,s){var r=this.m_delta/s;this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+(this.m_normals[i].X+this.m_normals[e].X)*r,this.m_srcPoly[e].Y+(this.m_normals[i].Y+this.m_normals[e].Y)*r))}DoRound(e,i){for(var s,r=Math.atan2(this.m_sinA,this.m_normals[i].X*this.m_normals[e].X+this.m_normals[i].Y*this.m_normals[e].Y),n=Math.max(Math.round(this.m_StepsPerRad*Math.abs(r)),1),o=this.m_normals[i].X,a=this.m_normals[i].Y,l=0;l<n;++l)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+o*this.m_delta,this.m_srcPoly[e].Y+a*this.m_delta)),s=o,o=o*this.m_cos-this.m_sin*a,a=s*this.m_sin+a*this.m_cos;this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[e].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[e].Y*this.m_delta))}},t.Error=function(e){throw new t.Error(e)}})(G||(G={}));const X=G;function W(t){let e=et(t),i=X.Clipper.GetBounds(e);return{min:[i.left,-i.bottom],max:[i.right,-i.top]}}function Y(t){if(!t.length)return[];let e=t.filter(t=>t&&t.length>0);if(!e.length)return[];if(1===e.length)return[e[0]];let i=et(e);if(!i.length)return[];let s=[i[0]],r=i.slice(1),n=new X.Clipper;n.AddPaths(s,X.PolyType.ptSubject,!0),n.AddPaths(r,X.PolyType.ptClip,!0);let o=[];return n.Execute(X.ClipType.ctUnion,o,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),it(o)}function H(t,e=0,i=[],s=[],r=[]){for(let n of t.m_Children){if(!n.m_polygon.length)continue;let t=e%2!=0,o=it([n.m_polygon])[0],a={polygon:o,children:[]};i.push(a),t?r.push(o):(r=[o],s.push(r)),H(n,e+1,a.children,s,r)}return s.sort((t,e)=>K(t[0])>K(e[0])?-1:1),{polyTree:i,polygons:s}}function $(t,e=.1,i,s){if(!t.length||!t[0])return[];void 0===i&&(i=X.EndType.etClosedPolygon),e=e&&"number"==typeof e?e:.1;let r=et(t=s?t:Q(t)),n=new X.ClipperOffset(2),o=[];return n.AddPaths(r,X.JoinType.jtMiter,i),n.Execute(o,e),it(o)}function j(t,e=.1,i=X.EndType.etClosedPolygon){if(!t.length||!t[0])return{polygons:[],polyTree:[]};let s=[];for(let o of t)s.push(...et(o));let r=new X.ClipperOffset(2);r.AddPaths(s,X.JoinType.jtMiter,i);let n=new X.PolyTree;return r.Execute(n,e),H(n)}function z(t,e,i){if(!t.length||!t[0])return[];if(!e.length)return t;let s=et(t),r=et(e),n=new X.Clipper;n.AddPaths(s,X.PolyType.ptSubject,!0),n.AddPaths(r,X.PolyType.ptClip,!0);let o=[];return new X.PolyTree,n.Execute(X.ClipType.ctDifference,o,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),it(o)}function V(t,e){if(!t.length||!t[0])return{polygons:[],polyTree:[]};if(!e.length){let e=t.map(t=>[...t]),i=e.map(t=>({polygon:t[0],children:[]}));return{polygons:e,polyTree:i}}let i=[];for(let o=0;o<t.length;o++)i.push(...et(t[o]));let s=[];for(let o=0;o<e.length;o++)s.push(...et(e[o]));let r=new X.Clipper;r.AddPaths(i,X.PolyType.ptSubject,!0),r.AddPaths(s,X.PolyType.ptClip,!0);let n=new X.PolyTree;return r.Execute(X.ClipType.ctDifference,n,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),H(n)}function q(t,e,i=[]){let s=new X.FPoint(t[0],-t[1]),r=et([e])[0],n=X.Clipper.PointInPolygon(s,r);for(let o of i){let e=q(t,o);1===e?n=0:-1===e&&(n=-1)}return n}function J(t){let e=et([t]);return X.Clipper.Area(e[0])}function K(t){return Math.abs(J(t))}function Z(t){let e=Math.abs(J(t[0]));for(let i of t.slice(1))e-=Math.abs(J(i));return e}function Q(t,e=.01){let i=et(t);return it(X.Clipper.CleanPolygons(i,e))}function tt(t,e=.01){return Q([t],e)[0]}function et(t=[]){let e=[],i=0;for(let s=0;s<t.length;s++){let r=t[s];if(!r?.length)continue;let n=new Array(r.length);for(let t=0;t<r.length;t++){let e=r[t];n[t]={X:e[0],Y:-e[1]}}e[i]=n,i++}return e}function it(t){let e=new Array(t.length);for(let i=0;i<t.length;i++){let s=t[i]||[],r=new Array(s.length);for(let t=0;t<s.length;t++){let e=s[t];r[t]=[e.X,-e.Y]}e[i]=r}return e}var st=1e-6,rt="undefined"!=typeof Float32Array?Float32Array:Array;function nt(){var t=new rt(16);return rt!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function ot(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function at(t,e){if(t===e){var i=e[1],s=e[2],r=e[3],n=e[6],o=e[7],a=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=i,t[6]=e[9],t[7]=e[13],t[8]=s,t[9]=n,t[11]=e[14],t[12]=r,t[13]=o,t[14]=a}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function lt(t,e){var i=e[0],s=e[1],r=e[2],n=e[3],o=e[4],a=e[5],l=e[6],h=e[7],u=e[8],c=e[9],d=e[10],p=e[11],f=e[12],m=e[13],g=e[14],y=e[15],v=i*a-s*o,x=i*l-r*o,b=i*h-n*o,w=s*l-r*a,_=s*h-n*a,P=r*h-n*l,E=u*m-c*f,T=u*g-d*f,A=u*y-p*f,I=c*g-d*m,S=c*y-p*m,C=d*y-p*g,M=v*C-x*S+b*I+w*A-_*T+P*E;return M?(M=1/M,t[0]=(a*C-l*S+h*I)*M,t[1]=(r*S-s*C-n*I)*M,t[2]=(m*P-g*_+y*w)*M,t[3]=(d*_-c*P-p*w)*M,t[4]=(l*A-o*C-h*T)*M,t[5]=(i*C-r*A+n*T)*M,t[6]=(g*b-f*P-y*x)*M,t[7]=(u*P-d*b+p*x)*M,t[8]=(o*S-a*A+h*E)*M,t[9]=(s*A-i*S-n*E)*M,t[10]=(f*_-m*b+y*v)*M,t[11]=(c*b-u*_-p*v)*M,t[12]=(a*T-o*I-l*E)*M,t[13]=(i*I-s*T+r*E)*M,t[14]=(m*x-f*w-g*v)*M,t[15]=(u*w-c*x+d*v)*M,t):null}function ht(t,e,i){var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],l=e[5],h=e[6],u=e[7],c=e[8],d=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],v=e[15],x=i[0],b=i[1],w=i[2],_=i[3];return t[0]=x*s+b*a+w*c+_*m,t[1]=x*r+b*l+w*d+_*g,t[2]=x*n+b*h+w*p+_*y,t[3]=x*o+b*u+w*f+_*v,x=i[4],b=i[5],w=i[6],_=i[7],t[4]=x*s+b*a+w*c+_*m,t[5]=x*r+b*l+w*d+_*g,t[6]=x*n+b*h+w*p+_*y,t[7]=x*o+b*u+w*f+_*v,x=i[8],b=i[9],w=i[10],_=i[11],t[8]=x*s+b*a+w*c+_*m,t[9]=x*r+b*l+w*d+_*g,t[10]=x*n+b*h+w*p+_*y,t[11]=x*o+b*u+w*f+_*v,x=i[12],b=i[13],w=i[14],_=i[15],t[12]=x*s+b*a+w*c+_*m,t[13]=x*r+b*l+w*d+_*g,t[14]=x*n+b*h+w*p+_*y,t[15]=x*o+b*u+w*f+_*v,t}function ut(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t}function ct(t,e){var i=new rt(3);!function(t,e){var i=e[0],s=e[1],r=e[2],n=e[4],o=e[5],a=e[6],l=e[8],h=e[9],u=e[10];t[0]=Math.sqrt(i*i+s*s+r*r),t[1]=Math.sqrt(n*n+o*o+a*a),t[2]=Math.sqrt(l*l+h*h+u*u)}(i,e);var s=1/i[0],r=1/i[1],n=1/i[2],o=e[0]*s,a=e[1]*r,l=e[2]*n,h=e[4]*s,u=e[5]*r,c=e[6]*n,d=e[8]*s,p=e[9]*r,f=e[10]*n,m=o+u+f,g=0;return m>0?(g=2*Math.sqrt(m+1),t[3]=.25*g,t[0]=(c-p)/g,t[1]=(d-l)/g,t[2]=(a-h)/g):o>u&&o>f?(g=2*Math.sqrt(1+o-u-f),t[3]=(c-p)/g,t[0]=.25*g,t[1]=(a+h)/g,t[2]=(d+l)/g):u>f?(g=2*Math.sqrt(1+u-o-f),t[3]=(d-l)/g,t[0]=(a+h)/g,t[1]=.25*g,t[2]=(c+p)/g):(g=2*Math.sqrt(1+f-o-u),t[3]=(a-h)/g,t[0]=(d+l)/g,t[1]=(c+p)/g,t[2]=.25*g),t}function dt(){var t=new rt(3);return rt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function pt(t){var e=new rt(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function ft(t,e,i){var s=new rt(3);return s[0]=t,s[1]=e,s[2]=i,s}function mt(t,e,i,s){return t[0]=e,t[1]=i,t[2]=s,t}function gt(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t[2]=e[2]+i[2],t}function yt(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t[2]=e[2]-i[2],t}function vt(t,e){var i=e[0],s=e[1],r=e[2],n=i*i+s*s+r*r;return n>0&&(n=1/Math.sqrt(n)),t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t}function xt(t,e,i){var s=e[0],r=e[1],n=e[2],o=i[0],a=i[1],l=i[2];return t[0]=r*l-n*a,t[1]=n*o-s*l,t[2]=s*a-r*o,t}function bt(t,e,i){var s=e[0],r=e[1],n=e[2],o=i[3]*s+i[7]*r+i[11]*n+i[15];return o=o||1,t[0]=(i[0]*s+i[4]*r+i[8]*n+i[12])/o,t[1]=(i[1]*s+i[5]*r+i[9]*n+i[13])/o,t[2]=(i[2]*s+i[6]*r+i[10]*n+i[14])/o,t}var wt=yt;function _t(){var t=new rt(4);return rt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function Pt(t,e,i){i*=.5;var s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t}dt(),function(){var t,e=(t=new rt(4),rt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t)}();var Et;function Tt(){var t=new rt(2);return rt!=Float32Array&&(t[0]=0,t[1]=0),t}dt(),ft(1,0,0),ft(0,1,0),_t(),_t(),Et=new rt(9),rt!=Float32Array&&(Et[1]=0,Et[2]=0,Et[3]=0,Et[5]=0,Et[6]=0,Et[7]=0),Et[0]=1,Et[4]=1,Et[8]=1,function(){var t=Tt()}();var At="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function It(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function St(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var i=function t(){var i=!1;try{i=this instanceof t}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};i.prototype=e.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(i,e,s.get?s:{enumerable:!0,get:function(){return t[e]}})}),i}var Ct,Mt={exports:{}};var Ot=function(){if(Ct)return Mt.exports;function t(t,i,r){r=r||2;var n,o,a,u,c,p,f,m=i&&i.length,g=m?i[0]*r:t.length,y=e(t,0,g,r,!0),v=[];if(!y||y.next===y.prev)return v;if(m&&(y=function(t,i,s,r){var n,o,a,u=[];for(n=0,o=i.length;n<o;n++)(a=e(t,i[n]*r,n<o-1?i[n+1]*r:t.length,r,!1))===a.next&&(a.steiner=!0),u.push(d(a));for(u.sort(l),n=0;n<u.length;n++)s=h(u[n],s);return s}(t,i,y,r)),t.length>80*r){n=a=t[0],o=u=t[1];for(var x=r;x<g;x+=r)(c=t[x])<n&&(n=c),(p=t[x+1])<o&&(o=p),c>a&&(a=c),p>u&&(u=p);f=0!==(f=Math.max(a-n,u-o))?32767/f:0}return s(y,v,r,n,o,f,0),v}function e(t,e,i,s,r){var n,o;if(r===T(t,e,i,s)>0)for(n=e;n<i;n+=s)o=_(n,t[n],t[n+1],o);else for(n=i-s;n>=e;n-=s)o=_(n,t[n],t[n+1],o);return o&&g(o,o.next)&&(P(o),o=o.next),o}function i(t,e){if(!t)return t;e||(e=t);var i,s=t;do{if(i=!1,s.steiner||!g(s,s.next)&&0!==m(s.prev,s,s.next))s=s.next;else{if(P(s),(s=e=s.prev)===s.next)break;i=!0}}while(i||s!==e);return e}function s(t,e,l,h,u,d,p){if(t){!p&&d&&function(t,e,i,s){var r=t;do{0===r.z&&(r.z=c(r.x,r.y,e,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){var e,i,s,r,n,o,a,l,h=1;do{for(i=t,t=null,n=null,o=0;i;){for(o++,s=i,a=0,e=0;e<h&&(a++,s=s.nextZ);e++);for(l=h;a>0||l>0&&s;)0!==a&&(0===l||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,l--),n?n.nextZ=r:t=r,r.prevZ=n,n=r;i=s}n.nextZ=null,h*=2}while(o>1)}(r)}(t,h,u,d);for(var f,m,g=t;t.prev!==t.next;)if(f=t.prev,m=t.next,d?n(t,h,u,d):r(t))e.push(f.i/l|0),e.push(t.i/l|0),e.push(m.i/l|0),P(t),t=m.next,g=m.next;else if((t=m)===g){p?1===p?s(t=o(i(t),e,l),e,l,h,u,d,2):2===p&&a(t,e,l,h,u,d):s(i(t),e,l,h,u,d,1);break}}}function r(t){var e=t.prev,i=t,s=t.next;if(m(e,i,s)>=0)return!1;for(var r=e.x,n=i.x,o=s.x,a=e.y,l=i.y,h=s.y,u=r<n?r<o?r:o:n<o?n:o,c=a<l?a<h?a:h:l<h?l:h,d=r>n?r>o?r:o:n>o?n:o,f=a>l?a>h?a:h:l>h?l:h,g=s.next;g!==e;){if(g.x>=u&&g.x<=d&&g.y>=c&&g.y<=f&&p(r,a,n,l,o,h,g.x,g.y)&&m(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function n(t,e,i,s){var r=t.prev,n=t,o=t.next;if(m(r,n,o)>=0)return!1;for(var a=r.x,l=n.x,h=o.x,u=r.y,d=n.y,f=o.y,g=a<l?a<h?a:h:l<h?l:h,y=u<d?u<f?u:f:d<f?d:f,v=a>l?a>h?a:h:l>h?l:h,x=u>d?u>f?u:f:d>f?d:f,b=c(g,y,e,i,s),w=c(v,x,e,i,s),_=t.prevZ,P=t.nextZ;_&&_.z>=b&&P&&P.z<=w;){if(_.x>=g&&_.x<=v&&_.y>=y&&_.y<=x&&_!==r&&_!==o&&p(a,u,l,d,h,f,_.x,_.y)&&m(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,P.x>=g&&P.x<=v&&P.y>=y&&P.y<=x&&P!==r&&P!==o&&p(a,u,l,d,h,f,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;P=P.nextZ}for(;_&&_.z>=b;){if(_.x>=g&&_.x<=v&&_.y>=y&&_.y<=x&&_!==r&&_!==o&&p(a,u,l,d,h,f,_.x,_.y)&&m(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;P&&P.z<=w;){if(P.x>=g&&P.x<=v&&P.y>=y&&P.y<=x&&P!==r&&P!==o&&p(a,u,l,d,h,f,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;P=P.nextZ}return!0}function o(t,e,s){var r=t;do{var n=r.prev,o=r.next.next;!g(n,o)&&y(n,r,r.next,o)&&b(n,o)&&b(o,n)&&(e.push(n.i/s|0),e.push(r.i/s|0),e.push(o.i/s|0),P(r),P(r.next),r=t=o),r=r.next}while(r!==t);return i(r)}function a(t,e,r,n,o,a){var l=t;do{for(var h=l.next.next;h!==l.prev;){if(l.i!==h.i&&f(l,h)){var u=w(l,h);return l=i(l,l.next),u=i(u,u.next),s(l,e,r,n,o,a,0),void s(u,e,r,n,o,a,0)}h=h.next}l=l.next}while(l!==t)}function l(t,e){return t.x-e.x}function h(t,e){var s=function(t,e){var i,s=e,r=t.x,n=t.y,o=-1/0;do{if(n<=s.y&&n>=s.next.y&&s.next.y!==s.y){var a=s.x+(n-s.y)*(s.next.x-s.x)/(s.next.y-s.y);if(a<=r&&a>o&&(o=a,i=s.x<s.next.x?s:s.next,a===r))return i}s=s.next}while(s!==e);if(!i)return null;var l,h=i,c=i.x,d=i.y,f=1/0;s=i;do{r>=s.x&&s.x>=c&&r!==s.x&&p(n<d?r:o,n,c,d,n<d?o:r,n,s.x,s.y)&&(l=Math.abs(n-s.y)/(r-s.x),b(s,t)&&(l<f||l===f&&(s.x>i.x||s.x===i.x&&u(i,s)))&&(i=s,f=l)),s=s.next}while(s!==h);return i}(t,e);if(!s)return e;var r=w(s,t);return i(r,r.next),i(s,s.next)}function u(t,e){return m(t.prev,t,e.prev)<0&&m(e.next,t,t.next)<0}function c(t,e,i,s,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function d(t){var e=t,i=t;do{(e.x<i.x||e.x===i.x&&e.y<i.y)&&(i=e),e=e.next}while(e!==t);return i}function p(t,e,i,s,r,n,o,a){return(r-o)*(e-a)>=(t-o)*(n-a)&&(t-o)*(s-a)>=(i-o)*(e-a)&&(i-o)*(n-a)>=(r-o)*(s-a)}function f(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&y(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(b(t,e)&&b(e,t)&&function(t,e){var i=t,s=!1,r=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s}(t,e)&&(m(t.prev,t,e.prev)||m(t,e.prev,e))||g(t,e)&&m(t.prev,t,t.next)>0&&m(e.prev,e,e.next)>0)}function m(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function g(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,i,s){var r=x(m(t,e,i)),n=x(m(t,e,s)),o=x(m(i,s,t)),a=x(m(i,s,e));return r!==n&&o!==a||(!(0!==r||!v(t,i,e))||(!(0!==n||!v(t,s,e))||(!(0!==o||!v(i,t,s))||!(0!==a||!v(i,e,s)))))}function v(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function x(t){return t>0?1:t<0?-1:0}function b(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function w(t,e){var i=new E(t.i,t.x,t.y),s=new E(e.i,e.x,e.y),r=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=r,r.prev=i,s.next=i,i.prev=s,n.next=s,s.prev=n,s}function _(t,e,i,s){var r=new E(t,e,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function P(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function E(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function T(t,e,i,s){for(var r=0,n=e,o=i-s;n<i;n+=s)r+=(t[o]-t[n])*(t[n+1]+t[o+1]),o=n;return r}return Ct=1,Mt.exports=t,Mt.exports.default=t,t.deviation=function(t,e,i,s){var r=e&&e.length,n=r?e[0]*i:t.length,o=Math.abs(T(t,0,n,i));if(r)for(var a=0,l=e.length;a<l;a++){var h=e[a]*i,u=a<l-1?e[a+1]*i:t.length;o-=Math.abs(T(t,h,u,i))}var c=0;for(a=0;a<s.length;a+=3){var d=s[a]*i,p=s[a+1]*i,f=s[a+2]*i;c+=Math.abs((t[d]-t[f])*(t[p+1]-t[d+1])-(t[d]-t[p])*(t[f+1]-t[d+1]))}return 0===o&&0===c?0:Math.abs((c-o)/o)},t.flatten=function(t){for(var e=t[0][0].length,i={vertices:[],holes:[],dimensions:e},s=0,r=0;r<t.length;r++){for(var n=0;n<t[r].length;n++)for(var o=0;o<e;o++)i.vertices.push(t[r][n][o]);r>0&&(s+=t[r-1].length,i.holes.push(s))}return i},Mt.exports}();const Nt=/* @__PURE__ */It(Ot);for(var Lt,Rt=[],Bt=0;Bt<256;++Bt)Rt.push((Bt+256).toString(16).slice(1));var kt=new Uint8Array(16);function Ft(){if(!Lt&&!(Lt="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lt(kt)}const Dt={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Ut(t,e,i){if(Dt.randomUUID&&!t)return Dt.randomUUID();var s=(t=t||{}).random||(t.rng||Ft)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(t,e=0){return(Rt[t[e+0]]+Rt[t[e+1]]+Rt[t[e+2]]+Rt[t[e+3]]+"-"+Rt[t[e+4]]+Rt[t[e+5]]+"-"+Rt[t[e+6]]+Rt[t[e+7]]+"-"+Rt[t[e+8]]+Rt[t[e+9]]+"-"+Rt[t[e+10]]+Rt[t[e+11]]+Rt[t[e+12]]+Rt[t[e+13]]+Rt[t[e+14]]+Rt[t[e+15]]).toLowerCase()}(s)}function Gt(t,e,i,s,r){Xt(t,e,i||0,s||t.length-1,r||Yt)}function Xt(t,e,i,s,r){for(;s>i;){if(s-i>600){var n=s-i+1,o=e-i+1,a=Math.log(n),l=.5*Math.exp(2*a/3),h=.5*Math.sqrt(a*l*(n-l)/n)*(o-n/2<0?-1:1);Xt(t,e,Math.max(i,Math.floor(e-o*l/n+h)),Math.min(s,Math.floor(e+(n-o)*l/n+h)),r)}var u=t[e],c=i,d=s;for(Wt(t,i,e),r(t[s],u)>0&&Wt(t,i,s);c<d;){for(Wt(t,c,d),c++,d--;r(t[c],u)<0;)c++;for(;r(t[d],u)>0;)d--}0===r(t[i],u)?Wt(t,i,d):Wt(t,++d,s),d<=e&&(i=d+1),e<=d&&(s=d-1)}}function Wt(t,e,i){var s=t[e];t[e]=t[i],t[i]=s}function Yt(t,e){return t<e?-1:t>e?1:0}class Ht{constructor(t=9){this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(t){let e=this.data;const i=[];if(!ie(t,e))return i;const s=this.toBBox,r=[];for(;e;){for(let n=0;n<e.children.length;n++){const o=e.children[n],a=e.leaf?s(o):o;ie(t,a)&&(e.leaf?i.push(o):ee(t,a)?this._all(o,i):r.push(o))}e=r.pop()}return i}collides(t){let e=this.data;if(!ie(t,e))return!1;const i=[];for(;e;){for(let s=0;s<e.children.length;s++){const r=e.children[s],n=e.leaf?this.toBBox(r):r;if(ie(t,n)){if(e.leaf||ee(t,n))return!0;i.push(r)}}e=i.pop()}return!1}load(t){if(!t||!t.length)return this;if(t.length<this._minEntries){for(let e=0;e<t.length;e++)this.insert(t[e]);return this}let e=this._build(t.slice(),0,t.length-1,0);if(this.data.children.length)if(this.data.height===e.height)this._splitRoot(this.data,e);else{if(this.data.height<e.height){const t=this.data;this.data=e,e=t}this._insert(e,this.data.height-e.height-1,!0)}else this.data=e;return this}insert(t){return t&&this._insert(t,this.data.height-1),this}clear(){return this.data=se([]),this}remove(t,e){if(!t)return this;let i=this.data;const s=this.toBBox(t),r=[],n=[];let o,a,l;for(;i||r.length;){if(i||(i=r.pop(),a=r[r.length-1],o=n.pop(),l=!0),i.leaf){const s=$t(t,i.children,e);if(-1!==s)return i.children.splice(s,1),r.push(i),this._condense(r),this}l||i.leaf||!ee(i,s)?a?(o++,i=a.children[o],l=!1):i=null:(r.push(i),n.push(o),o=0,a=i,i=i.children[0])}return this}toBBox(t){return t}compareMinX(t,e){return t.minX-e.minX}compareMinY(t,e){return t.minY-e.minY}toJSON(){return this.data}fromJSON(t){return this.data=t,this}_all(t,e){const i=[];for(;t;)t.leaf?e.push(...t.children):i.push(...t.children),t=i.pop();return e}_build(t,e,i,s){const r=i-e+1;let n,o=this._maxEntries;if(r<=o)return n=se(t.slice(e,i+1)),jt(n,this.toBBox),n;s||(s=Math.ceil(Math.log(r)/Math.log(o)),o=Math.ceil(r/Math.pow(o,s-1))),n=se([]),n.leaf=!1,n.height=s;const a=Math.ceil(r/o),l=a*Math.ceil(Math.sqrt(o));re(t,e,i,l,this.compareMinX);for(let h=e;h<=i;h+=l){const e=Math.min(h+l-1,i);re(t,h,e,a,this.compareMinY);for(let i=h;i<=e;i+=a){const r=Math.min(i+a-1,e);n.children.push(this._build(t,i,r,s-1))}}return jt(n,this.toBBox),n}_chooseSubtree(t,e,i,s){for(;s.push(e),!e.leaf&&s.length-1!==i;){let i,s=1/0,r=1/0;for(let n=0;n<e.children.length;n++){const o=e.children[n],a=Kt(o),l=Qt(t,o)-a;l<r?(r=l,s=a<s?a:s,i=o):l===r&&a<s&&(s=a,i=o)}e=i||e.children[0]}return e}_insert(t,e,i){const s=i?t:this.toBBox(t),r=[],n=this._chooseSubtree(s,this.data,e,r);for(n.children.push(t),Vt(n,s);e>=0&&r[e].children.length>this._maxEntries;)this._split(r,e),e--;this._adjustParentBBoxes(s,r,e)}_split(t,e){const i=t[e],s=i.children.length,r=this._minEntries;this._chooseSplitAxis(i,r,s);const n=this._chooseSplitIndex(i,r,s),o=se(i.children.splice(n,i.children.length-n));o.height=i.height,o.leaf=i.leaf,jt(i,this.toBBox),jt(o,this.toBBox),e?t[e-1].children.push(o):this._splitRoot(i,o)}_splitRoot(t,e){this.data=se([t,e]),this.data.height=t.height+1,this.data.leaf=!1,jt(this.data,this.toBBox)}_chooseSplitIndex(t,e,i){let s,r=1/0,n=1/0;for(let o=e;o<=i-e;o++){const e=zt(t,0,o,this.toBBox),a=zt(t,o,i,this.toBBox),l=te(e,a),h=Kt(e)+Kt(a);l<r?(r=l,s=o,n=h<n?h:n):l===r&&h<n&&(n=h,s=o)}return s||i-e}_chooseSplitAxis(t,e,i){const s=t.leaf?this.compareMinX:qt,r=t.leaf?this.compareMinY:Jt;this._allDistMargin(t,e,i,s)<this._allDistMargin(t,e,i,r)&&t.children.sort(s)}_allDistMargin(t,e,i,s){t.children.sort(s);const r=this.toBBox,n=zt(t,0,e,r),o=zt(t,i-e,i,r);let a=Zt(n)+Zt(o);for(let l=e;l<i-e;l++){const e=t.children[l];Vt(n,t.leaf?r(e):e),a+=Zt(n)}for(let l=i-e-1;l>=e;l--){const e=t.children[l];Vt(o,t.leaf?r(e):e),a+=Zt(o)}return a}_adjustParentBBoxes(t,e,i){for(let s=i;s>=0;s--)Vt(e[s],t)}_condense(t){for(let e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children,e.splice(e.indexOf(t[i]),1)):this.clear():jt(t[i],this.toBBox)}}function $t(t,e,i){if(!i)return e.indexOf(t);for(let s=0;s<e.length;s++)if(i(t,e[s]))return s;return-1}function jt(t,e){zt(t,0,t.children.length,e,t)}function zt(t,e,i,s,r){r||(r=se(null)),r.minX=1/0,r.minY=1/0,r.maxX=-1/0,r.maxY=-1/0;for(let n=e;n<i;n++){const e=t.children[n];Vt(r,t.leaf?s(e):e)}return r}function Vt(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function qt(t,e){return t.minX-e.minX}function Jt(t,e){return t.minY-e.minY}function Kt(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function Zt(t){return t.maxX-t.minX+(t.maxY-t.minY)}function Qt(t,e){return(Math.max(e.maxX,t.maxX)-Math.min(e.minX,t.minX))*(Math.max(e.maxY,t.maxY)-Math.min(e.minY,t.minY))}function te(t,e){const i=Math.max(t.minX,e.minX),s=Math.max(t.minY,e.minY),r=Math.min(t.maxX,e.maxX),n=Math.min(t.maxY,e.maxY);return Math.max(0,r-i)*Math.max(0,n-s)}function ee(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function ie(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function se(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function re(t,e,i,s,r){const n=[e,i];for(;n.length;){if((i=n.pop())-(e=n.pop())<=s)continue;const o=e+Math.ceil((i-e)/s/2)*s;Gt(t,o,e,i,r),n.push(e,o,o,i)}}var ne,oe={exports:{}};var ae,le,he,ue,ce=function(){if(ne)return oe.exports;function t(){}return ne=1,t.prototype={on:function(t,e,i){var s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var s=this;function r(){s.off(t,r),e.apply(i,arguments)}return r._=e,this.on(t,r,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),s=0,r=i.length;s<r;s++)i[s].fn.apply(i[s].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),s=i[t],r=[];if(s&&e)for(var n=0,o=s.length;n<o;n++)s[n].fn!==e&&s[n].fn._!==e&&r.push(s[n]);return r.length?i[t]=r:delete i[t],this}},oe.exports=t,oe.exports.TinyEmitter=t,oe.exports}(),de=t=>{throw TypeError(t)},pe=(t,e,i)=>e.has(t)||de("Cannot "+i),fe=(t,e,i)=>(pe(t,e,"read from private field"),i?i.call(t):e.get(t)),me=(t,e,i)=>e.has(t)?de("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),ge=(t,e,i,s)=>(pe(t,e,"write to private field"),e.set(t,i),i),ye=(t,e,i)=>(pe(t,e,"access private method"),i);let ve=new class extends E{error(...t){this.levels.includes("errors")&&(t.length>0&&(t[0]="Internal error: "+t[0]),console.error(...t),this.emit("error",...t))}}(["info","warnings","errors"]);class xe{constructor(t){this.spaceGraph=null,this.type=t}}class be extends xe{constructor(t,e){super(e),this.name="",this.customId="",this.id=t}copyForClone(t){this.name=t.name,this.customId=t.customId}setName(t){this.name=t,this.emit("node-property-change",this,"name")}setCustomId(t){this.customId=t,this.emit("node-property-change",this,"customId")}emit(t,...e){this.spaceGraph&&this.spaceGraph.emit(t,...e)}toJSON(){return{type:this.type,id:this.id,name:""===this.name?void 0:this.name,customId:""===this.customId?void 0:this.customId}}}const we="material:color";class _e extends be{constructor(t,e=[1,1,1],i=1){super(t,we),this.color=[...e],this.opacity=i}toJSON(){let t;return t=1===this.opacity?[...this.color]:[this.color[0],this.color[1],this.color[2],this.opacity],{...super.toJSON(),value:t}}}const Pe="material:standard";class Ee extends be{constructor(t,e){super(t,Pe),this.reference=e}toJSON(){return{...super.toJSON(),reference:this.reference}}}const Te="material:embedded";class Ae extends be{constructor(t,e,i){super(t,Ie),this.reference=e,this.format=i}toJSON(){return ve.warn("Embedded material not supported in materials section."),{...super.toJSON(),type:"material:color",value:[1,1,1,1]}}}const Ie="material:basic";class Se extends be{constructor(t){super(t,Ie),this.colorDiffuse=[1,1,1],this.colorSpecular=[1,1,1],this.specularCoefficient=1,this.opacity=1}copyForClone(t){super.copyForClone(t),this.colorDiffuse=[...t.colorDiffuse],this.colorSpecular=[...t.colorSpecular],this.specularCoefficient=t.specularCoefficient,this.opacity=t.opacity}toJSON(){return{...super.toJSON(),colorDiffuse:[...this.colorDiffuse],colorSpecular:[...this.colorSpecular],specularCoefficient:this.specularCoefficient,opacity:this.opacity}}}const Ce="default",Me=[1,1,1],Oe=[1,1,1],Ne=[...Me,1];function Le(t,e){return Number.isFinite(t)?!(t<0||t>1)||(ve.warn(`Value out of range (0 to 1) in color literal: '${e}'.`),!1):(ve.warn(`Invalid float value in color literal: '${e}'.`),!1)}function Re(t,e){return Number.isInteger(t)?!(t<0||t>255)||(ve.warn(`Value out of range (0 to 255) in color literal: '${e}'.`),!1):(ve.warn(`Invalid byte value in color literal: '${e}'.`),!1)}function Be(t){if(t.length<3||t.length>4)return ve.warn(`Invalid number of components in color literal: '${t}'.`),Ne;let e=t.toString(),i=[0,0,0,0];for(let s=0;s<t.length;s++){let r=t[s];if(!Le(r,e))return Ne;i[s]=r}return 3===t.length&&(i[3]=Ne[3]),i}function ke(t){let e,i,s,r,n=t.substring(1),o=parseInt(n,16);if(isNaN(o))return ve.warn(`Invalid hexadecimal color literal: '${t}'.`),Ne;if(3===n.length?o=o<<4|15:6===n.length&&(o=o<<8|255),3===n.length||4===n.length)e=(o>>12&15)/15,i=(o>>8&15)/15,s=(o>>4&15)/15,r=(15&o)/15;else{if(6!==n.length&&8!==n.length)return ve.warn(`Invalid hexademical color literal length: '${t}'.`),Ne;e=(o>>24&255)/255,i=(o>>16&255)/255,s=(o>>8&255)/255,r=(255&o)/255}return[e,i,s,r]}function Fe(t,e){if(!t.endsWith(")"))return ve.warn(`Missing closing parenthesis: '${t}'.`),Ne;let i=e?5:4,s=t.substring(i,t.length-1).split(",");if(s.length<3||s.length>4||3===s.length&&e||4===s.length&&!e)return ve.warn(`Invalid number of components in color literal: '${t}'.`),Ne;let r=[0,0,0,0];for(let n=0;n<3;n++){let e=s[n],i=parseFloat(e);if(!Re(i,t))return Ne;r[n]=i/255}if(4===s.length){let e=parseFloat(s[3]);if(!Le(e,t))return Ne;r[3]=e}else r[3]=Ne[3];return r}function De([t,e,i]){return"#"+Math.round(255*t).toString(16).padStart(2,"0")+Math.round(255*e).toString(16).padStart(2,"0")+Math.round(255*i).toString(16).padStart(2,"0")}function Ue({name:t=Ce,color:e=Me,specularColor:i=Oe,specularCoefficient:s=1,opacity:r=1,reference:n}={}){return n?{name:t,reference:n}:{name:t,color:[...e],specularColor:[...i],specularCoefficient:s,opacity:r}}function Ge(t,e={}){if(Array.isArray(t)){let[e,i,s,r]=Be(t);return Ue({name:t.toString(),color:[e,i,s],opacity:r})}if("string"==typeof t){let i,s,r,n;if(""===t)return ve.warn("Empty string not a valid color value."),Ue({name:t});if(t===Ce)return Ue();if("#"===t.charAt(0))[i,s,r,n]=ke(t);else if(t.startsWith("rgb("))[i,s,r,n]=Fe(t,!1);else{if(!t.startsWith("rgba(")){if(t.startsWith("asm:")){let e=t.substring(4,t.length);return Ue({name:t,reference:e})}if(t.startsWith("data3d:")){let e=t.substring(7,t.length);return Ue({name:t,reference:e})}{let i=e[t];if(void 0===i)return ve.warn(`Unknown material: '${t}'.`),Ue();{let e;switch(i.type){case we:e=Ue({name:t,color:i.color,specularColor:i.color});break;case Pe:e=Ue({name:t,reference:i.reference});break;case Te:ve.warn("Embedded material not supported in materials section."),e=Ue();break;case Ie:e=Ue({name:t,color:i.colorDiffuse,specularColor:i.colorSpecular,specularCoefficient:i.specularCoefficient,opacity:i.opacity});break;default:ve.warn(`Unknown material type ${i.type}.`),e=Ue()}return e}}}[i,s,r,n]=Fe(t,!0)}return Ue({name:t,color:[i,s,r],opacity:n})}return ve.warn(`Material can only be an array or a string: '${t}'.`),Ue()}const Xe="default";function We(t,e){return new Array(e-t).fill(void 0).map((e,i)=>t+i)}function Ye(t,e){let i=new Array(3*e.length),s=0;for(let r=0;r<e.length;r++){let n=3*e[r];i[s++]=t[n],i[s++]=t[n+1],i[s++]=t[n+2]}return i}function He(t,e,i){let s=3*e,r=new Array(s*i.length),n=0;for(let o=0;o<i.length;o++){let e=s*i[o];for(let i=0;i<s;i++)r[n++]=t[e++]}return r}function $e(t,e,i){let s=[],r=e.faces,{surfaces:n,materials:o}=function(t){let e=t.surfaces??{[Xe]:"all"},i=t.materials??{[Xe]:"default"};if(e&&0===Object.keys(e).length)ve.warn("Empty 'surfaces' field not allowed.");else if(i&&0===Object.keys(i).length)ve.warn("Empty 'materials' field not allowed.");else if(t.material)t.materials?ve.warn("Cannot use 'material' and 'materials' at the same time."):i={[Xe]:t.material};else if(i[Xe])Object.keys(i).length>1&&ve.warn("Extraneous material assignments ignored.");else{let t=Object.keys(e);for(let e of t)i[e]||ve.warn(`Surface '${e}' not assigned a material, using default.`);let s=Object.keys(i);for(let i of s)e[i]||ve.warn(`Surface '${i}' not found.`)}return{surfaces:e,materials:i}}(t);for(let[a,l]of Object.entries(n)){if("all"!==l&&!Array.isArray(l)&&"object"!=typeof l){ve.warn(`Unknown face indices type, skipping surface '${a}'.`);continue}let n=[];if("geometry:mesh"===t.type)if("all"===l){let t=e.indices.length/3;n.push(...We(0,t))}else if(Array.isArray(l))n.push(...l);else{let{start:t,end:e}=l;n.push(...We(t,e))}else if("all"===l)for(let t of r){let{index:e,count:i}=t;n.push(...We(e,e+i))}else if(Array.isArray(l))for(let t=0;t<l.length;t++){let e=r[l[t]],{index:i,count:s}=e;n.push(...We(i,i+s))}else{let{start:t,end:e}=l;for(let i=t;i<e;i++){let t=r[i],{index:e,count:s}=t;n.push(...We(e,e+s))}}let h,{vertices:u,indices:c,normals:d,uvs:p}=e;h=o[Xe]?o[Xe]:o[a]??"default";let f=Ge(h,i),m={name:a,vertices:u,indices:Ye(c,n),material:f};d&&(m.normals=He(d,3,n)),p&&(m.uvs=He(p,2,n)),s.push(m)}return s}function je(t,e){let i=function(t){if(Array.isArray(t))return[t];if("vector3:list"===t.type)return t.list;if("vector3:range"===t.type){let{start:e,step:i,count:s}=t.range;return function(t,e,i){let s=[];for(let r=0;r<i;r++){let i=t[0]+r*e[0],n=t[1]+r*e[1],o=t[2]+r*e[2];s.push([i,n,o])}return s}(e,i,s)}return ve.warn(`Unknown position type: ${t}`),[[0,0,0]]}(t),s=function(t){if("number"==typeof t)return[t];if("number:list"===t.type)return t.list;if("number:range"===t.type){let{start:e,step:i,count:s}=t.range;return function(t,e,i){let s=[];for(let r=0;r<i;r++){let i=t+r*e;s.push(i)}return s}(e,i,s)}return ve.warn(`Unknown rotation type: ${t}`),[0]}(e),r=Math.max(i.length,s.length),n=[];for(let o=0;o<r;o++){let t=i[Math.min(o,i.length-1)],e=s[Math.min(o,s.length-1)];void 0!==t&&void 0!==e&&n.push({position:t,rotation:e})}return n}function ze(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Ve(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var i=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};i.prototype=e.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(i,e,s.get?s:{enumerable:!0,get:function(){return t[e]}})}),i}var qe={exports:{}};function Je(t,e){return t<e?-1:t>e?1:0}const Ke=/* @__PURE__ */Ve(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:class{constructor(t=[],e=Je){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(t){this.data.push(t),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:i}=this,s=e[t];for(;t>0;){const r=t-1>>1,n=e[r];if(i(s,n)>=0)break;e[t]=n,t=r}e[t]=s}_down(t){const{data:e,compare:i}=this,s=this.length>>1,r=e[t];for(;t<s;){let s=1+(t<<1),n=e[s];const o=s+1;if(o<this.length&&i(e[o],n)<0&&(s=o,n=e[o]),i(n,r)>=0)break;e[t]=n,t=s}e[t]=r}}},Symbol.toStringTag,{value:"Module"})));var Ze;const Qe=/* @__PURE__ */ze(function(){if(Ze)return qe.exports;Ze=1;var t=Ke;function e(e,r,n){var o,a,l,h;r=r||1;for(var u=0;u<e[0].length;u++){var c=e[0][u];(!u||c[0]<o)&&(o=c[0]),(!u||c[1]<a)&&(a=c[1]),(!u||c[0]>l)&&(l=c[0]),(!u||c[1]>h)&&(h=c[1])}var d=l-o,p=h-a,f=Math.min(d,p),m=f/2;if(0===f){var g=[o,a];return g.distance=0,g}for(var y=new t(void 0,i),v=o;v<l;v+=f)for(var x=a;x<h;x+=f)y.push(new s(v+m,x+m,m,e));var b=function(t){for(var e=0,i=0,r=0,n=t[0],o=0,a=n.length,l=a-1;o<a;l=o++){var h=n[o],u=n[l],c=h[0]*u[1]-u[0]*h[1];i+=(h[0]+u[0])*c,r+=(h[1]+u[1])*c,e+=3*c}return 0===e?new s(n[0][0],n[0][1],0,t):new s(i/e,r/e,0,t)}(e),w=new s(o+d/2,a+p/2,0,e);w.d>b.d&&(b=w);for(var _=y.length;y.length;){var P=y.pop();P.d>b.d&&(b=P,n&&console.log("found best %d after %d probes",Math.round(1e4*P.d)/1e4,_)),P.max-b.d<=r||(m=P.h/2,y.push(new s(P.x-m,P.y-m,m,e)),y.push(new s(P.x+m,P.y-m,m,e)),y.push(new s(P.x-m,P.y+m,m,e)),y.push(new s(P.x+m,P.y+m,m,e)),_+=4)}n&&(console.log("num probes: "+_),console.log("best distance: "+b.d));var E=[b.x,b.y];return E.distance=b.d,E}function i(t,e){return e.max-t.max}function s(t,e,i,s){this.x=t,this.y=e,this.h=i,this.d=function(t,e,i){for(var s=!1,n=1/0,o=0;o<i.length;o++)for(var a=i[o],l=0,h=a.length,u=h-1;l<h;u=l++){var c=a[l],d=a[u];c[1]>e!=d[1]>e&&t<(d[0]-c[0])*(e-c[1])/(d[1]-c[1])+c[0]&&(s=!s),n=Math.min(n,r(t,e,c,d))}return 0===n?0:(s?1:-1)*Math.sqrt(n)}(t,e,s),this.max=this.d+this.h*Math.SQRT2}function r(t,e,i,s){var r=i[0],n=i[1],o=s[0]-r,a=s[1]-n;if(0!==o||0!==a){var l=((t-r)*o+(e-n)*a)/(o*o+a*a);l>1?(r=s[0],n=s[1]):l>0&&(r+=o*l,n+=a*l)}return(o=t-r)*o+(a=e-n)*a}return t.default&&(t=t.default),qe.exports=e,qe.exports.default=e,qe.exports}());function ti(t,e){return[t[0]+e[0],t[1]+e[1]]}function ei(t){let e;return 0===t[0]?e=t[1]>0?Math.PI/2:t[1]<0?3*Math.PI/2:0:(e=Math.atan2(t[1],t[0]),e<0&&(e+=2*Math.PI)),e}function ii(t,e){return t[0]*e[1]-t[1]*e[0]}function si(t,e,i){return Math.abs(t[0]-e[0])<=i&&Math.abs(t[1]-e[1])<=i}function ri(t){return Math.sqrt(function(t){return t[0]*t[0]+t[1]*t[1]}(t))}function ni(t,e){return ri(ui(e,t))}function oi(t,e,i){return[t[0]+i*(e[0]-t[0]),t[1]+i*(e[1]-t[1])]}function ai(t){let e=ri(t);return[t[0]/e,t[1]/e]}function li(t){return[-t[1],t[0]]}function hi(t,e){return[t[0]*e,t[1]*e]}function ui(t,e){return[t[0]-e[0],t[1]-e[1]]}function ci(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}function di(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function pi(t,e){return function(t){return Math.hypot(t[0],t[1],t[2])}(di(e,t))}function fi(t,e,i){return[t[0]+i*(e[0]-t[0]),t[1]+i*(e[1]-t[1]),t[2]+i*(e[2]-t[2])]}function mi(t,e,i){let s=ii(ui(e,t),ui(i,t));return s>1e-7?1:s<-1e-7?-1:0}function gi(t,e){return ei([e[0]-t[0],e[1]-t[1]])}function yi(t,e,i,s){let r=ui(e,t),n=ui(s,i),o=function(t,e){return t[0]*e[0]+t[1]*e[1]}(r,n),a=ii(r,n);return Math.atan2(Math.abs(a),o)}function vi(t,e){let i=!1;const s=t[0],r=t[1];for(let n=0;n<e.length;n++){const t=e[n],o=n===e.length-1?e[0]:e[n+1];if(t[1]<r&&o[1]>=r||o[1]<r&&t[1]>=r){const e=o[0]-t[0],n=o[1]-t[1];Math.abs(n)>=1e-9&&t[0]+(r-t[1])/n*e<s&&(i=!i)}}return i}function xi(t,e){if(!vi(t,e[0]))return!1;for(let i=1;i<e.length;i++){if(vi(t,e[i]))return!1}return!0}function bi(t,e,i){return function(t,e,i){const s=ui(i,e),r=s[0]*s[0]+s[1]*s[1];let n;if(r<1e-9)n=e;else{const o=((t[0]-e[0])*s[0]+(t[1]-e[1])*s[1])/r;n=o<0?e:o>1?i:oi(e,i,o)}const o=ui(n,t);return o[0]*o[0]+o[1]*o[1]}(t,e,i)**.5}function wi(t){let e=0;for(let i=0;i<t.length;i++){let s=i,r=i<t.length-1?i+1:0,n=t[s],o=t[r];e+=n[0]*o[1]-o[0]*n[1]}return.5*e}function _i(t){return Math.abs(wi(t))}function Pi(t,e=.1){let i;if(function(t){if(0===t.length)return 0;let e=_i(t[0]);for(let i=1;i<t.length;i++)e-=_i(t[i]);return e}(t)<.1)i=function(t){const{min:e,max:i}=W([t]);return[e[0]+(i[0]-e[0])/2,e[1]+(i[1]-e[1])/2]}(t[0]);else{const s=Qe(t,e);i=[s[0],s[1]]}return i}function Ei(t){return wi(t)>0}function Ti(t,e,i){if(0!==t[0]||0!==t[1]||0!==t[2]||0!==e){let s=nt(),r=ft(t[0],t[1],t[2]),n=function(t=0,e=[0,1,0]){let i=t*Math.PI/180,s=_t();return Pt(s,e,i),s}(e,i);return function(t,e,i){var s=e[0],r=e[1],n=e[2],o=e[3],a=s+s,l=r+r,h=n+n,u=s*a,c=s*l,d=s*h,p=r*l,f=r*h,m=n*h,g=o*a,y=o*l,v=o*h;t[0]=1-(p+m),t[1]=c+v,t[2]=d-y,t[3]=0,t[4]=c-v,t[5]=1-(u+m),t[6]=f+g,t[7]=0,t[8]=d+y,t[9]=f-g,t[10]=1-(u+p),t[11]=0,t[12]=i[0],t[13]=i[1],t[14]=i[2],t[15]=1}(s,n,r),s}return nt()}function Ai(t){let e=dt(),i=_t();ut(e,t),ct(i,t);let s=dt(),r=(n=s,o=i,a=2*Math.acos(o[3]),(l=Math.sin(a/2))>st?(n[0]=o[0]/l,n[1]=o[1]/l,n[2]=o[2]/l):(n[0]=1,n[1]=0,n[2]=0),a);var n,o,a,l;return 0===r&&(s=[0,1,0]),{position:[e[0],e[1],e[2]],rotation:180*r/Math.PI,rotationAxis:[s[0],s[1],s[2]]}}function Ii(t,e){let i=dt();for(let s=0;s<t.length;s+=3)i[0]=t[s],i[1]=t[s+1],i[2]=t[s+2],bt(i,i,e),t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2]}function Si(t){let e=function(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=e[0],t[5]=e[1],t}(function(){var t=new rt(6);return rt!=Float32Array&&(t[1]=0,t[2]=0,t[4]=0,t[5]=0),t[0]=1,t[3]=1,t}(),t.position);return function(t,e,i){var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],l=e[5],h=Math.sin(i),u=Math.cos(i);t[0]=s*u+n*h,t[1]=r*u+o*h,t[2]=s*-h+n*u,t[3]=r*-h+o*u,t[4]=a,t[5]=l}(e,e,-t.rotation*Math.PI/180),e}function Ci(t,e){return function(t,e){let i=function(t,e,i){var s=e[0],r=e[1];return t[0]=i[0]*s+i[2]*r+i[4],t[1]=i[1]*s+i[3]*r+i[5],t}(Tt(),t.position,e),s=t.rotation+Math.atan2(-e[1],e[0])*(180/Math.PI);return{position:[i[0],i[1]],rotation:(r=s,n=360,(r%n+n)%n)};var r,n}(t,Si(e))}function Mi(t,e){return t.map(t=>{let{position:i}=Ci({position:t,rotation:0},e);return i})}function Oi({position:t=[0,0,0],rotation:e=0,rotationAxis:i=[0,1,0],name:s,vertices:r,indices:n,normals:o,uvs:a,material:l}){let h=je(t,e),u=[],c=[],d=[],p=[],f=nt();for(let g=0;g<h.length;g++){let t=h[g],{position:e,rotation:s}=t,l=Ti(e,s,i),m=r.slice();Ii(m,l);let y=u.length/3;for(const i of m)u.push(i);for(const i of n)c.push(y+i);if(Array.isArray(o)){ot(f,l),f[12]=0,f[13]=0,f[14]=0,at(f,f),lt(f,f);let t=o.slice();Ii(t,f),d.push(...t)}Array.isArray(a)&&p.push(...a)}let m={name:s,vertices:u,indices:c,material:l};return Array.isArray(o)&&(m.normals=d),Array.isArray(a)&&(m.uvs=p),m}class Ni{constructor(){this.polygons=[]}clone(){const t=new Ni;for(const e of this.polygons)t.polygons.push(e.clone());return t}toPolygons(){return this.polygons}union(t){var e=new Ni.Node(this.clone().polygons),i=new Ni.Node(t.clone().polygons);return e.clipTo(i),i.clipTo(e),i.invert(),i.clipTo(e),i.invert(),e.build(i.allPolygons()),Ni.fromPolygons(e.allPolygons())}subtract(t){var e=new Ni.Node(this.polygons),i=new Ni.Node(t.polygons);return e.invert(),e.clipTo(i),i.clipTo(e),i.invert(),i.clipTo(e),i.invert(),e.build(i.allPolygons()),e.invert(),Ni.fromPolygons(e.allPolygons())}intersect(t){var e=new Ni.Node(this.clone().polygons),i=new Ni.Node(t.clone().polygons);return e.invert(),i.clipTo(e),i.invert(),e.clipTo(i),i.clipTo(e),e.build(i.allPolygons()),e.invert(),Ni.fromPolygons(e.allPolygons())}inverse(){var t=this.clone();return t.polygons.forEach(function(t){t.flip()}),t}}(t=>{function e(t){return[-t[0],-t[1],-t[2]]}function i(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function s(t){const e=function(t){return Math.sqrt(i(t,t))}(t);return[t[0]/e,t[1]/e,t[2]/e]}t.fromPolygons=function(e){var i=new t;return i.polygons=e,i};t.Vertex=class{constructor(t,e){this.pos=t,this.normal=e}clone(){return new t.Vertex([...this.pos],this.normal?[...this.normal]:void 0)}flip(){this.normal&&(this.normal=e(this.normal))}interpolate(e,i){return new t.Vertex(fi(this.pos,e.pos,i),this.normal&&e.normal?fi(this.normal,e.normal,i):void 0)}};const r=class{constructor(t,e){this.normal=t,this.w=e}clone(){return new t.Plane([...this.normal],this.w)}flip(){this.normal=e(this.normal),this.w=-this.w}splitPolygon(e,s,r,n,o){for(var a=0,l=[],h=0;h<e.vertices.length;h++){var u=(v=i(this.normal,e.vertices[h].pos)-this.w)<-t.Plane.EPSILON?2:v>t.Plane.EPSILON?1:0;a|=u,l.push(u)}switch(a){case 0:(i(this.normal,e.plane.normal)>0?s:r).push(e);break;case 1:n.push(e);break;case 2:o.push(e);break;case 3:var c=[],d=[];for(h=0;h<e.vertices.length;h++){var p=(h+1)%e.vertices.length,f=l[h],m=l[p],g=e.vertices[h],y=e.vertices[p];if(2!=f&&c.push(g),1!=f&&d.push(2!=f?g.clone():g),3==(f|m)){var v=(this.w-i(this.normal,g.pos))/i(this.normal,di(y.pos,g.pos)),x=g.interpolate(y,v);c.push(x),d.push(x.clone())}}c.length>=3&&n.push(new t.Polygon(c,e.shared)),d.length>=3&&o.push(new t.Polygon(d,e.shared))}}};r.EPSILON=1e-5,r.fromPoints=function(e,r,n){var o,a,l=s((o=di(r,e),a=di(n,e),[o[1]*a[2]-o[2]*a[1],o[2]*a[0]-o[0]*a[2],o[0]*a[1]-o[1]*a[0]]));return new t.Plane(l,i(l,e))};let n=r;t.Plane=n;t.Polygon=class{constructor(e,i){this.vertices=e,this.shared=i,this.plane=t.Plane.fromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=[];for(const t of this.vertices)e.push(t.clone());return new t.Polygon(e,this.shared)}flip(){this.vertices.reverse();for(const t of this.vertices)t.flip();this.plane.flip()}};t.Node=class{constructor(t){this.plane=null,this.front=null,this.back=null,this.polygons=[],t&&this.build(t)}clone(){var e=new t.Node;e.plane=this.plane&&this.plane.clone(),e.front=this.front&&this.front.clone(),e.back=this.back&&this.back.clone();for(const t of this.polygons)e.polygons.push(t.clone());return e}invert(){var t;for(let i=0;i<this.polygons.length;i++)this.polygons[i].flip();null==(t=this.plane)||t.flip(),this.front&&this.front.invert(),this.back&&this.back.invert();const e=this.front;this.front=this.back,this.back=e}clipPolygons(t){if(!this.plane)return t.slice();for(var e=[],i=[],s=0;s<t.length;s++)this.plane.splitPolygon(t[s],e,i,e,i);this.front&&(e=this.front.clipPolygons(e)),i=this.back?this.back.clipPolygons(i):[];const r=new Array(e.length+i.length);for(let n=0;n<e.length;n++)r[n]=e[n];for(let n=0;n<i.length;n++)r[e.length+n]=i[n];return r}clipTo(t){this.polygons=t.clipPolygons(this.polygons),this.front&&this.front.clipTo(t),this.back&&this.back.clipTo(t)}allPolygons(t=!0){var e=t?this.polygons.slice():this.polygons;return this.front&&(e=e.concat(this.front.allPolygons(!1))),this.back&&(e=e.concat(this.back.allPolygons(!1))),e}build(e){if(e.length){this.plane||(this.plane=e[0].plane.clone());for(var i=[],s=[],r=0;r<e.length;r++)this.plane.splitPolygon(e[r],this.polygons,this.polygons,i,s);i.length&&(this.front||(this.front=new t.Node),this.front.build(i)),s.length&&(this.back||(this.back=new t.Node),this.back.build(s))}}}})(Ni||(Ni={}));const Li=Ni;function Ri(t,e,i){let s=.5*i,r=[[-s,-s,0],[s,-s,0],[s,s,0],[-s,s,0]],{u:n,v:o,n:a}=function(t){const e=1/Math.sqrt(2);let i=[0,0,0],s=[0,0,0],r=[0,0,0];return vt(r,t),xt(i,Math.abs(r[1])<e?ft(0,1,0):ft(1,0,0),t),xt(s,t,i),vt(i,i),vt(s,s),{u:i,v:s,n:r}}(e),l=t,h=function(t,e,i,s,r,n,o,a,l,h,u,c,d,p,f,m){var g=new rt(16);return g[0]=t,g[1]=e,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=u,g[11]=c,g[12]=d,g[13]=p,g[14]=f,g[15]=m,g}(n[0],n[1],n[2],0,o[0],o[1],o[2],0,a[0],a[1],a[2],0,l[0],l[1],l[2],1);for(let u of r)bt(u,u,h);return r}function Bi(t,e){const i=[],s=t.nextId++,{name:r,vertices:n,indices:o,material:a}=e;for(let l=0;l<o.length;l+=3){const t=3*o[l],e=3*o[l+1],h=3*o[l+2],u=[n[t],n[t+1],n[t+2]],c=[n[e],n[e+1],n[e+2]],d=[n[h],n[h+1],n[h+2]],p=[new Li.Vertex(u),new Li.Vertex(c),new Li.Vertex(d)];i.push(new Li.Polygon(p,{id:s,name:r,material:a}))}return i}function ki(){let t=Math.random(),e=Math.random(),i=Math.random();return Ue({name:De([t,e,i]),color:[t,e,i],opacity:1})}function Fi(t,e){const i=[],s=[],r={};for(let n=0;n<e.length;n++){const o=3*e[n],a=t[o],l=t[o+1],h=t[o+2],u=73856093*a^19349663*l^83492791*h;let c=r[u];void 0===c&&(c=i.push(a,l,h)/3-1,r[u]=c),s.push(c)}return{vertices:i,indices:s}}function Di(t,e){const i=[];for(const s of e){const e=Bi(t,s);for(const t of e)i.push(t)}return Li.fromPolygons(i)}function Ui(t,{debugMode:e=!1,sharedVertices:i=!0}={}){const s={},{polygons:r}=t;for(let n=0;n<r.length;n++){const t=r[n],i=t.vertices.length;if(i<3){ve.warn(`Skipping CSG polygon with '${i}' '${1===i?"vertex":"vertices"}.`);continue}const o=[];o.length=3*i;for(let e=0;e<i;e++){const i=t.vertices[e];o[3*e]=i.pos[0],o[3*e+1]=i.pos[1],o[3*e+2]=i.pos[2]}let a;if(3===i)a=[0,1,2];else{a=[];for(let t=1;t<i-1;t++)a.push(0,t,t+1)}if(e){const t=ki();s[n]={name:t.name,vertices:o,indices:a,material:t}}else{const{id:e,name:i,material:r}=t.shared,n=s[e];if(n){const t=n.vertices.length;n.vertices.length=t+o.length;for(let s=0;s<o.length;s++)n.vertices[t+s]=o[s];const e=n.indices.length;n.indices.length=e+a.length;const i=t/3;for(let s=0;s<a.length;s++)n.indices[e+s]=a[s]+i}else s[e]={name:i,vertices:o,indices:a,material:r}}}if(i)for(const n of Object.values(s)){const{vertices:t,indices:e}=n,i=Fi(t,e);n.vertices=i.vertices,n.indices=i.indices}return Object.values(s)}function Gi(t,e,i,s){let r,n,o,a,l;if("string"==typeof t){if(r=t,l=e[r],!l)return ve.warn(`Geometry '${r}' not found.`),[];n=[0,0,0],o=0,a=[0,1,0]}else{let i=t;if("string"==typeof i.geometry){if(r=i.geometry,l=e[r],!l)return ve.warn(`Geometry '${r}' not found.`),[]}else l=i.geometry;n=i.position??[0,0,0],o=i.rotation??0,a=i.rotationAxis??[0,1,0]}if(s.indexOf(l)>-1)return ve.warn(`Cycle detected while resolving geometry '${l.id}'.`),[];let h=os(l,e,i,s);"string"!=typeof t&&"csg:clip"!==t.type&&function(t,e,i,s){let r;if(t.material?t.materials?ve.warn("Cannot use 'material' and 'materials' at the same time."):r={[Xe]:t.material}:t.materials&&(0===Object.keys(t.materials).length?ve.warn("Empty 'materials' field not allowed."):r=t.materials),r)if(r[Xe]){let t=Ge(r[Xe],i);for(let i of e)i.material=t;Object.keys(r).length>1&&ve.warn(`Extraneous material assignments to '${s}' ignored.`)}else for(let[n,o]of Object.entries(r)){let t=e.find(t=>t.name===n);if(t){let e=Ge(o,i);t.material=e}else ve.warn(`Surface '${n}' not found in geometry '${s}', skipping material assignment.`)}}(t,h,i,l.id);let u=[];for(let c of h){let{name:t,vertices:e,indices:i,normals:s,uvs:r,material:l}=c,h=Oi({position:n,rotation:o,rotationAxis:a,name:t,vertices:e,indices:i,normals:s,uvs:r,material:l});u.push(h)}return u}function Xi(t,e,i,s,r){return[...t,...Gi(e,i,s,r)]}function Wi(t,e,i,s){let{plane:r,material:n}=i,o=Di(t,e);{let e=function(t,e,i,s,r=100){let n=t.nextId++,{position:o,normal:a}=e,l=Ge(i,s),h=[0,0,0],u=[0,0,0];vt(h,a),function(t,e,i,s){t[0]=e[0]+i[0]*s,t[1]=e[1]+i[1]*s,t[2]=e[2]+i[2]*s}(u,o,h,r);let c=Ri(o,h,r),d=Ri(u,h,r),p=c.concat(d),f=[[0,1,2,3],[4,5,6,7],[0,4,5,1],[1,5,6,2],[2,6,7,3],[3,7,4,0]],m=[];for(let g of f){let t=[];for(let i of g)t.push(new Li.Vertex(p[i]));let e=new Li.Polygon(t,{id:n,name:"",material:l});m.push(e)}return Li.fromPolygons(m)}(t,r,n,s);o.polygons.length>0&&(o=o.subtract(e))}return Ui(o,{debugMode:!1})}function Yi(t,e,i,s,r,n){const o=Gi(i,s,r,n),a=Di(t,e),l=Di(t,o);let h=[];if(a.polygons.length&&l.polygons.length){let t;switch(i.type){case"csg:subtract":t=a.subtract(l);break;case"csg:union":t=a.union(l);break;case"csg:intersect":t=a.intersect(l);break;default:t=a}h=Ui(t,{debugMode:!1})}return h}function Hi(t,e,i){e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2]}function $i(t,e,i){t[i+0]=e[0],t[i+1]=e[1],t[i+2]=e[2]}function ji(t,e){let i=new Array(3*e.length),s=dt(),r=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=0;for(let u=0;u<e.length;u+=3){let c=e[u],d=e[u+1],p=e[u+2];Hi(t,s,3*c),Hi(t,r,3*d),Hi(t,n,3*p),wt(o,r,s),wt(a,n,s),xt(l,o,a),vt(l,l),$i(i,l,h+0),$i(i,l,h+3),$i(i,l,h+6),h+=9}return i}function zi(t,e){let i=new Array(3*e.length),s=dt(),r=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=e.length/3,u=new Array(h),c=0;for(let f=0;f<e.length;f+=3){let i=e[f],h=e[f+1],d=e[f+2];Hi(t,s,3*i),Hi(t,r,3*h),Hi(t,n,3*d),wt(o,r,s),wt(a,n,s),xt(l,o,a),vt(l,l),u[c++]={index1:i,index2:h,index3:d,normal1:pt(l),normal2:pt(l),normal3:pt(l)}}let d=[];for(let f=0;f<t.length;f++)d[f]={normals:[],normal:dt()};for(let f=0;f<u.length;f++){let t=u[f],{index1:e,index2:i,index3:s}=t;d[e].normals.push(t.normal1),d[i].normals.push(t.normal2),d[s].normals.push(t.normal3)}for(let f=0;f<d.length;f++){let t=d[f],e=t.normals.length;if(e>0){let i=t.normal;mt(i,0,0,0);for(let s=0;s<e;s++)gt(i,i,t.normals[s]);vt(i,i)}}let p=0;for(let f=0;f<e.length;f+=3){let t=e[f],s=e[f+1],r=e[f+2],n=d[t].normal,o=d[s].normal,a=d[r].normal;$i(i,n,p+0),$i(i,o,p+3),$i(i,a,p+6),p+=9}return i}function Vi(t,e,i){e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2]}function qi(t,e){let i=new Array(2*e.length),s=dt(),r=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=0;for(let u=0;u<e.length;u+=3){let c,d,p=e[u],f=e[u+1],m=e[u+2];Vi(t,s,3*p),Vi(t,r,3*f),Vi(t,n,3*m),wt(o,r,s),wt(a,n,s),xt(l,o,a),vt(l,l),l[0]=Math.abs(l[0]),l[1]=Math.abs(l[1]),l[2]=Math.abs(l[2]),l[0]>=l[1]&&l[0]>=l[2]?(c=2,d=1):l[1]>=l[0]&&l[1]>=l[2]?(c=0,d=2):(c=0,d=1),i[h++]=s[c],i[h++]=s[d],i[h++]=r[c],i[h++]=r[d],i[h++]=n[c],i[h++]=n[d]}return i}function Ji(t,e){let i=new Array(2*e.length),s=0;for(let r=0;r<e.length;r++){let n=3*e[r],o=t[n],a=t[n+1],l=t[n+2],h=.5+Math.atan2(o,l)/(2*Math.PI),u=.5+Math.asin(a)/Math.PI;i[s++]=h,i[s++]=u}return i}function Ki(t,e,i){let s=Math.cos(e),r=Math.sin(e);return[t*r*Math.cos(i),t*s,t*r*Math.sin(i)]}const Zi=48,Qi=12;function ts(t,e){return[e*Math.cos(t),-e*Math.sin(t)]}function es(t,e,i,s=!0){let r=[],n=e-t,o=function(t,e){let i=Math.ceil(Zi/(2*Math.PI)*t*e);const s=Math.ceil(Qi/(2*Math.PI)*t);return Math.max(s,i)}(Math.abs(n),i),a=n/o;for(let l=0;l<o;l++){let e=ts(t+l*a,i);r.push(e)}if(s){let t=ts(e,i);r.push(t)}return r}function is(t){let e=[];switch(t.type){case"curve:line":e.push(t.start,t.end);break;case"curve:arc":e=es(Math.PI*t.startAngle/180,Math.PI*t.endAngle/180,t.radius);break;case"curve:polyline":e=t.points}return e}function ss(t){let e=[],i=[],s=[];switch(t.type){case"curve:circle":e=es(0,2*Math.PI,t.radius,!1),i.push({index:0,count:e.length});break;case"curve:polygon":e=t.points;for(let t=0;t<e.length;t++)i.push({index:t,count:1});break;case"curve:polygonWithHoles":e=t.polygons[0];for(let t=0;t<e.length;t++)i.push({index:t,count:1});const r=t.polygons.slice(1);if(r.length>=1){const t=r.length>1?Y(r):r;for(let e of t)s.push(ss({type:"curve:polygon",points:e}))}break;case"curve:rectangle":let{dimensions:n}=t,o=n[0],a=n[1];e=[[0,0],[0,a],[o,a],[o,0]];for(let t=0;t<e.length;t++)i.push({index:t,count:1});break;case"curve:composite":const l=1e-7;let h,u,c=t.segments;for(let t=0;t<c.length;t++){let s=is(c[t]),r=s[0],n=s[s.length-1];0===t||si(r,u,l)||ve.warn(`Composite curve segments ${t} and ${t+1} are not continuous.`),0===t&&(h=r),u=n,i.push({index:e.length,count:s.length-1}),e.push(...s.slice(0,s.length-1))}c.length>0&&!si(u,h,l)&&ve.warn("Composite curve not closed.")}return{points:e,segmentRanges:i,holes:s}}function rs(t,e,i){let s,r=i.holes??[],n=i.y??0,o=i.flipSide??!1,a=t,l=[];if(8===a.length&&0===r.length){s=(e?o:!o)?[3,0,1,1,2,3]:[1,0,3,3,2,1]}else{if(r.length>0){let t=new Array(r.length);for(let e=0;e<r.length;e++)t[e]=a.length/2,a=a.concat(r[e]);s=Nt(a,t)}else s=Nt(a);if(!o)for(let t=0;t<s.length;t+=3){let e=s[t];s[t]=s[t+2],s[t+2]=e}}let h=0;for(let u=0;u<a.length;u+=2)l[h++]=a[u],l[h++]=n,l[h++]=a[u+1];return{vertices:l,indices:s}}function ns(t,e,i=0,s=!1){let r=new Array(2*t*3),n=0;for(let o=0;o<t;o++){o===t-1?s?(r[n++]=o+i,r[n++]=i,r[n++]=e+i,r[n++]=o+i,r[n++]=e+i,r[n++]=o+e+i):(r[n++]=e+i,r[n++]=i,r[n++]=o+i,r[n++]=o+e+i,r[n++]=e+i,r[n++]=o+i):s?(r[n++]=o+i,r[n++]=o+1+i,r[n++]=o+e+1+i,r[n++]=o+i,r[n++]=o+e+1+i,r[n++]=o+e+i):(r[n++]=o+e+1+i,r[n++]=o+1+i,r[n++]=o+i,r[n++]=o+e+i,r[n++]=o+e+1+i,r[n++]=o+i)}return r}function os(t,e,i,s=[]){var r;let n,o=[];switch(t.type){case"geometry:plane":n=function(t){let{normal:e,size:i,doubleSided:s}=t,r=Ri([0,0,0],e,i).flat(),n=[0,1,2,0,2,3],o=[{index:0,count:2}];return s&&(n=n.concat([0,2,1,0,3,2]),o.push({index:2,count:2})),{vertices:r,indices:n,faces:o}}(t);break;case"geometry:cuboid":n=function(t){let{dimensions:e}=t,i=e[0],s=e[1],r=e[2],n=[0,s,r,i,s,r,i,s,0,0,s,0,0,0,r,i,0,r,i,0,0,0,0,0],o=[];for(let a=0;a<6;a++)o.push({index:2*a,count:2});return{vertices:n,indices:[0,1,2,0,2,3,4,7,6,4,6,5,0,4,5,0,5,1,1,5,6,1,6,2,2,6,7,2,7,3,3,7,4,3,4,0],faces:o}}(t);break;case"geometry:sphere":n=function(t){const e=16,i=16;let s,r,n=t.radius,o=[],a=[],l="generator"===t.uvs?[]:void 0;o.push(0,n,0);for(let u=1;u<i;u++){let t=Math.PI*u/i;for(let i=0;i<e;i++){let s=Ki(n,t,2*Math.PI*i/e);o.push(s[0],s[1],s[2])}}let h=o.push(0,-n,0)/3-1;s=1,r=.9375;for(let u=0;u<e;u++){let t=1+u,i=1+(u+1)%e;if(a.push(0,i,t),l){let t=1-u/e,i=1-(u+1)/e,n=.5*(t+i);l.push(n,s,i,r,t,r)}}for(let u=0;u<14;u++)for(let t=0;t<e;t++){let s=1+u*e+t,r=1+u*e+(t+1)%e,n=1+(u+1)*e+(t+1)%e,o=1+(u+1)*e+t;if(a.push(s,r,n),a.push(s,n,o),l){let s=1-t/e,r=1-(u+1)/i,n=1-(t+1)/e,o=1-(u+2)/i;l.push(s,r,n,r,n,o),l.push(s,r,n,o,s,o)}}s=.0625,r=0;for(let u=0;u<e;u++){let t=225+u,i=225+(u+1)%e;if(a.push(t,i,h),l){let t=1-u/e,i=1-(u+1)/e,n=.5*(t+i);l.push(t,s,i,s,n,r)}}return{vertices:o,indices:a,uvs:l,faces:[{index:0,count:a.length/3}]}}(t);break;case"geometry:extrusion":n=function(t){let{profile:e,height:i}=t,s=ss(e),{points:r,segmentRanges:n,holes:o}=s,a=r.flat(),l=[],h=r.length,u=[{points:r,segmentRanges:n}];for(let _ of o)l.push(_.points.flat()),u.push(_),h+=_.points.length;let c=Ei(r),d=rs(a,c,{y:i,flipSide:!1,holes:l}),p=rs(a,c,{y:0,flipSide:!0,holes:l}),f=[];f.push(...d.vertices),f.push(...p.vertices);let m=d.indices,g=p.indices.map(t=>t+h),y=[];y.push(...m),y.push(...g);let v=m.length/3,x=[];x[0]={index:0,count:v},x[1]={index:v,count:v};let b=2*v,w=0;for(let _=0;_<u.length;_++){let{points:t,segmentRanges:e}=u[_],i=0===_?Ei(t):!Ei(t),s=ns(t.length,d.vertices.length/3,w,i);w=t.length,y.push(...s);for(let r of e){let t=b+2*r.index,e=2*r.count;x.push({index:t,count:e})}b+=2*t.length}return{vertices:f,indices:y,faces:x}}(t);break;case"geometry:mesh":n=function(t){let{vertices:e,indices:i,normals:s,uvs:r}=t,n={vertices:e,indices:i,faces:[]};return Array.isArray(s)&&(n.normals=s),Array.isArray(r)&&(n.uvs=r),n}(t);break;default:return ve.warn(`Invalid geometry type ${t.type}.`),o}o=$e(t,n,i),"geometry:plane"!==t.type&&"geometry:cuboid"!==t.type&&"geometry:sphere"!==t.type&&"geometry:extrusion"!==t.type||(null==(r=t.geometries)?void 0:r.length)&&(s.push(t),o=function(t,e,i,s,r){let n={nextId:0},o=t.geometries??[];for(let a of o)e="string"==typeof a||"reference:geometry"===a.type?Xi(e,a,i,s,r):"csg:clip"===a.type?Wi(n,e,a,s):Yi(n,e,a,i,s,r);return e}(t,o,e,i,s),s.pop());let a=[];for(let u of o){let{name:e,vertices:i,indices:s,normals:r,uvs:n,material:o}=u,{position:l,rotation:h,rotationAxis:c}=t,d=Oi({position:l,rotation:h,rotationAxis:c,name:e,vertices:i,indices:s,normals:r,uvs:n,material:o});a.push(d)}o=a;let l=t.normals??"flat";if("flat"===l||"smooth"===l)for(let u of o){let{vertices:t,indices:e}=u;u.normals="flat"===l?ji(t,e):zi(t,e)}let h=t.uvs??"automatic";if("automatic"==h||"spherical"===h)for(let u of o){let{vertices:t,indices:e}=u;u.uvs="automatic"===h?qi(t,e):Ji(t,e)}return o}function as(t){let e,i,s,r={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]};for(let n=0;n<t.length;n+=3)e=t[n],i=t[n+1],s=t[n+2],r.min[0]=Math.min(r.min[0],e),r.max[0]=Math.max(r.max[0],e),r.min[1]=Math.min(r.min[1],i),r.max[1]=Math.max(r.max[1],i),r.min[2]=Math.min(r.min[2],s),r.max[2]=Math.max(r.max[2],s);return r}function ls({min:t,max:e,transform:i}){if(0===i.rotation)return{min:ci(t,i.position),max:ci(e,i.position)};{let s=Ti(i.position,i.rotation,i.rotationAxis);const r=[[...t],[...e],[t[0],t[1],e[2]],[e[0],e[1],t[2]]];for(const t of r)bt(t,t,s);return as(r.flat())}}class hs{constructor(){this.vertices=[],this.edges=[],this.geometryProfile=[]}toJSON(){return{edges:this.edges.map(t=>t.id)}}}function us(t,e){return"integer"===e.type?"number"==typeof t&&Number.isInteger(t):typeof t===e.type&&(!("enum"in e)||e.enum.includes(t))}const cs={"spatialStructure:layout":"layout","layout:space":"space","product:static":"product","product:component":"product","spatialStructure:building":"building","spatialStructure:floor":"floor","element:asset":"element","element:beam":"element","element:casework":"element","element:column":"element","element:door":"element","element:kitchen":"element","element:railing":"element","element:ramp":"element","element:roof":"element","element:slab":"element","element:stairs":"element","element:stairFlight":"element","element:window":"element","element:generic":"element","element:floor":"element","element:ceiling":"element","element:boundaryWall":"element","element:curtainWall":"element","element:opening":"element","element:spaceDivider":"element","element:wall":"element"},ds=(t,e)=>{const i=cs[e];return i||ve.error(`Missing custom attribute resource type for node type: "${e}"`),`${t}:${i}`};function ps(t,e){if("boolean"===e.type&&"string"==typeof t){if("true"===t.toLowerCase())return!0;if("false"===t.toLowerCase())return!1}if("number"===e.type&&"string"==typeof t){const e=Number(t);if(!isNaN(e))return e}return null}class fs extends be{constructor(t,e){super(t,"customAttribute:definition"),this.attributes={resourceType:"space",schema:{type:"string"}},e&&this.setAttributes(e)}getInputType(){return function(t){switch(t.type){case"integer":return"Integer";case"boolean":return"Boolean";case"number":return"Number";case"string":return"enum"in t?"Select":"Text"}}(this.attributes.schema)}setAttributes(t){let e=this.attributes;e.resourceType=t.resourceType??e.resourceType,e.updatedAt=t.updatedAt??e.updatedAt,e.description=t.description??e.description,e.schema=function(t){return t.schema?JSON.parse(JSON.stringify(t.schema)):"Text"===t.valueType?{type:"string"}:"Number"===t.valueType?{type:"number"}:"Boolean"===t.valueType?{type:"boolean"}:void 0}(t)}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes))}toJSON(){const t=super.toJSON();let e={resourceType:this.attributes.resourceType,schema:JSON.parse(JSON.stringify(this.attributes.schema))};return void 0!==this.attributes.updatedAt&&(e.updatedAt=this.attributes.updatedAt),void 0!==this.attributes.description&&(e.description=this.attributes.description),t.attributes=e,t}}const ms={"customAttribute:definition":fs};class gs extends be{constructor(t,e){super(t,e),this.customAttributes={}}setCustomAttributes(t,e){let i=null,s=!1;if(null===t&&(this.customAttributes={},s=!0),t&&e)for(const r in t){let n=t[r];if(null===n){delete this.customAttributes[r],s=!0;continue}const o=ds(r,this.type),a=e[o];if(a){if(!us(n,a.attributes.schema)){let t=ps(n,a.attributes.schema);if(null===t){ve.error(`Value type mismatch for custom attribute. Received value: "${n}". Expected type: ${a.attributes.schema.type}`),i=`Value type mismatch for custom attribute. Received value: "${n}". Expected type: ${a.attributes.schema.type}`;continue}n=t}this.customAttributes[r]!==n&&(this.customAttributes[r]=n,s=!0)}else i=`Missing custom attribute definition for node key: "${r}", node type: "${this.type}" and definition id: ${o}`}s&&this.emit("node-custom-attributes-change",this),i&&ve.error(i)}toJSON(){const t=super.toJSON();return Object.keys(this.customAttributes).length>0&&(t.customAttributes=JSON.parse(JSON.stringify(this.customAttributes))),t}copyForClone(t){super.copyForClone(t),this.customAttributes=JSON.parse(JSON.stringify(t.customAttributes))}}class ys extends gs{constructor(t,e){super(t,e),this.layout=null}}class vs extends ys{constructor(){super(...arguments),this.axisAlignedBoundingBox=null,this.objectAlignedBoundingBox=null,this.boundingBoxContour=null,this.transform=null,this.worldTransform=null}calculateTransform(){return{position:[0,0,0],rotation:0,rotationAxis:[0,1,0]}}getTransform(){return this.transform||(this.transform=this.calculateTransform()),this.transform}calculateWorldTransform(){return this.getTransform()}getWorldTransform(){return this.worldTransform||(this.worldTransform=this.calculateWorldTransform()),this.worldTransform}resetTransform(t=!1){var e;this.transform=null,this.worldTransform=null,this.axisAlignedBoundingBox=null,this.boundingBoxContour=null,t&&(null==(e=this.layout)||e.spatialIndex.addNode(this))}resetBoundingBox(t=!1){var e;this.objectAlignedBoundingBox=null,this.axisAlignedBoundingBox=null,this.boundingBoxContour=null,t&&(null==(e=this.layout)||e.spatialIndex.addNode(this))}resetSpatialIndexing(){this.resetTransform(),this.resetBoundingBox(!0)}calculateBoundingBox(){return{min:[0,0,0],max:[0,0,0]}}getBoundingBox(t=!1){this.objectAlignedBoundingBox||(this.objectAlignedBoundingBox=this.calculateBoundingBox());const{min:e,max:i}=this.objectAlignedBoundingBox;return{min:e,max:i,transform:t?this.getTransform():this.getWorldTransform()}}getAxisAlignedBoundingBox(){return this.axisAlignedBoundingBox||(this.axisAlignedBoundingBox=ls(this.getBoundingBox())),this.axisAlignedBoundingBox}calculateBoundingBoxContour(t=!1){const{min:[e,,i],max:[s,,r],transform:n}=this.getBoundingBox(t),{position:[o,,a],rotation:l}=n;let h=[[e,i],[s,i],[s,r],[e,r]];return(o||a||l)&&(h=Mi(h,{position:[o,a],rotation:l})),h}getBoundingBoxContour(){return this.boundingBoxContour||(this.boundingBoxContour=this.calculateBoundingBoxContour()),this.boundingBoxContour}}class xs extends vs{}class bs extends xs{constructor(t,e,i){super(t,"spatialGraph:vertex"),this.position=[0,0],this.edges=[],this.position[0]=e,this.position[1]=i}sortVertexEdges(){let t=[];for(let e of this.edges){let i=this===e.vertices[0]?e.vertices[1]:e.vertices[0],s=ei([i.position[0]-this.position[0],i.position[1]-this.position[1]]);t.push({edge:e,edgeAngle:s})}t.sort((t,e)=>t.edgeAngle-e.edgeAngle),this.edges=t.map(t=>t.edge)}calculateTransform(){return{position:[this.position[0],0,this.position[1]],rotation:0,rotationAxis:[0,1,0]}}addEdge(t){this.edges.push(t),this.sortVertexEdges(),this.emit("vertex-add-edge",this,t)}removeEdge(t){let e=this.edges.indexOf(t);if(e>-1){let t=this.edges.splice(e,1)[0];this.emit("vertex-remove-edge",this,t)}else ve.error(`Vertex does not reference edge ${t.id}.`)}setPosition(t,e){this.position[0]=t,this.position[1]=e,this.edges.length>0&&(this.layout.spatialGraph.graphChanged=!0),this.resetSpatialIndexing(),this.emit("vertex-set-position",this)}resetSpatialIndexing(){super.resetSpatialIndexing();const t=/* @__PURE__ */new Set;for(const e of this.edges){e.resetSpatialIndexing();for(const i of e.spaces)i&&t.add(i)}for(const e of t)e.resetSpatialIndexing()}toJSON(){return{...super.toJSON(),position:[...this.position]}}}function ws(t,e,i,s,r=!1){if(e.layout)return ve.warn(`${s} ${e.id} already part of layout ${e.layout.id}.`),!1;if(i[e.id])return ve.error(`${s} ${e.id} already registered in layout.`),!1;let n=t.spaceGraph;if(n&&n.nodesById[e.id])return ve.error(`${s} ${e.id} already registered in space graph.`),!1;if(e.type.startsWith("space:")){let t=e;if(t.slabs.length>0)return ve.warn(`Detached space ${t.id} references boundary slab elements.`),!1}else if(e.type.startsWith("element:")){let n=e;if(r&&n.parent)return ve.warn(`${s} ${n.id} already a child of ${s} ${n.parent.id}.`),!1;for(let e of n.elements)if(!ws(t,e,i,s,!1))return!1}return!0}function _s(t,e){if(e.layout=t,t.elementsById[e.id])return void ve.error(`Element ${e.id} already registered.`);t.elementsById[e.id]=e;const i=t.elementsByType[e.type];i||(ve.warn(`unrecognized layout element type: ${e.type}`),t.elementsByType[e.type]=[]),i.push(e);let s=t.spaceGraph;s&&("element:asset"===e.type&&e.product&&!s.productsById[e.product.id]&&s.insertProduct(e.product),s.registerNode(e),s.emit("element-create",e));for(let r of e.elements)_s(t,r)}function Ps(t,e,i){for(let o of e.elements)Ps(t,o,e);if(t.elementsById[e.id]!==e)return void ve.error(`Entry ${e.id} in 'elements stored by ID' record does not contain this object.`);delete t.elementsById[e.id];const s=t.elementsByType[e.type],r=null==s?void 0:s.indexOf(e);if(!s||-1===r)return void ve.error(`element ${e.id} not found in 'elements stored by type' record.`);s.splice(r,1);let n=t.spaceGraph;n&&(n.unregisterNode(e),n.emit("element-delete",e,i)),e.layout=null}function Es(t){return"object"==typeof t&&null!==t}function Ts(t){return Es(t)&&!function(t){return Array.isArray(t)||ArrayBuffer.isView(t)}(t)}function As(t,e,i,s){Ts(t)&&Ts(e)||ve.error("Both arguments must be objects.");let{onNewKeys:r,copyScopes:n,cloneObjects:o}=s,a=Object.keys(e);for(let l of a){if(r){let{allow:e,excludedScopes:s}=r;if(e===(!!s&&s.includes(i))&&!(l in t)){ve.warn(`Key '${l}' not found in scope ${i}, skipped.`);continue}}let a=e[l],h=t[l];if(Es(a)){let e=`${i}.${l}`;!(null==n?void 0:n.includes(e))&&Ts(h)?As(h,a,e,s):t[l]=o?JSON.parse(JSON.stringify(a)):a}else t[l]=a}}function Is(t,e,i={onNewKeys:{allow:!1,excludedScopes:[]},copyScopes:[],cloneObjects:!0}){let s;i.onNewKeys?(s=i.onNewKeys,s.allow=i.onNewKeys.allow??!1,s.excludedScopes=i.onNewKeys.excludedScopes??[]):s={allow:!1,excludedScopes:[]},As(t,e,"",{onNewKeys:s,copyScopes:i.copyScopes??[],cloneObjects:i.cloneObjects??!0})}function Ss(t,e){t.name=e.name??t.name,t.customId=e.customId??t.customId}function Cs(t,e,i){t.setCustomAttributes(e.customAttributes,i)}function Ms(t){let e=t.getEdges();return 1===e.length?e[0].id:e.map(t=>t.id)}function Os(t){let e;switch(t.type){case"element:ceiling":case"element:floor":e=function(t){let e=[];for(let i of t.boundaries){let t=i.toJSON();e.push(t)}return{id:t.id,type:t.type,boundaries:e,parameters:{height:t.parameters.height,elevation:t.parameters.elevation,materials:{...t.parameters.materials}}}}(t);break;case"element:boundaryWall":e=function(t){let e=[];for(let s of t.boundaries){let t=s.toJSON();e.push(t)}let i=JSON.parse(JSON.stringify(t.parameters.surfaces));return{id:t.id,type:t.type,boundaries:e,parameters:{height:t.parameters.height,elevation:t.parameters.elevation,surfaces:i,materials:{...t.parameters.materials}}}}(t);break;case"element:curtainWall":e={id:(n=t).id,type:n.type,edge:Ms(n)};break;case"element:spaceDivider":e={id:(r=t).id,type:r.type,edge:Ms(r)};break;case"element:wall":e=function(t){let{width:e,height:i,offset:s,elevation:r,materials:n}=t.parameters;return{id:t.id,type:t.type,parameters:{width:e,height:i,offset:s,elevation:r,materials:{...n}},edge:Ms(t)}}(t);break;case"element:opening":e=function(t){let{position:e,dimensions:i,materials:s}=t.parameters;return{id:t.id,type:t.type,parameters:{position:[...e],dimensions:[...i],materials:{...s}}}}(t);break;case"element:asset":e={id:(i=t).id,type:i.type,position:[...i.position],rotation:i.rotation,rotationAxis:i.rotationAxis,product:null==(s=i.product)?void 0:s.id,geometries:JSON.parse(JSON.stringify(i.geometries))};break;case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:kitchen":case"element:railing":case"element:ramp":case"element:roof":case"element:slab":case"element:stairs":case"element:stairFlight":case"element:window":e=function(t){let e={id:t.id,type:t.type,position:[...t.position],parameters:JSON.parse(JSON.stringify(t.parameters)),rotation:t.rotation,rotationAxis:t.rotationAxis};return"element:generic"!==t.type&&"element:asset"!==t.type||(e.geometries=JSON.parse(JSON.stringify(t.geometries))),e}(t);break;default:return void ve.warn(`Unknown element type '${t.type}, skipping element.`)}var i,s,r,n,o,a;if(o=e,""!==(a=t).name&&(o.name=a.name),""!==a.customId&&(o.customId=a.customId),function(t,e){e.customAttributes===Object(e.customAttributes)&&Object.keys(e.customAttributes).length>0&&(t.customAttributes=e.customAttributes)}(e,t),t.elements.length){e.elements=[];for(let i of t.elements){let t=Os(i);t&&e.elements.push(t)}}return e}class Ns extends vs{constructor(){super(...arguments),this.parent=null,this.elements=[],this.geometries=[]}insertElement(t){let e=this.layout;e&&!ws(e,t,e.elementsById,"Element",!0)||(t.parent=this,this.elements.push(t),e&&_s(e,t))}get isExternal(){if(this.parent)return this.parent.isExternal;const t=this.getSpaces().flatMap(t=>t?[t]:[]);return!t.length||t[0].isExternal}resetTransform(t=!1){super.resetTransform(t);for(const e of this.elements)e.resetTransform(t)}resetBoundingBox(t=!1){super.resetBoundingBox(t);for(const e of this.elements)e.resetBoundingBox(t)}removeElement(t){if(t.parent!==this)return void ve.warn(`Element ${t.id} not a child of element ${this.id}.`);let e=this.elements.indexOf(t);if(-1===e)return void ve.error(`Element ${t.id} not found in parent ${this.id}.`);let i=t.parent;t.parent=null,this.elements.splice(e,1),t.layout&&Ps(t.layout,t,i)}copyForClone(t){super.copyForClone(t),this.parameters=JSON.parse(JSON.stringify(t.parameters)),this.geometries=JSON.parse(JSON.stringify(t.geometries))}setParameters(t){Is(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.resetBoundingBox(),this.emit("element-parameters-change",this)}getSpaces(){return this.parent?this.parent.getSpaces():[]}toJSON(){return Os(this)}}function Ls(t,e,i){let s=t.getAxisLength(),r=[];for(let n of t.elements)if("element:opening"===n.type){let t=n.parameters.position[0],o=t/s,a=(t+n.parameters.dimensions[0])/s;i?e>=o&&e<a&&r.push(n):e>o&&e<a&&r.push(n)}return r}class Rs extends Ns{constructor(t,e,i){super(t,e),me(this,ae),this.edges=[],this.vertices=[],this.boundingBoxTransform=null,this.edgesChanged=!1,this.setEdges(i)}setEdges(t){var e,i;if(!t.length)return this.edges=[],this.vertices=[],void ye(this,ae,le).call(this);if(1===t.length)return this.edges=[t[0]],this.vertices=[t[0].vertices[0],t[0].vertices[1]],void ye(this,ae,le).call(this);const s=function(t){var e;const i=/* @__PURE__ */new Map;for(const s of t)for(const t of s.vertices)i.has(t)||i.set(t,[]),null==(e=i.get(t))||e.push(s);return i}(t),r=[];let n,o;for(const[h,u]of s.entries())if(1===u.length){n=u[0];const t=n.vertices.find(t=>t!==h);if(2!==(null==(e=s.get(t))?void 0:e.length))return void ve.error("Edge sequence is not continuous");r.push(h,t),o=t;break}if(!n||!o)return void ve.error("Unable to find start of edge sequence");const a=[n];let l=n;for(;a.length<t.length;){const t=o&&(null==(i=s.get(o))?void 0:i.find(t=>t!==l));if(!t)return void ve.error("Edge sequence is not continuous");if(a.includes(t))return void ve.error("Duplicate Edge in sequence",t.id,l.id);const e=t.vertices.find(t=>t!==o);r.push(e),a.push(t),o=e,l=t}this.edges=a,this.vertices=r,ye(this,ae,le).call(this)}getEdges(){return[...this.edges]}getVertices(){return ye(this,ae,he).call(this),[...this.vertices]}getStartVertex(){return ye(this,ae,he).call(this),this.vertices.at(0)}getEndVertex(){return ye(this,ae,he).call(this),this.vertices.at(-1)}getAxisPoints(){const t=this.getStartVertex(),e=this.getEndVertex();return t&&e?[t.position,e.position]:[]}getAxisLength(){const[t,e]=this.getAxisPoints();return t&&e?ri(ui(t,e)):0}getEdgeAtLinearPosition(t){if(t<0||t>1)return;if(1===this.edges.length)return this.edges[0];let e=this.getAxisLength();if(!e)return;let i=this.vertices[0].position;for(let s=0;s<this.vertices.length-1;s++){if(ni(i,this.vertices[s+1].position)/e>=t)return this.edges[s]}}getEdgesAtLinearSegment(t,e){if(t>e)return[];if(1===this.edges.length)return[this.edges[0]];let i=this.getAxisLength();if(!i)return[];let s=[],r=this.vertices[0].position,n=r;for(let o=0;o<this.vertices.length-1;o++){let a=this.vertices[o+1].position,l=ni(r,n)/i,h=ni(r,a)/i;(t<=l&&e>=h||t>=l&&t<h||e>l&&e<=h)&&s.push(this.edges[o]),n=a}return s}resetTransform(){this.boundingBoxTransform=null,this.objectAlignedBoundingBox=null,super.resetTransform()}getBoundingBox(){this.objectAlignedBoundingBox||(this.objectAlignedBoundingBox=this.calculateBoundingBox());const{min:t,max:e}=this.objectAlignedBoundingBox;return this.boundingBoxTransform||(this.boundingBoxTransform=this.calculateBoundingBoxTransform()),{min:t,max:e,transform:this.boundingBoxTransform}}calculateBoundingBoxTransform(){const[t,e]=this.getAxisPoints();if(!t||!e)return super.calculateTransform();const i={rotation:-(gi(t,e)/Math.PI*180)};return{position:[t[0],0,t[1]],rotation:i.rotation,rotationAxis:[0,1,0]}}get edge(){return ve.warn("Use getEdges() instead of edge"),this.edges[0]||null}getAdjacentElementsByVertex(){let t=[[],[]];for(let e=0;e<this.vertices.length;e++){let i=this.vertices[e].edges.filter(t=>t.element&&t.element.id!==this.id).map(t=>t.element);t[e]=i}return t}getAdjacentSpacesBySide(){let t=[[],[]];for(let e=0;e<2;e++){let i=this.edges.filter(t=>t.spaces[e]).map(t=>t.spaces[e]);t[e]=i}return t}getSpaces(){let t=[];for(let e of this.edges)e.spaces[0]&&t.push(e.spaces[0]),e.spaces[1]&&t.push(e.spaces[1]);return t}getElementsAtLinearPosition(t){return Ls(this,t,!0)}get isExternal(){let t=0,e=0;for(const i of this.getEdges())i.isExternal?t+=i.getLength():e+=i.getLength();return t>=e}}function Bs(t){for(let e of t.elements)if("element:door"===e.type){let t=e.parameters;t.hingeSide="right"===t.hingeSide?"left":"right",t.doorSide="side1"===t.doorSide?"side2":"side1"}}ae=/* @__PURE__ */new WeakSet,le=function(){this.edgesChanged=!1,this.resetSpatialIndexing(),this.emit("element-edges-change",this)},he=function(){this.edgesChanged&&this.edges.length&&this.setEdges(this.edges)};class ks extends xs{constructor(t,e,i){super(t,"spatialGraph:edge"),this.spaces=[void 0,void 0],this.boundaryWalls=[null,null],this.element=null,this.vertices=[e,i]}getPoints(){return[this.vertices[0].position,this.vertices[1].position]}getLength(){return ni(...this.getPoints())}get isExternal(){return this.spaces.some(t=>!t||t.isExternal)}setVertices(t,e){if(t===e)return void ve.warn("Cannot set both edge vertices to the same vertex.");let i,s,r=this.vertices[0],n=this.vertices[1];this.vertices[0]=t,this.vertices[1]=e,r!==t?(r.removeEdge(this),t.addEdge(this),i=!0):i=!1,n!==e?(n.removeEdge(this),e.addEdge(this),s=!0):s=!1,this.layout.spatialGraph.graphChanged=!0,this.element&&(this.element.edgesChanged=!0),this.resetSpatialIndexing(),(i||s)&&this.emit("edge-set-vertices",this,{previousVertices:[r,n]})}resetSpatialIndexing(){super.resetSpatialIndexing(),this.element&&this.element.resetSpatialIndexing()}calculateBoundingBox(){const[t,e]=this.getPoints();return{min:[Math.min(t[0],e[0]),0,Math.min(t[1],e[1])],max:[Math.max(t[0],e[0]),0,Math.max(t[1],e[1])]}}setVerticesByIds(t,e){let i=this.layout.spatialGraph,s=i.verticesById[t];if(!s)return void ve.error(`Cannot find vertex ${t}.`);let r=i.verticesById[e];r?this.setVertices(s,r):ve.error(`Cannot find vertex ${e}.`)}canSplit(t,e={}){let{minimumLength:i}=e;if(void 0!==i){if(t<0||t>1)return!1;let[e,s]=this.getPoints(),r=oi(e,s,t),n=ri(ui(r,e)),o=ri(ui(r,s));if(n<i||o<i)return!1}else if(t<=0||t>=1)return!1;if(this.element){let[e,i]=this.getPoints(),s=oi(e,i,t),[r]=this.element.getAxisPoints();if(!r)return!1;let n=this.element.getAxisLength(),o=ni(r,s)/n;return 0===Ls(this.element,o,!1).length}return!0}split(t,e={},i=!1){var s,r,n;let o=this.layout.spatialGraph,a=this.vertices[0],l=this.vertices[1],h=null==(s=this.element)?void 0:s.getAxisLength(),u=null==(n=null==(r=this.element)?void 0:r.getStartVertex())?void 0:n.position,[c,d]=this.getPoints(),p=oi(c,d,t),f=e.vertexId??(this.layout.debugIds?o.debugVertexCount.toString():Ut()),m=o.verticesById[f]??o.createVertex(f,p[0],p[1]);this.setVertices(a,m);let g=e.edgeId??o.getEdgeId(),y=o.createEdge(g,m,l);if(y.spaces[0]=this.spaces[0],y.spaces[1]=this.spaces[1],y.boundaryWalls[0]=this.boundaryWalls[0],y.boundaryWalls[1]=this.boundaryWalls[1],this.element&&e.elementId&&h&&u){let i=ni(u,p)/h,s=this.element.getEdges(),r=s.indexOf(this)+1,n=[y,...s.splice(r)];this.element.setEdges(s);let o=e.elementId??this.layout.getElementId(this.element),a=this.layout.createElement(this.element.type,o,n);a.parameters=JSON.parse(JSON.stringify(this.element.parameters));let l=ni(u,p),c=[...this.element.elements];for(let e of c)if("element:opening"===e.type){let s=e.parameters.position[0],r=s/h,n=(s+e.parameters.dimensions[0])/h;i<=r?(e.parameters.position[0]=r*h-l,this.element.removeElement(e),a.insertElement(e)):t<n&&ve.warn(`Opening ${e.id} overlaps split position.`)}}else if(this.element){const t=this.element.getEdges();this.element.setEdges([...t,y]),y.element=this.element}if(i)for(let v of y.spaces){if(!v)continue;let{boundary:t}=v.getBoundaryFromEdge(this);if(t){let e,i=t.vertices.indexOf(a),s=t.vertices.indexOf(l);e=0===i&&s===t.vertices.length-1?s:0===s&&i===t.vertices.length-1||i<s?i:s,t.vertices.splice(e+1,0,m),t.edges=[];for(let r=0;r<t.vertices.length;r++){let e=r,i=r<t.vertices.length-1?r+1:0,s=t.vertices[e],n=t.vertices[i],a=o.getEdgeFromVertices(s,n);a?t.edges.push(a):ve.error(`Cannot find edge with vertices ${s.id} and ${n.id}.`)}}else ve.error(`Edge ${this.id} not found in space boundary.`)}for(let v of y.boundaryWalls){if(!v)continue;let t,e=v.boundaries[0],i=e.vertices.indexOf(a),s=e.vertices.indexOf(l);t=0===i&&s===e.vertices.length-1?s:0===s&&i===e.vertices.length-1||i<s?i:s,e.vertices.splice(t+1,0,m),e.edges=[];for(let r=0;r<e.vertices.length;r++){let t=r,i=r<e.vertices.length-1?r+1:0,s=e.vertices[t],n=e.vertices[i],a=o.getEdgeFromVertices(s,n);a?e.edges.push(a):ve.error(`Cannot find edge with vertices ${s.id} and ${n.id}.`)}}return{vertex:m,edge:y,element:undefined}}canMerge(t){if(this.element&&!t.element||!this.element&&t.element)return!1;let e,i=this.vertices[0],s=this.vertices[1],r=t.vertices[0],n=t.vertices[1];if(i===r)e=[s,i,n];else if(i===n)e=[s,i,r];else if(s===r)e=[i,s,n];else{if(s!==n)return!1;e=[i,s,r]}if(0!==mi(e[0].position,e[1].position,e[2].position))return!1;let o=e[1];return!(!o.edges.includes(this)||!o.edges.includes(t))}merge(t,e=!1){var i;if(this.element&&!t.element||!this.element&&t.element)return void ve.warn("Either none or both edges must have an element, cannot merge.");let s,r,n=this.layout.spatialGraph,o=this.vertices[0],a=this.vertices[1],l=t.vertices[0],h=t.vertices[1];if(o===l)s=[h,o,a],r=!0;else if(o===h)s=[l,o,a],r=!1;else if(a===l)s=[o,a,h],r=!1;else{if(a!==h)return void ve.warn(`Edge ${this.id} does not share a vertex with edge ${t.id}, cannot merge.`);s=[o,a,l],r=!0}let u=s[0].position,c=s[1].position;if(0!==mi(u,c,s[2].position))return void ve.warn(`Edges ${this.id} and ${t.id} are not collinear, cannot merge.`);let d=s[1];if(d.edges.includes(this)&&d.edges.includes(t)||ve.error(`Common vertex ${d.id} edge list does not contain either one or both edges, cannot merge.`),t.element&&r&&function(t){let e=t.getAxisLength();for(let i of t.elements){if("element:opening"!==i.type)continue;let t=i.parameters;t.position[0]=e-(t.position[0]+t.dimensions[0]),Bs(i)}}(t.element),this.setVertices(s[0],s[2]),this.element&&this.element===t.element){const e=this.element.getEdges(),i=e.indexOf(t);e.splice(i,1),this.element.setEdges(e),t.element=null}else if(this.element&&t.element){const e=t.element.getEdges(),s=e.indexOf(t);e.splice(s,1);let r=[...this.element.getEdges(),...e];this.element.setEdges(r),t.element.setEdges([t]);for(const t of r)t.element=this.element;let n=null==(i=this.element.getStartVertex())?void 0:i.position;if(!n)return;let o=ni(c,n),a=[...t.element.elements];for(let i of a){if("element:opening"!==i.type)continue;t.element.removeElement(i),this.element.insertElement(i),i.parameters.position[0]+=o}}if(e)for(let p of t.spaces){if(!p)continue;let{boundary:e,edgeIndex:i}=p.getBoundaryFromEdge(t);if(e){e.edges.splice(i,1);let t=e.vertices.indexOf(s[1]);t>-1?e.vertices.splice(t,1):ve.error(`Cannot find vertex ${s[1].id} in space ${p.id}`)}else ve.error(`Cannot find edge ${t.id} in space ${p.id}.`)}for(let p of t.boundaryWalls){if(!p)continue;let e=p.boundaries[0],i=e.edges.indexOf(t);if(i>-1){e.edges.splice(i,1);let t=e.vertices.indexOf(s[1]);t>-1?e.vertices.splice(t,1):ve.error(`Cannot find vertex ${s[1].id} in boundary wall ${p.id}`)}else ve.error(`Cannot find edge ${t.id} in boundary wall ${p.id}.`)}t.spaces[0]=null,t.spaces[1]=null,t.boundaryWalls[0]=null,t.boundaryWalls[1]=null,n.removeEdge(t),0===d.edges.length&&n.removeVertex(d)}toJSON(){const t=this.vertices[0],e=this.vertices[1];return{...super.toJSON(),vertices:[t.id,e.id]}}}const Fs={usage:"generic",program:"none"};function Ds(t,e){const i=e.parent,s=i.getAxisLength(),{position:r,dimensions:n}=e.parameters,o=r[0]/s,a=(r[0]+n[0])/s;return i.getEdgesAtLinearSegment(o,a).some(e=>e.spaces[0]===t||e.spaces[1]===t)}class Us extends vs{constructor(t,e){super(t,"layout:space"),me(this,ue),ge(this,ue,null),this.boundaries=[],this.slabs=[],this.attributes={...Fs},this.boundaries=e,this.geometry={polygons:[]}}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes)),this.geometry=JSON.parse(JSON.stringify(t.geometry))}setId(t){if(t===this.id)return;let e=this.layout;if((null==e?void 0:e.spacesById[t])||(null==e?void 0:e.elementsById[t])||(null==e?void 0:e.annotationsById[t]))return void ve.error(`ID ${t} already in use in layout ${e.id}.`);if(e&&e.spacesById[this.id]!==this)return void ve.error(`Entry ${this.id} in 'spaces stored by ID' record does not contain space ${this.id}.`);let i=this.spaceGraph;if(null==i?void 0:i.nodesById[t])return void ve.error(`ID ${t} already in use in space graph object.`);if(i&&i.nodesById[this.id]!==this)return void ve.error(`Entry ${this.id} in 'nodes stored by ID' record does not contain space ${this.id}.`);let s=this.id;this.id=t,e&&(delete e.spacesById[s],e.spacesById[this.id]=this),i&&(delete i.nodesById[s],i.nodesById[this.id]=this),this.emit("node-id-change",this,s)}setAttributes(t){this.attributes.usage=t.usage??this.attributes.usage,this.attributes.program=t.program??this.attributes.program,this.emit("space-attributes-change",this)}get isExternal(){return["balcony","terrace","buildingOpening"].includes(this.attributes.usage)}calculateArea(){let t=this.geometry.polygons;if(0===t.length)return ve.error(`Geometry has not been computed for space ${this.id}.`),0;let e=_i(t[0]);for(let i=1;i<t.length;i++){e-=_i(t[i])}return e}getArea(){return null===fe(this,ue)&&ge(this,ue,this.calculateArea()),fe(this,ue)}getAdjacentSpaces(t,{connectivity:e}={}){var i;let s=null==(i=t.nodeMap.get(this))?void 0:i.get("graph:adjacentTo");if(!s)return[];if(void 0===e)return Array.from(s);{let i=0===e?2:2*e;return Array.from(s).filter(s=>{let r=t.findShortestPath("graph:connectedTo",s,this,{depthLimit:i});return!!(null==r?void 0:r.length)&&(0!==e||"element:spaceDivider"===r[1].type)})}}getElements(t){let e=t&&(Array.isArray(t)?t:[t]),i=[],s=this.layout.getElementList();for(let r of s){if(e&&!e.includes(r.type))continue;let t;switch(r.type){case"element:ceiling":case"element:floor":t=r.space===this;break;case"element:boundaryWall":break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":t=r.getEdges().some(t=>t.spaces[0]===this||t.spaces[1]===this);break;case"element:opening":t=Ds(this,r);break;case"element:door":case"element:window":t=Ds(this,r.parent);break;default:{let e,i=r;if(i.parent){let t=i.parent;for(;t.parent;)t=t.parent;e=t.getTransform().position}else e=i.position;t=xi([e[0],e[2]],this.geometry.polygons);break}}t&&i.push(r)}return i}getBoundaryFromVertex(t){for(let e of this.boundaries){let i=e.vertices.indexOf(t);if(i>-1)return{boundary:e,itemIndex:i}}return{boundary:void 0,itemIndex:-1}}getBoundaryFromEdge(t){for(let e of this.boundaries){let i=e.edges.indexOf(t);if(i>-1)return{boundary:e,edgeIndex:i}}return{boundary:void 0,edgeIndex:-1}}calculateBoundingBox(){var t;const e=W([null==(t=this.boundaries[0])?void 0:t.geometryProfile]);let i=0,s=0;for(const r of this.slabs)"element:floor"===r.type&&(i=r.parameters.elevation),"element:ceiling"===r.type&&(s=r.parameters.elevation);return{min:[e.min[0],i,e.min[1]],max:[e.max[0],s,e.max[1]]}}getAxisAlignedBoundingBox(){const{min:t,max:e}=this.getBoundingBox();return{min:t,max:e}}resetBoundingBox(t){super.resetBoundingBox(t),ge(this,ue,null)}resetSpatialIndexing(){super.resetSpatialIndexing();for(const t of this.slabs)t.resetSpatialIndexing()}attachSlab(t){if(null!==t.space)return void ve.warn(`Boundary slab ${t.id} already attached to space ${t.space.id}.`);this.slabs.indexOf(t)>-1?ve.warn(`Boundary slab ${t.id} already referenced by space ${this.id}.`):(t.boundaries=this.boundaries,t.space=this,this.slabs.push(t),this.resetBoundingBox())}detachSlab(t){if(t.space!==this)return void ve.warn(`Boundary slab ${t.id} not attached to space ${this.id}.`);let e=this.slabs.indexOf(t);-1!==e?(t.space=null,t.boundaries=pr(this.boundaries),this.slabs.splice(e,1),this.resetBoundingBox()):ve.warn(`Boundary slab ${t.id} not referenced by space ${this.id}.`)}toJSON(){const{program:t,usage:e}=this.attributes,i={...super.toJSON(),boundaries:[],attributes:{program:t,usage:e}};for(const s of this.boundaries)i.boundaries.push(s.toJSON());return i}}ue=/* @__PURE__ */new WeakMap;class Gs extends Ns{constructor(t,e,i){super(t,e),this.boundaries=pr(i)}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0],i=W([this.boundaries[0].geometryProfile]);return t[0]=i.min[0],e[0]=i.max[0],t[2]=i.min[1],e[2]=i.max[1],"element:floor"===this.type?(t[1]=this.parameters.elevation-this.parameters.height,e[1]=this.parameters.elevation):(t[1]=this.parameters.elevation,e[1]=this.parameters.elevation+this.parameters.height),{min:t,max:e}}}const Xs={top:"#202020",bottom:"#000000",side1:"asm:basic-wall",side2:"asm:basic-wall",join1:"asm:basic-wall",join2:"asm:basic-wall"},Ws={width:.15,height:3,offset:0,elevation:0,materials:{...Xs}};class Ys extends Rs{constructor(t,e){super(t,"element:wall",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(Ws)),this.geometryProfile={valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}}copyForClone(t){super.copyForClone(t),this.geometryProfile=JSON.parse(JSON.stringify(t.geometryProfile))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0],[i,s]=this.getAxisPoints();if(!i||!s)return super.calculateBoundingBox();const r=ni(i,s),{width:n,offset:o}=this.parameters,a=-.5*n+o,l=a+n,h=W([[[0,a],[r,a],[r,l],[0,l]]]);return t[0]=h.min[0],e[0]=h.max[0],t[2]=h.min[1],e[2]=h.max[1],t[1]=this.parameters.elevation,e[1]=this.parameters.elevation+this.parameters.height,{min:t,max:e}}}const Hs={"element:ceiling":{height:.2,elevation:Ws.elevation+Ws.height,materials:{top:"#808080",bottom:"asm:basic-ceiling",sides:"asm:basic-wall"}},"element:floor":{height:.2,elevation:0,materials:{top:"asm:basic-floor",bottom:"#808080",sides:"asm:basic-wall"}}};class $s extends Gs{constructor(t,e,i){super(t,e,i);let s=Hs[this.type];this.parameters=JSON.parse(JSON.stringify(s)),this.space=null}setParameters(t){super.setParameters(t)}getSpaces(){return null===this.space?[]:[this.space]}}function js(t,e){var i;let s,r=t.vertices.map(t=>t.position),n=[];for(let o of t.edges){if("element:wall"!==(null==(i=o.element)?void 0:i.type))continue;let t=o.element.geometryProfile.points;n.push(t)}if(0===n.length)s=[r];else if(e){s=z([r],Y(n))}else s=Y([r,...n]);return s=s.filter(t=>K(t)>1e-7),0===s.length?(ve.warn("No valid polygons, returning boundary polygon."),r):(s=Q(s,.001),s=s.filter(t=>t.length>0),0===s.length?(ve.warn("No valid polygons after filtering, returning boundary polygon."),r):(s.length>1&&(ve.warn(`Result has ${s.length} polygons, returning largest one.`),s=s.sort((t,e)=>K(e)-K(t))),s[0]))}function zs(t,e){var i;let s=[js(e.boundaries[0],!0)];for(let o=1;o<e.boundaries.length;o++){s=z(s,[js(e.boundaries[o],!1)])}let{edges:r}=t.spatialGraph,n=[];for(let o of r){if(o.spaces[0]!==e||o.spaces[1]!==e||"element:wall"!==(null==(i=o.element)?void 0:i.type))continue;let[t,r]=o.getPoints();if(xi(oi(t,r,.5),s)){let t=o.element.geometryProfile.points;n.push(t)}}n.length>0&&(s=z(s,n)),s.sort((t,e)=>{let i=K(t);return K(e)-i}),e.geometry.polygons=s}function Vs(t,e){return new Array(e-t).fill(void 0).map((e,i)=>t+i)}function qs(t){return`${t.type.split(":")[1]}Geometry-${t.id.substring(0,8)}`}function Js(t){let e;switch(t.type){case"curve:rectangle":e=4;break;case"curve:polygon":e=t.points.length;break;case"curve:polygonWithHoles":e=t.polygons.reduce((t,e)=>t+Js({type:"curve:polygon",points:e}),0);break;case"curve:composite":e=t.segments.reduce((t,e)=>t+Js(e),0);break;case"curve:polyline":e=t.points.length-1;break;case"curve:circle":case"curve:arc":case"curve:line":e=1}return e}function Ks(){return De([Math.random(),Math.random(),Math.random()])}function Zs(t,e=!1){let{materials:i,height:s,elevation:r}=t.parameters,n="element:floor"===t.type?-s:0,o=[];for(let d=1;d<t.boundaries.length;d++){let e=t.boundaries[d].geometryProfile.slice();o.push(e)}o=Y(o);let a=t.boundaries[0].geometryProfile.slice(),l=r+n,h={id:`boundarySlabGeometry-${t.id}-boundary`,type:"geometry:extrusion",position:[0,l,0],height:s,profile:{type:"curve:polygonWithHoles",polygons:[a,...o]},geometries:[]},u={top:[0],bottom:[1],sides:Vs(2,2+a.length)},c={top:e?Ks():i.top,bottom:i.bottom,sides:i.sides};h.surfaces=u,h.materials=c,t.geometries=[{type:"reference:geometry",geometry:h}],t.emit("geometry-update",t)}function Qs(t){for(let e=0;e<t.boundaries.length;e++){const i=t.boundaries[e];for(const s of i.edges){const r=s.vertices[0],n=s.vertices[1],o=i.vertices.indexOf(r),a=i.vertices.indexOf(n);let l,h;if(l=0===o?1===a:o===i.vertices.length-1?0===a:a-o===1,h=0===e?l?1:0:l?0:1,null===s.spaces[h])s.spaces[h]=t;else{const t=0===h?"left":"right";ve.error(`Edge ${s.id} already references a space on its ${t} side.`)}}}}function tr(t){for(const e of t.boundaries)for(const i of e.edges)i.spaces[0]||null!==i.boundaryWalls[0]?i.spaces[1]||null!==i.boundaryWalls[1]?ve.error(`Edge ${i.id} referenced by more than two adjacent nodes.`):i.boundaryWalls[1]=t:i.boundaryWalls[0]=t}function er(t,e){let i=t.spatialGraph;for(let s=0;s<e.edges.length;s++){let t=e.edges[s],r=i.edgesById[t.id];r?e.edges[s]=r:i.insertEdge(t)}lr(e)}function ir(t,e){if(0!==e.boundaries.length){for(let i of e.boundaries)er(t,i);switch(e.type){case"element:boundaryWall":tr(e);break;case"element:ceiling":case"element:floor":{let i=function(t,e){for(const i of t.spaces){if(i.boundaries.length!==e.length)continue;let t=0;for(;t<i.boundaries.length;){if(!hr(i.boundaries[t],e[t]))break;t++}if(t===i.boundaries.length)return cr(i,[{boundaries:e}])?i:void 0}return}(t,e.boundaries);i?i.attachSlab(e):ve.warn(`Matching space not found for boundary slab element ${e.id}.`);break}}}else ve.warn(`Boundary slab element ${e.id} does not specify boundaries.`)}function sr(t,e){let i=t.spatialGraph;const s=e.getEdges(),r=new Set(s);let n=!1;for(let o of s){let t=i.edgesById[o.id];t?(n=!0,r.delete(o),r.add(t)):i.insertEdge(o)}n&&e.setEdges(Array.from(r)),function(t){for(const e of t.getEdges())null===e.element?e.element=t:e.element!==t&&ve.error(`Edge ${e.id} referenced by more than one edge element.`)}(e)}function rr(t){var e;switch(t.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":!function(t){switch(t.type){case"element:boundaryWall":for(let e of t.boundaries)for(let i of e.edges)i.boundaryWalls[0]===t&&(i.boundaryWalls[0]=null),i.boundaryWalls[1]===t&&(i.boundaryWalls[1]=null);break;case"element:ceiling":case"element:floor":{let e=t.space;e?e.detachSlab(t):ve.warn(`Boundary slab element ${t.id} not attached to a space.`);break}}}(t);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":!function(t){for(const e of t.getEdges())e.element=null}(t);break;case"element:asset":null==(e=t.product)||e.instances.delete(t)}}function nr(t){const e=[];for(const i of t.boundaries){const t=[];for(const e of i.vertices)t.push(e.position);e.push(t)}return e}function or(t){let e=[];if(0===t.length)return e;if(1===t.length){let i=t[0];return e.push(i.vertices[0]),e.push(i.vertices[1]),e}for(let i=0;i<t.length;i++){let s=t[i],r=t[(i+1)%t.length],n=s.vertices[0],o=s.vertices[1],a=r.vertices[0],l=r.vertices[1];if(n===a||n===l)e.push(o);else{if(o!==a&&o!==l)return void ve.warn(`Could not add edge ${s.id} to current path.`);e.push(n)}}return e}function ar(t){let e=[];for(let i=0;i<t.length-1;i++){let s=t[i],r=t[i+1];for(let t of s.edges)if(r.edges.indexOf(t)>-1){e.push(t);break}}return e}function lr(t){let e=or(t.edges);if(!e)return!1;if(t.vertices=e,t.geometryProfile=t.vertices.map(t=>t.position),!Ei(t.geometryProfile)){let{vertices:e,edges:i,geometryProfile:s}=t;e.reverse(),s.reverse();{i.reverse();let t=e[e.length-1],s=i[0];s.vertices[0]!==t&&s.vertices[1]!==t||(e.pop(),e.unshift(t))}}return!0}function hr(t,e,i){if(t.edges.length!==e.edges.length)return!1;const s=function(t,e){let i=0;for(const s of t.edges)for(const t of e.edges)if(s.id===t.id){i++;break}return i}(t,e);let r;return r=s===t.edges.length,r}function ur(t,e,i){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++){if(!hr(t[s],e[s]))return!1}return!0}function cr(t,e,i=!1){const s=.01;if(!i){const i=t.boundaries.map(t=>t.geometryProfile),r=e.map(t=>t.boundaries.map(t=>t.geometryProfile)),n=Z(i),o=r.map(t=>Z(t)).reduce((t,e)=>t+e,0);if(Math.abs(n-o)>s)return!1}const r=e.map(t=>[t.boundaries[0].geometryProfile]),{polygons:n}=j(r,.01),{polygons:o}=j(n,-.01);if(0===o.length)return ve.warn(`No union polygon, cannot match space ${t.id}.`),!1;if(o.length>1)return ve.warn(` Disjoint union area, cannot match space ${t.id}.`),!1;const a=o[0][0],l=t.boundaries[0].geometryProfile,h=V([[l]],[[a]]).polygons,u=V([[a]],[[l]]).polygons,c=h.length?Z(h[0]):0,d=u.length?Z(u[0]):0;return c<s&&d<s}function dr(t){let e=new hs;return e.vertices=[...t.vertices],e.edges=[...t.edges],e.geometryProfile=JSON.parse(JSON.stringify(t.geometryProfile)),e}function pr(t){let e=[];for(let i of t){let t=dr(i);e.push(t)}return e}function fr(t,e,i){for(let s of t.edges)s.spaces[0]===e?s.spaces[0]=i:s.spaces[1]===e?s.spaces[1]=i:ve.warn(`Edge ${s.id} not in space ${e.id} boundary.`)}function mr(t,e,i,s){let r=function(t,e,i,s){let r=t.vertices,n=Math.min(e,i),o=Math.max(e,i),a=o-n+1,l=r.length-a+2;if(a<3||l<3)return ve.warn("Cannot split boundary, both fragments should have three or more vertices."),[];let h=r.slice(0,n+1),u=r.slice(n,o+1),c=r.slice(o,r.length).concat(h),d=u,p=ar(c).concat(s),f=ar(d).concat(s),m=c.map(t=>t.position),g=d.map(t=>t.position),y=new hs;y.vertices=c,y.edges=p,y.geometryProfile=m;let v=new hs;return v.vertices=d,v.edges=f,v.geometryProfile=g,[y,v]}(t.boundaries[0],e,i,s);if(!r)return void ve.warn(`Could not split outer boundary of space ${t.id}.`);let n=[r[0]],o=[r[1]];for(let f=1;f<t.boundaries.length;f++){let e=t.boundaries[f],i=e.vertices[0].position;if(vi(i,r[0].geometryProfile))n.push(e);else{if(!vi(i,r[1].geometryProfile)){ve.warn("Inner boundary is not contained by either of the two split boundaries.");continue}o.push(e)}}let a,l,h=t.layout;(null==h?void 0:h.debugIds)?(a=h.getSpaceId(),l=h.getSpaceId()):(a=Ut(),l=Ut());let u=new Us(a,n),c=new Us(l,o);for(let f of n)fr(f,t,u);for(let f of o)fr(f,t,c);for(let f of n)u.geometry.polygons.push(f.geometryProfile);for(let f of o)c.geometry.polygons.push(f.geometryProfile);zs(h,u),zs(h,c);let d=[],p=[];for(let f=0;f<t.slabs.length;f++){let e,i,s=t.slabs[f];if(null==h?void 0:h.debugIds){let t="element:ceiling"===s.type?"ceiling":"floor";e=`${t}-${f+1}-in-${a}`,i=`${t}-${f+1}-in-${l}`}else e=Ut(),i=Ut();let r=new $s(e,s.type,n),u=new $s(i,s.type,o);Zs(r,!0),Zs(u,!0),d.push(r),p.push(u)}return{spaces:[u,c],slabs:[d,p]}}function gr(t,e){let{position:i,rotation:s,rotationAxis:r}=t.getTransform(),n=Ti(i,s,r);return e&&ht(n,e,n),n}function yr(t){let e;return t.parent&&(e=yr(t.parent)),gr(t,e)}function vr(t,e){switch(e.type){case"annotation:floorPlanDxf":case"annotation:floorPlanImage":return{name:"annotation",nodes:t.annotations,nodesById:t.annotationsById,nodesByType:t.annotationsByType};case"view:2d":case"view:3d":return{name:"view",nodes:t.views,nodesById:t.viewsById,nodesByType:t.viewsByType}}}class xr{constructor(t){this.vertices=[],this.verticesById={},this.edges=[],this.edgesById={},this.graphChanged=!1,this.debugVertexCount=0,this.debugEdgeCount=0,this.layout=t}emit(t,...e){let i=this.layout.spaceGraph;i&&i.emit(t,...e)}copyForClone(t){this.debugVertexCount=t.debugVertexCount,this.debugEdgeCount=t.debugEdgeCount}deleteVertexAtIndex(t,e){let i=this.vertices[t];if(e){let t=i.edges.slice();for(let s of t){let t=s.vertices[0],r=s.vertices[1];t!==i&&r!==i||this.removeEdge(s,e)}}if(this.vertices.splice(t,1),this.verticesById[i.id]===i)return delete this.verticesById[i.id],i;ve.error(`Entry ${i.id} in 'vertices by ID' record does not contain this object.`)}deleteEdgeAtIndex(t,e){let i=this.edges[t];if(i.element&&this.layout.removeElement(i.element),i.vertices[0].removeEdge(i),i.vertices[1].removeEdge(i),e){if(i.spaces[0]!==i.spaces[1]){if(i.spaces[0]){let t=i.spaces[0].slabs;for(let e of t)this.layout.removeElement(e);this.layout.removeSpace(i.spaces[0])}if(i.spaces[1]){let t=i.spaces[1].slabs;for(let e of t)this.layout.removeElement(e);this.layout.removeSpace(i.spaces[1])}}i.boundaryWalls[0]&&this.layout.removeElement(i.boundaryWalls[0]),i.boundaryWalls[1]&&this.layout.removeElement(i.boundaryWalls[1])}if(this.edges.splice(t,1),this.edgesById[i.id]===i)return delete this.edgesById[i.id],this.graphChanged=!0,i;ve.error(`Entry ${i.id} in 'edges by id' record does not contain this object.`)}insertVertex(t){if(!ws(this.layout,t,this.edgesById,"Edge"))return;t.layout=this.layout,this.vertices.push(t),this.verticesById[t.id]=t;let e=this.layout.spaceGraph;e&&(e.registerNode(t),e.emit("vertex-create",t))}removeVertex(t,e=!1){let i=this.vertices.indexOf(t);if(-1===i)return void ve.warn(`Vertex ${t.id} not found.`);this.deleteVertexAtIndex(i,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(t),s.emit("vertex-delete",t)),t.layout=null,t}removeVertexAtIndex(t,e=!1){let i=this.vertices[t];if(!i)return void ve.warn(`Vertex not found at index ${t}.`);this.deleteVertexAtIndex(t,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(i),s.emit("vertex-delete",i)),i.layout=null,i}removeVertexById(t,e=!1){let i=this.verticesById[t];if(i&&i.id===t)return this.removeVertex(i,e);ve.error(`Entry ${t} in 'vertices by id' record does not contain this object.`)}insertEdge(t,e=!1){if(!ws(this.layout,t,this.edgesById,"Edge"))return;let i=this.verticesById[t.vertices[0].id],s=this.verticesById[t.vertices[1].id];i?t.vertices[0]=i:this.insertVertex(t.vertices[0]),s?t.vertices[1]=s:this.insertVertex(t.vertices[1]),t.layout=this.layout,this.edges.push(t),this.edgesById[t.id]=t,t.vertices[0].addEdge(t),t.vertices[1].addEdge(t);let r=this.layout.spaceGraph;r&&(r.registerNode(t),r.emit("edge-create",t)),e&&function(t){let e=t.layout,i=t.vertices[0],s=t.vertices[1];for(let r of e.spaces){let n=r.boundaries[0],o=n.vertices.indexOf(i),a=n.vertices.indexOf(s);if(o>-1&&a>-1){t.spaces[0]=r,t.spaces[1]=r;let i=mr(r,o,a,t);if(i){let s=r.slabs.slice();for(let t of s)e.removeElement(t);e.removeSpace(r);let[n,o]=i.spaces,[a,l]=i.slabs;e.insertSpace(n);for(let t of a)e.insertElement(t);e.insertSpace(o);for(let t of l)e.insertElement(t);t.emit("space-split",r,[n,o]),n.emit("geometry-profile-update",n),o.emit("geometry-profile-update",o);for(let t of n.slabs)t.emit("geometry-profile-update",t);for(let t of o.slabs)t.emit("geometry-profile-update",t)}else ve.warn(`Failed to split space ${r.id}.`);break}}}(t),this.graphChanged=!0}removeEdge(t,e=!1){let i=this.edges.indexOf(t);if(-1===i)return void ve.warn(`Edge ${t.id} not found.`);this.deleteEdgeAtIndex(i,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(t),s.emit("edge-delete",t)),t.layout=null,t}removeEdgeAtIndex(t,e=!1){let i=this.edges[t];if(!i)return void ve.warn(`Edge not found at index ${t}.`);this.deleteEdgeAtIndex(t,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(i),s.emit("edge-delete",i)),i.layout=null,i}removeEdgeById(t,e=!1){let i=this.edgesById[t];if(i&&i.id===t)return this.removeEdge(i,e);ve.error(`Entry ${t} in 'edges by id' record does not contain this object.`)}getEdgeFromVertices(t,e){let i=t.edges,s=e.edges;for(let r of i)for(let t of s)if(r===t)return r}getVertexId(t){return this.layout.debugIds?(t??"vertex-")+this.debugVertexCount:Ut()}getEdgeId(t){return this.layout.debugIds?(t??"edge-")+this.debugEdgeCount:Ut()}createVertex(t,e,i){let s=new bs(t,e,i);return this.insertVertex(s),s}createEdge(t,e,i,s=!1){let r=new ks(t,e,i);return this.insertEdge(r,s),r}createEdgeByVertexIds(t,e,i,s=!1){let r=this.verticesById[e],n=this.verticesById[i];return this.createEdge(t,r,n,s)}toJSON(){let t=[];for(let i of this.vertices){let e=i.toJSON();t.push(e)}let e=[];for(let i of this.edges){let t=i.toJSON();e.push(t)}return{vertices:t,edges:e}}}const br={height:3,elevation:0,surfaces:{top:[0],bottom:[1],sides:"..."},materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class wr extends Gs{constructor(t,e){super(t,"element:boundaryWall",e),this.parameters=JSON.parse(JSON.stringify(br))}setParameters(t){super.setParameters(t)}}const _r={materials:{}};class Pr extends Rs{constructor(t,e){super(t,"element:curtainWall",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(_r))}setParameters(t){super.setParameters(t)}}const Er={materials:{}};class Tr extends Rs{constructor(t,e){super(t,"element:spaceDivider",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(Er))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const[t,e]=this.getAxisPoints();if(!t||!e)return super.calculateBoundingBox();return{min:[0,0,-.01],max:[ni(t,e),0,.01]}}}class Ar extends Ns{constructor(t,e){super(t,e)}}function Ir(t,e,i=0){let{width:s,offset:r,elevation:n}=t.parameters,[o,a]=t.getAxisPoints();if(!o||!a)return{position:[0,0,0],rotation:0};let l=ui(a,o),h=ri(l),u=oi(o,a,e.parameters.position[0]/h);u=ti(u,hi(li(ai(l)),-.5*s+r-i));let c=e.parameters.position[1]+n;return{position:[u[0],c,u[1]],rotation:180*-ei(ui(a,o))/Math.PI}}function Sr(t,e,i,s){const r=.001;let n=s.parameters.dimensions[0],o=s.parameters.dimensions[1],{width:a,elevation:l}=e.parameters,{position:[h,u,c],rotation:d}=Ir(e,s,r),p=s.parameters.materials,f={id:i,type:"geometry:cuboid",position:[h,u-r-l,c],rotation:d,dimensions:[n,o+r,a+.002],surfaces:{top:[0],bottom:[1],frontBack:[2,4],sides:[3,5]}},m={top:p.top,bottom:p.bottom,frontBack:"#FFFFFF",sides:p.sides};f.materials=m;let g=e.geometries[0].geometry;g.geometries??(g.geometries=[]),g.geometries.push({type:"csg:subtract",geometry:f}),s.emit("geometry-update",s)}function Cr(t,e){let i,s={},r=Vs(0,e);for(let[n,o]of Object.entries(t))if("string"==typeof o)"..."===o?i=n:ve.warn("Invalid surface definition string.");else if(Array.isArray(o)){s[n]=[];for(let t of o){if(t<0||t>=e){ve.warn(`Face index ${t} out of range when defining surface ${n}.`);continue}let i=r.indexOf(t);-1!==i?(s[n].push(t),r.splice(i,1)):ve.warn(`Face index ${t} already assigned when defining surface ${n}.`)}}else ve.warn("Invalid surface definition.");return i&&r.length>0&&(s[i]=r),s}function Mr(t){let e,{surfaces:i,materials:s}=t.parameters;for(let r=0;r<t.boundaries.length;r++){let n=t.boundaries[r],o=t.parameters.elevation,a=or(n.edges);if(!a)return void ve.warn(`Could not create geometry for boundary wall ${t.id}.`);let l=a.map(t=>t.position),h=0===r?"boundary":"hole-"+r,u={id:`boundaryWallGeometry-${t.id}-${h}`,type:"geometry:extrusion",position:[0,o,0],height:t.parameters.height,profile:{type:"curve:polygon",points:l},geometries:[]};u.surfaces=Cr(i,2+l.length),u.materials=JSON.parse(JSON.stringify(s)),0===r?(e=u,t.geometries=[{type:"reference:geometry",geometry:u}]):e.geometries.push({type:"csg:subtract",geometry:u})}t.emit("geometry-update",t)}function Or(t){let{length:e,height:i,frameThickness:s,frameDepth:r,doorAngle:n,hingeSide:o,doorSide:a,doorType:l,materials:h}=t.parameters,u="right"===o,c=[e/2,r/2],d=qs(t),p=.05,f=[],m=(180-Math.min(180,Math.max(0,n)))/180,g=(r-p)/2,y=e-2*s,v=i-s;switch(l){case"singleSwing":u?f.push({position:[s-c[0],0,-c[1]],rotation:n,dimensions:[y,v,p]}):f.push({position:[c[0]-s,0,-c[1]],dimensions:[p,v,y],rotation:270-n});break;case"doubleSwing":y=e/2-s,f.push({position:[s-c[0],0,-c[1]],rotation:n,dimensions:[y,v,p]}),f.push({position:[c[0]-s,0,-c[1]],rotation:270-n,dimensions:[p,v,y]});break;case"slidingDoor":y=(e-2*s)*m;let t=u?s-c[0]:c[0]-y-s;f.push({position:[t,0,-c[1]+g],rotation:0,dimensions:[y,v,p]});break;case"garageDoor":f.push({position:[s-c[0],v*(1-m),-c[1]+g],rotation:0,dimensions:[y,v*m,p]});break;case"elevatorDoor":y=(e-2*s)/2-.005,f.push({position:[s-c[0],0,-c[1]+g],rotation:0,dimensions:[y,v,p]}),f.push({position:[0,0,-c[1]+g],rotation:0,dimensions:[y,v,p]})}let x=[];for(let b=0;b<f.length;b++){let{position:t,rotation:e,dimensions:i}=f[b],s={id:d+"-leaf-"+b,type:"geometry:cuboid",position:t,rotation:e,dimensions:i,material:h.leaf};x.push({type:"reference:geometry",position:[c[0],0,c[1]],rotation:"side2"===a?180:0,geometry:s})}return x}function Nr(t,e,i){let s=qs(t),{stepCount:r,stepHeight:n,angle:o,radius:a,width:l,circulation:h}=i,u=a-l,c=a-l/2,d=Math.PI*o/180*c/r/(u+l/2),p=[0,n,0],f=180/Math.PI*d,m=0;"right"===h&&(f=-f,m=180);let g=function(t,e,i){let{stepThickness:s,stepHeight:r,angle:n,width:o,stepCount:a,radius:l,circulation:h}=i,u=l-o/2,c=l-o,d=Math.PI*n/180*u/a/(c+o/2),p="right"===h,f=r,m=c,g=(p?-1:1)*Math.sin(d)*c,y=r-s,v=Math.cos(d)*c,x=-s,b=c+o,w=(p?-1:1)*Math.sin(d)*(c+o),_=Math.cos(d)*(c+o),P=[0,f,m,0,0,m,g,y,v,g,f,v,0,x,m,0,f,b,0,0,b,w,y,_,w,f,_,0,x,b],E=[0,8,3,0,5,8,0,3,2,0,2,1,1,2,4,0,6,5,0,1,6,5,7,8,5,6,7,6,9,7,2,7,4,4,7,9,8,7,3,7,2,3];if(p)for(let T=0;T<E.length;T+=3){let t=E[T+1];E[T+1]=E[T+2],E[T+2]=t}return{id:t,type:"geometry:mesh",vertices:P,indices:E,rotation:0,surfaces:{top:[0,1],base:[2,3,4,5,6,7,8,9,10,11,12,13]},materials:{top:e.tread,base:e.steps}}}(s,e,i);return{type:"reference:geometry",position:{type:"vector3:range",range:{start:[0,0,0],step:p,count:r}},rotation:{type:"number:range",range:{start:m,step:f,count:r}},geometry:g}}function Lr(t){let{width:e,height:i,materials:s}=t.parameters;const r=Math.max(1,Math.round(i/.17)),n={height:i,width:e,stepCount:r,stepHeight:i/r,stepThickness:.1};let o;if("straight"===t.parameters.stairFlightType){let{length:e}=t.parameters;o=function(t,e,i){let{stepCount:s,width:r,stepHeight:n,length:o,stepThickness:a}=i,l=o/s,h=[l,n,0],u=function(t,e,i){let{riser:s,tread:r,width:n,thickness:o}=i;return{id:t,type:"geometry:extrusion",rotation:90,rotationAxis:[1,0,0],height:n,profile:{type:"curve:polygon",points:[[0,0],[0,o],[r,o-s],[r,-s],[0,-s]]},surfaces:{top:[5],base:[0,1,2,3,4,6]},materials:{top:e.tread,base:e.steps}}}(qs(t),e,{tread:l,riser:n,width:r,thickness:a});return{type:"reference:geometry",position:{type:"vector3:range",range:{start:[0,0,0],step:h,count:s}},geometry:u}}(t,s,{...n,length:e})}else{let{radius:e,angle:i,circulation:r}=t.parameters;o=Nr(t,s,{...n,radius:e,angle:i,circulation:r})}t.geometries=[o],t.emit("geometry-update",t)}function Rr(t,e=!1){let{sidePoints1:i,sidePoints2:s,joinPoints1:r,joinPoints2:n,points:o}=t.geometryProfile;if(0===o.length)return;let a="wallGeometry-"+t.id,l={id:a,type:"geometry:extrusion",position:[0,t.parameters.elevation,0],height:t.parameters.height,profile:{type:"curve:composite",segments:[{type:"curve:polyline",points:i},{type:"curve:polyline",points:r},{type:"curve:polyline",points:s},{type:"curve:polyline",points:n}]}},h=t.parameters.materials,u={top:[0],bottom:[1],side1:[2],side2:[4]},c={top:e?Ks():h.top??Xs.top,bottom:h.bottom??Xs.bottom,side1:h.side1??Xs.side1,side2:h.side2??Xs.side2},[d,p]=function(t){let e=[!1,!1],i=[t.getStartVertex(),t.getEndVertex()];for(let s=0;s<i.length;s++){let t=i[s];t&&(t.edges.filter(t=>{var e;return"element:wall"===(null==(e=t.element)?void 0:e.type)}).map(t=>t.element).length>0?e[s]=!0:ve.error(`Vertex ${t.id} not referencing edge that references it.`))}return e}(t);d&&(u.join1=[3],c.join1=h.join1??Xs.join1),p&&(u.join2=[5],c.join2=h.join2??Xs.join2),l.surfaces=u,l.materials=c,t.geometries=[{type:"reference:geometry",geometry:l}];for(let f=0;f<t.elements.length;f++){let e=t.elements[f];if("element:opening"!==e.type)continue;let i=a+"-opening-"+(f+1);Sr(t.layout,t,i,e)}t.emit("geometry-update",t)}function Br(t){switch(t.type){case"element:asset":case"element:beam":case"element:curtainWall":case"element:opening":case"element:ramp":case"element:roof":case"element:spaceDivider":case"element:stairs":break;case"element:casework":!function(t){let{length:e,width:i,height:s,counterHeight:r,materials:n}=t.parameters,o=Math.min(.6,e),a=Math.floor(e/o),l=e%o,h=i-.02,u=s-r,c=.02,d=qs(t),p=[],f=t.elements;for(let y of f)if("product"in y&&y.product){let{min:t,max:e}=y.product.getBoundingBox();if(0===pi(t,e))continue;let i=di(t,[0,.01,0]),s=di(e,i),r=ci(i,y.position);p.push({id:d+"-subtraction-"+y.id.substring(0,8),type:"geometry:cuboid",position:[...r],dimensions:s})}let m=[];r>0&&m.push({id:d+"-counter",type:"geometry:cuboid",position:[0,u,0],dimensions:[e,r,i],material:n.counter}),m.push({id:d+"-doors",type:"geometry:cuboid",position:{type:"vector3:range",range:{start:[c,c,h],step:[o,0,0],count:a}},dimensions:[o-.04,u-.04,c],material:n.cabinetDoors}),l>.04&&m.push({id:d+"-doors+2",type:"geometry:cuboid",position:[a*o+c,c,h],dimensions:[l-.04,u-.04,c],material:n.cabinet});let g={id:d+"-cabinet",type:"geometry:cuboid",position:[0,0,0],dimensions:[e,u,h],geometries:[...m.map(t=>({type:"reference:geometry",geometry:t})),...p.map(t=>({type:"csg:subtract",geometry:t}))],material:n.cabinet};t.geometries=[{type:"reference:geometry",geometry:g}],t.emit("geometry-update",t)}(t);break;case"element:column":!function(t){let{profile:e,height:i,materials:s}=t.parameters,r=qs(t),n=[0,0,0];"curve:rectangle"===e.type&&(n=[-e.dimensions[0]/2,0,-e.dimensions[1]/2]);let o={id:r,type:"geometry:extrusion",position:n,profile:e,height:i},a=Js(e);o.surfaces={top:[0],bottom:[1],sides:Vs(2,2+a)},o.materials={top:s.top,bottom:s.bottom,sides:s.sides},t.geometries=[{type:"reference:geometry",geometry:o}],t.emit("geometry-update",t)}(t);break;case"element:ceiling":case"element:floor":Zs(t);break;case"element:boundaryWall":Mr(t);break;case"element:door":!function(t){let{height:e,length:i,frameThickness:s,frameDepth:r,materials:n}=t.parameters,o=qs(t),a={id:o+"-frame-top",type:"geometry:cuboid",position:[0,e-s,0],rotation:0,dimensions:[i,s,r],material:n.frame},l={id:o+"-frame-side",type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,0,0],[i-s,0,0]]},rotation:0,dimensions:[s,e-s,r],material:n.frame};t.geometries=[{type:"reference:geometry",geometry:a},{type:"reference:geometry",geometry:l},...Or(t)],t.emit("geometry-update",t)}(t);break;case"element:generic":!function(t){let{profile:e,height:i,materials:s}=t.parameters;if("none"===e)return;let r=Js(e),n={id:qs(t),type:"geometry:extrusion",position:[0,0,0],profile:e,height:i,surfaces:{top:[0],bottom:[1],sides:Vs(2,2+r)},materials:{top:s.top,bottom:s.bottom,sides:s.sides}};t.geometries=[{type:"reference:geometry",geometry:n}],t.emit("geometry-update",t)}(t);break;case"element:railing":!function(t){let e,{height:i,length:s,width:r,segmentCount:n,segmentLength:o,materials:a}=t.parameters,l=.01;e=o&&o>0?Math.max(Math.round(s/o),1):n&&n>0?n:Math.max(Math.round(s/.12),1);let h=(s-l)/e,u=qs(t),c={id:u+"-horizontal",type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,i-l,-r/2],[0,0,-r/2]]},rotation:0,dimensions:[s,l,r],material:a.surface},d={id:u+"-vertical",type:"geometry:cuboid",position:{type:"vector3:range",range:{start:[0,l,-r/2],step:[h,0,0],count:e+1}},rotation:0,dimensions:[l,i-.02,r],material:a.surface};t.geometries=[{type:"reference:geometry",geometry:c},{type:"reference:geometry",geometry:d}],t.emit("geometry-update",t)}(t);break;case"element:slab":!function(t){let{profile:e,height:i,materials:s}=t.parameters,r={id:qs(t),type:"geometry:extrusion",position:[0,0,0],profile:e,height:i},n=Js(e);r.surfaces={top:[0],bottom:[1],sides:Vs(2,2+n)},r.materials={top:s.top,bottom:s.bottom,sides:s.sides},t.geometries=[{type:"reference:geometry",geometry:r}],t.emit("geometry-update",t)}(t);break;case"element:stairFlight":Lr(t);break;case"element:wall":Rr(t);break;case"element:window":!function(t){let{panelCount:e,panelLength:i,height:s,length:r,frameThickness:n,frameDepth:o,materials:a}=t.parameters,l=qs(t),h={id:l,type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,s-n,0],[0,0,0]]},rotation:0,dimensions:[r,n,o],material:a.frame},u=[[0,n,0]],c=r-n;if(e&&(i=c/e),i&&i>n){let t=i;for(;t<c;)u.push([t,n,0]),t+=i}u.push([r-n,n,0]);let d={id:l+"-vertical",type:"geometry:cuboid",position:{type:"vector3:list",list:u},rotation:0,dimensions:[n,s-2*n,o],material:a.frame},p={id:l+"-glass",type:"geometry:extrusion",position:[n,n,o/2],rotation:0,height:s-2*n,profile:{type:"curve:rectangle",dimensions:[r-2*n,.01]},material:a.panel};t.geometries=[{type:"reference:geometry",geometry:h},{type:"reference:geometry",geometry:d},{type:"reference:geometry",geometry:p}],t.emit("geometry-update",t)}(t)}for(let e of t.elements)Br(e)}function kr(t){for(let e of t.elements)Br(e)}const Fr={position:[0,0],dimensions:[1,2],materials:{top:"#FFFFFF",bottom:"#FFFFFF",sides:"#FFFFFF"}};class Dr extends Ar{constructor(t){super(t,"element:opening"),this.parameters=JSON.parse(JSON.stringify(Fr))}getTransform(){var t;if("element:wall"!==(null==(t=this.parent)?void 0:t.type)){const t=this.parent?`Parent of element ${this.id} is not a wall.`:`Element ${this.id} does not have a parent.`;return ve.error(t),{position:[0,0,0],rotation:0,rotationAxis:[0,1,0]}}let{position:e,rotation:i}=Ir(this.parent,this);return{position:e,rotation:i,rotationAxis:[0,1,0]}}get position(){return this.getTransform().position}get rotation(){return this.getTransform().rotation}setParameters(t){let e=!!t.position,i=!!t.dimensions;if(super.setParameters(t),this.emit("element-parameters-change",this),e||i){let t=this.parent;if(t&&Br(t),i)for(let e of this.elements)Br(e);this.resetSpatialIndexing()}}getBoundingBox(t=!1){const{dimensions:e}=this.parameters,i=this.parent,s=(null==i?void 0:i.parameters.width)||0;return{min:[0,0,0],max:[e[0],e[1],s],transform:t?this.getTransform():this.getWorldTransform()}}getSpaces(){if(this.parent){return this.parent.getSpaces().filter(t=>Ds(t,this))}return ve.error(`Element ${this.id} does not have a parent.`),[]}get isExternal(){const t=this.parent;if(!t)return super.isExternal;const[e]=t.getAxisPoints();if(!e)return super.isExternal;const i=t.getAxisLength(),{position:s,dimensions:r}=this.parameters,n=s[0]/i,o=(s[0]+r[0])/i,a=t.getEdgesAtLinearSegment(n,o);if(1===a.length)return a[0].isExternal;let l=0,h=0;for(const u of a){const[t,s]=u.getPoints().map(t=>ni(e,t)/i).sort((t,e)=>t-e),r=(o>s?s:o)-(n>t?n:t);u.isExternal?l+=r:h+=r}return l>=h}}class Ur extends Ns{constructor(t,e){super(t,e),this.position=[0,0,0],this.rotation=0,this.rotationAxis=[0,1,0]}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation,this.rotationAxis=[...t.rotationAxis]}setPosition(t){this.position=[...t],this.resetTransform(!0),this.emit("element-transform-change",this)}setRotation(t,e){this.rotation=t,e&&(this.rotationAxis=[...e]),this.resetTransform(!0),this.emit("element-transform-change",this)}setTransform(t,e,i){this.position=[...t],this.rotation=e,i&&(this.rotationAxis=[...i]),this.resetTransform(!0),this.emit("element-transform-change",this)}getSpaces(){if(this.parent)return this.parent.getSpaces();let t=[this.position[0],this.position[2]];for(let e of this.layout.spaces)if(xi(t,e.geometry.polygons))return[e];return[]}calculateTransform(){return{position:[...this.position],rotation:this.rotation,rotationAxis:[...this.rotationAxis]}}calculateWorldTransform(){if(!this.parent)return this.getTransform();let t=yr(this),{position:e,rotation:i,rotationAxis:s}=Ai(t);return 0===s[0]&&s[1]<0&&0===s[2]&&(s=[0,1,0],i=-i),{position:e,rotation:i,rotationAxis:s}}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0];if("length"in this.parameters&&(e[0]=this.parameters.length),"height"in this.parameters&&(e[1]=this.parameters.height),"width"in this.parameters?e[2]=this.parameters.width:"frameDepth"in this.parameters&&(e[2]=this.parameters.frameDepth),"radius"in this.parameters&&(t[0]=t[2]=-this.parameters.radius,e[0]=e[2]=this.parameters.radius),"profile"in this.parameters&&"none"!==this.parameters.profile)switch(this.parameters.profile.type){case"curve:rectangle":{let[i,s]=this.parameters.profile.dimensions;e[0]=i,e[2]=s,"element:column"===this.type&&(t[0]=-i/2,e[0]=i/2,t[2]=-s/2,e[2]=s/2);break}case"curve:circle":t[0]=t[2]=-this.parameters.profile.radius,e[0]=e[2]=this.parameters.profile.radius;break;case"curve:polygon":let i=W([this.parameters.profile.points]);t[0]=i.min[0],e[0]=i.max[0],t[2]=i.min[1],e[2]=i.max[1]}return{min:t,max:e}}setParameters(t){super.setParameters(t),Br(this)}}const Gr={materials:{}};class Xr extends Ur{constructor(t){super(t,"element:asset"),this.product=null,this.parameters=JSON.parse(JSON.stringify(Gr))}get isComponentInstance(){var t;return"product:component"===(null==(t=this.product)?void 0:t.type)}get isComponentInstanceChild(){var t;return"element:asset"===(null==(t=this.parent)?void 0:t.type)&&this.parent.isComponentInstance}setParameters(t){super.setParameters(t)}setProduct(t){this.product=t,this.product.instances.add(this),this.resetBoundingBox(),this.emit("node-property-change",this,"product"),this.emit("geometry-update",this)}calculateBoundingBox(){if(!this.product)return super.calculateBoundingBox();const{min:t,max:e}=this.product.getBoundingBox();return{min:t,max:e}}}const Wr={length:2,width:.1,height:.2,materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class Yr extends Ur{constructor(t){super(t,"element:beam"),this.parameters=JSON.parse(JSON.stringify(Wr))}setParameters(t){super.setParameters(t)}}const Hr={length:2,height:.7,width:.6,counterHeight:.03,materials:{cabinet:"asm:cabinet_paint_white",cabinetDoors:"asm:cabinet_paint_white",counter:"asm:cabinet_paint_white"}};class $r extends Ur{constructor(t){super(t,"element:casework"),this.parameters=JSON.parse(JSON.stringify(Hr))}setParameters(t){super.setParameters(t)}}const jr={type:"curve:circle",radius:.1},zr={"curve:circle":{...jr},"curve:rectangle":{type:"curve:rectangle",dimensions:[.1,.1]},"curve:polygon":{type:"curve:polygon",points:[[0,0],[.1,0],[.1,.1],[0,.1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[.1,0],[.1,.1],[0,.1]],[[.02,.02],[.02,.08],[.08,.08],[.08,.02]]]}},Vr={profile:{...jr},height:3,materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class qr extends Ur{constructor(t){super(t,"element:column"),this.parameters=JSON.parse(JSON.stringify(Vr))}setParameters(t){var e;(null==(e=t.profile)?void 0:e.type)&&t.profile.type!==this.parameters.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(zr[t.profile.type]))),super.setParameters(t)}}const Jr={length:1,height:2,frameThickness:.05,frameDepth:.1,doorType:"singleSwing",doorAngle:90,hardware:!0,hingeSide:"right",doorSide:"side1",materials:{frame:"asm:doorLeaf-flush-white",leaf:"asm:doorLeaf-flush-white"}};class Kr extends Ur{constructor(t){super(t,"element:door"),this.parameters=JSON.parse(JSON.stringify(Jr))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const t=super.calculateBoundingBox(),{doorType:e,frameThickness:i,frameDepth:s,doorSide:r,length:n}=this.parameters;if("singleSwing"===e||"doubleSwing"===e){const o="singleSwing"===e?n-2*i:n/2-i;"side1"===r?t.min[2]=-o:t.max[2]=s+o}return t}}const Zr={"curve:circle":{type:"curve:circle",radius:.5},"curve:rectangle":{type:"curve:rectangle",dimensions:[1,1]},"curve:polygon":{type:"curve:polygon",points:[[0,0],[1,0],[1,1],[0,1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[1,0],[1,1],[0,1]],[[.25,.25],[.25,.75],[.75,.75],[.75,.25]]]}},Qr={profile:"none",height:0,materials:{top:"#F0F0F0",bottom:"#F0F0F0",sides:"#F0F0F0"}};class tn extends Ur{constructor(t){super(t,"element:generic"),this.parameters=JSON.parse(JSON.stringify(Qr))}setParameters(t){t.profile&&"none"!==t.profile&&t.profile.type&&"none"!==this.parameters.profile&&this.parameters.profile.type!==t.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(Zr[t.profile.type]))),super.setParameters(t)}}const en="product:static",sn={manufacturer:"",categories:[],subCategories:[],thumbnail:"",boundingBox:{min:[0,0,0],max:[0,0,0]},seatCapacity:0,updatedAt:""};class rn extends gs{constructor(t,e){super(t,e),this.instances=/* @__PURE__ */new Set,this.attributes=JSON.parse(JSON.stringify(sn))}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes))}setAttributes(t){var e,i;let s=this.attributes;s.manufacturer=t.manufacturer??s.manufacturer,s.categories=(null==(e=t.categories)?void 0:e.slice())??s.categories,s.subCategories=(null==(i=t.subCategories)?void 0:i.slice())??s.subCategories,s.thumbnail=t.thumbnail??s.thumbnail,t.boundingBox&&(s.boundingBox.min=[...t.boundingBox.min],s.boundingBox.max=[...t.boundingBox.max]),s.seatCapacity=t.seatCapacity??s.seatCapacity,s.updatedAt=t.updatedAt??s.updatedAt}getBoundingBox(){return this.attributes.boundingBox}toJSON(){const t=super.toJSON(),e={},i=this.attributes;""!==i.manufacturer&&(e.manufacturer=i.manufacturer),i.categories.length>0&&(e.categories=[...i.categories]),i.subCategories.length>0&&(e.subCategories=[...i.subCategories]),""!==i.thumbnail&&(e.thumbnail=i.thumbnail);let{min:s,max:r}=i.boundingBox;return 0===s[0]&&0===pi(r,s)||(e.boundingBox={min:[...i.boundingBox.min],max:[...i.boundingBox.max]}),i.seatCapacity>0&&(e.seatCapacity=i.seatCapacity),""!==i.updatedAt&&(e.updatedAt=i.updatedAt),t.attributes=e,t}}class nn extends rn{constructor(t){super(t,en),this.geometries=[]}copyForClone(t){super.copyForClone(t),this.geometries=JSON.parse(JSON.stringify(t.geometries))}toJSON(){return{...super.toJSON(),type:en,geometries:JSON.parse(JSON.stringify(this.geometries))}}}const on="product:component";class an extends rn{constructor(t){super(t,on),this.products=[],this.geometries=[],this.attributes=JSON.parse(JSON.stringify(sn))}copyForClone(t){super.copyForClone(t),this.products=JSON.parse(JSON.stringify(t.products))}toJSON(){return{...super.toJSON(),type:on,products:JSON.parse(JSON.stringify(this.products)),geometries:[]}}setProducts(t){this.products=JSON.parse(JSON.stringify(t))}setInstances(){var t;for(const e of this.instances){if(this.products.length===e.elements.length&&this.products.every((t,i)=>{var s;const r=e.elements[i];return"element:asset"===(null==r?void 0:r.type)&&t.product===(null==(s=r.product)?void 0:s.id)}))for(let i=0;i<this.products.length;i++){const s=this.products[i];if("type"in s.position)continue;if("number"!=typeof s.rotation)continue;const r=e.elements[i];"element:asset"===r.type&&(null==(t=r.product)?void 0:t.id)===s.product&&r.setTransform(s.position,s.rotation)}else{for(let t=e.elements.length-1;t>=0;t--)e.removeElement(e.elements[t]);for(const t of this.products){const i=new Xr(Ut()),s=this.spaceGraph.productsById[t.product];s||ve.error(`Product ${t.product} is missing`),i.setProduct(s),"type"in t.position||"number"==typeof t.rotation&&(i.setTransform(t.position,t.rotation),e.insertElement(i))}}}}}function ln(t){for(let e=t.elements.length-1;e>=0;e--)t.removeElement(t.elements[e])}function hn(t,e,i){let s=t.elements.filter(t=>t.type===e);for(let r=s.length-1;r>=i;r--)t.removeElement(s[r]);for(let r=0;r<i;r++)if(!s[r]){let i=Ut();s[r]="element:casework"===e?new $r(i):new Xr(i),t.insertElement(s[r])}return s}function un(t){let{length:e,width:i,height:s,wallCabinet:r,leftHighCabinetCount:n,rightHighCabinetCount:o,sinkElementSlot:a,materials:l}=t.parameters,h=Math.min(.6,e),u=s-1.5,c=Math.min(e,h*Math.max(n,0)),d=e>c?h*o:0,p=Math.max(e-c-d,0);d=Math.max(e-c-p,0);let f=0;p>0&&(f++,r&&f++),c>0&&f++,d>0&&f++;let m=p>0&&a*h>=c&&a*h<=c+p,g=hn(t,"element:casework",f),y={cabinet:l.cabinet,cabinetDoors:l.cabinetDoors,counter:l.counter};if(p>0){let e=g.shift();if(e){let s=hn(e,"element:asset",m?1:0);if(m){let e=s[0],r=function(t){const e="7f24bd1c-1ebc-4724-8cd4-ca78c7d4a1e5";if(null==t?void 0:t.productsById[e])return null==t?void 0:t.productsById[e];let i=new nn(e);return i.setName("Kitchen Sink"),i.setAttributes({categories:["appliances"],subCategories:["kitchen"],boundingBox:{max:[.54,.21,0],min:[0,-.17,-.47]}}),i.geometries=[{type:"reference:geometry",geometry:{id:"sinkGeometry",type:"geometry:uri",format:"data3d",uri:"015f8f8e-e588-4f51-a342-2930559834ee/201208-0355-60hukz/bf4e4a56-ed95-4b58-a214-4b1a0a84ae0e.gz.data3d.buffer"}}],i}(t.spaceGraph),{min:n,max:o}=r.getBoundingBox(),l=ci(n,(v=di(o,n),x=.5,[v[0]*x,v[1]*x,v[2]*x]));l[1]=0;let u=ci([a*h-c,.9,0],[h/2,0,i/2]);r&&(e.setProduct(r),e.setPosition(di(u,l)))}e.setParameters({length:p,width:i,height:.9,counterHeight:.03,materials:{...y}}),e.setTransform([c,0,0],0)}let s=r&&g.shift();s&&(ln(s),s.setParameters({length:p,width:.45,height:u,counterHeight:0,materials:{...y}}),s.setTransform([c,1.5,0],0))}var v,x;let b=c>0&&g.shift();b&&(ln(b),b.setParameters({length:c,width:i,height:s,counterHeight:0,materials:{...y}}),b.setTransform([0,0,0],0));let w=d>0&&g.shift();w&&(ln(w),w.setParameters({length:d,width:i,height:s,counterHeight:0,materials:{...y}}),w.setTransform([c+p,0,0],0))}const cn={length:3,width:.6,height:2.2,wallCabinet:!0,leftHighCabinetCount:1,rightHighCabinetCount:0,sinkElementSlot:-1,cooktopElementSlot:-1,ovenElementSlot:-1,materials:{cabinet:"asm:cabinet_paint_white",cabinetDoors:"asm:cabinet_paint_white",counter:"asm:cabinet_paint_white"}};class dn extends Ur{constructor(t){super(t,"element:kitchen"),this.parameters=JSON.parse(JSON.stringify(cn))}setParameters(t,e=!1){super.setParameters(t),e||un(this),this.emit("element-parameters-change",this)}}const pn={length:2,width:.05,height:1,segmentCount:0,segmentLength:.12,materials:{surface:"#CCCCCC"}};class fn extends Ur{constructor(t){super(t,"element:railing"),this.parameters=JSON.parse(JSON.stringify(pn))}setParameters(t){super.setParameters(t)}}const mn={length:2,width:1,height:.5,materials:{top:"asm:basic-floor",bottom:"asm:basic-wall",sides:"asm:basic-wall"}};class gn extends Ur{constructor(t){super(t,"element:ramp"),this.parameters=JSON.parse(JSON.stringify(mn))}}const yn={materials:{}};class vn extends Ur{constructor(t){super(t,"element:roof"),this.parameters=JSON.parse(JSON.stringify(yn))}}const xn={type:"curve:rectangle",dimensions:[1,1]},bn={"curve:circle":{type:"curve:circle",radius:1},"curve:rectangle":{...xn},"curve:polygon":{type:"curve:polygon",points:[[0,0],[1,0],[1,1],[0,1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[1,0],[1,1],[0,1]],[[.25,.25],[.25,.75],[.75,.75],[.75,.25]]]}},wn={profile:{...xn},height:.1,materials:{top:"asm:basic-floor",bottom:"asm:basic-floor",sides:"asm:basic-wall"}};class _n extends Ur{constructor(t){super(t,"element:slab"),this.parameters=JSON.parse(JSON.stringify(wn))}setParameters(t){var e;(null==(e=t.profile)?void 0:e.type)&&t.profile.type!==this.parameters.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(bn[t.profile.type]))),super.setParameters(t)}}const Pn={height:3,width:1.2,materials:{steps:"asm:basic-wall",tread:"asm:basic-floor"}},En={straight:{stairFlightType:"straight",length:3,...Pn},spiral:{stairFlightType:"spiral",angle:270,radius:1.5,circulation:"right",...Pn}};class Tn extends Ur{constructor(t){super(t,"element:stairFlight"),this.parameters=JSON.parse(JSON.stringify(En.straight))}setParameters(t){if(t.stairFlightType&&this.parameters.stairFlightType!==t.stairFlightType){let{height:e,materials:i,width:s}=this.parameters;this.parameters={...JSON.parse(JSON.stringify(En[t.stairFlightType])),height:e,materials:i,width:s}}super.setParameters(t)}}function An(t,e,i){let s=t.elements.filter(t=>t.type===e);for(let r=s.length-1;r>=i;r--)t.removeElement(s[r]);for(let r=0;r<i;r++)if(!s[r]){let i=Ut();s[r]="element:stairFlight"===e?new Tn(i):new _n(i),t.insertElement(s[r])}return s}const In=.1;const Sn={height:3,railing:"right",materials:{steps:"asm:basic-wall",tread:"asm:basic-floor",railing:"#CCCCCC"}},Cn={straight:{stairsType:"straight",length:4,width:1.2,...Sn},straightLanding:{stairsType:"straightLanding",length:4,width:1.2,...Sn},halfLanding:{stairsType:"halfLanding",length:4,width:2.5,stepWidth:1.2,circulation:"right",...Sn},quarterLanding:{stairsType:"quarterLanding",length:4,width:2.5,stepWidth:1.2,circulation:"right",...Sn},twoQuarterLanding:{stairsType:"twoQuarterLanding",length:3,width:4,stepWidth:1.2,circulation:"right",...Sn},winder:{stairsType:"winder",length:4,width:2.5,stepWidth:1.2,circulation:"right",...Sn},doubleWinder:{stairsType:"doubleWinder",length:4,width:2.5,stepWidth:1.2,circulation:"right",...Sn},spiral:{stairsType:"spiral",radius:1.5,angle:270,stepWidth:1.2,circulation:"right",...Sn},custom:{stairsType:"custom",stepWidth:1.2,...Sn}},Mn=Cn.straight;class On extends Ur{constructor(t){super(t,"element:stairs"),this.parameters=JSON.parse(JSON.stringify(Mn))}setParameters(t,e=!1){if(t.stairsType&&this.parameters.stairsType!==t.stairsType){let{height:e,railing:i,materials:s}=this.parameters;this.parameters={...JSON.parse(JSON.stringify(Cn[t.stairsType])),height:e,railing:i,materials:s}}super.setParameters(t),e||function(t){switch(t.parameters.stairsType){case"straight":{let{length:e,width:i,height:s,materials:r}=t.parameters,[n]=An(t,"element:stairFlight",1);An(t,"element:slab",0),n.setParameters({stairFlightType:"straight",length:e,width:i,height:s,materials:{steps:r.steps,tread:r.tread}}),n.setTransform([0,0,0],0);break}case"straightLanding":{let{length:e,width:i,height:s,materials:r}=t.parameters,n=(e-i)/2,[o,a]=An(t,"element:stairFlight",2),[l]=An(t,"element:slab",1);o.setParameters({stairFlightType:"straight",length:n,width:i,height:s/2,materials:{steps:r.steps,tread:r.tread}}),o.setTransform([0,0,0],0),l.setParameters({profile:{type:"curve:rectangle",dimensions:[i,i]},height:In,materials:{top:r.tread,bottom:r.steps,sides:r.steps}}),l.setTransform([n,s/2-In,0],0),a.setParameters({stairFlightType:"straight",length:n,width:i,height:s/2}),a.setTransform([e-n,s/2,0],0);break}case"halfLanding":{let{length:e,width:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,[l,h]=An(t,"element:stairFlight",2),[u]=An(t,"element:slab",1);l.setParameters({stairFlightType:"straight",length:e-r,width:r,height:s/2,materials:{steps:o.steps,tread:o.tread}}),l.setTransform([0,0,a?0:-r],0),u.setParameters({profile:{type:"curve:rectangle",dimensions:[r,i]},height:In,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),u.setPosition([e-r,s/2-In,a?0:-i]),h.setParameters({stairFlightType:"straight",length:e-r,width:r,height:s/2,materials:{steps:o.steps,tread:o.tread}}),h.setTransform([e-r,s/2,a?i:-i+r],-180);break}case"quarterLanding":{let{length:e,width:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,l=e-r,h=i-r,u=l/(l+h)*s,c=h/(l+h)*s,[d,p]=An(t,"element:stairFlight",2),[f]=An(t,"element:slab",1);d.setParameters({stairFlightType:"straight",length:l,width:r,height:u,materials:{steps:o.steps,tread:o.tread}}),d.setTransform([0,0,a?0:-r],0),f.setParameters({profile:{type:"curve:rectangle",dimensions:[r,r]},height:In,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),f.setPosition([e-r,u-In,a?0:-r]),p.setParameters({stairFlightType:"straight",length:h,width:r,height:c,materials:{steps:o.steps,tread:o.tread}}),a?p.setTransform([e,u,r],-90):p.setTransform([e-r,u,-r],90);break}case"twoQuarterLanding":{let{length:e,width:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,l=e-r,h=i-2*r,u=l/(2*l+h)*s,c=h/(2*l+h)*s,[d,p,f]=An(t,"element:stairFlight",3),[m,g]=An(t,"element:slab",2);d.setParameters({stairFlightType:"straight",length:l,width:r,height:u,materials:{steps:o.steps,tread:o.tread}}),d.setTransform([0,0,a?0:-r],0),m.setParameters({profile:{type:"curve:rectangle",dimensions:[r,r]},height:In,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),m.setPosition([e-r,u-In,a?0:-r]),p.setParameters({stairFlightType:"straight",length:h,width:r,height:c,materials:{steps:o.steps,tread:o.tread}}),a?p.setTransform([e,u,r],-90):p.setTransform([e-r,u,-r],90),g.setParameters({profile:{type:"curve:rectangle",dimensions:[r,r]},height:In,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),g.setPosition([e-r,u+c-In,a?i-r:-i]),f.setParameters({stairFlightType:"straight",length:l,width:r,height:u,materials:{steps:o.steps,tread:o.tread}}),f.setTransform([e-r,u+c,a?i:-i+r],-180);break}case"spiral":{let{radius:e,angle:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,[l]=An(t,"element:stairFlight",1);An(t,"element:slab",0),l.setParameters({stairFlightType:"spiral",radius:e,angle:i,height:s,width:r,circulation:n,materials:{steps:o.steps,tread:o.tread}}),l.setTransform([0,0,a?e:-e],0);break}}}(this),this.emit("element-parameters-change",this)}calculateBoundingBox(){const t=super.calculateBoundingBox();return"radius"in this.parameters&&(t.min[2]=0,t.max[2]=2*this.parameters.radius,t.min[0]=-this.parameters.radius,t.max[0]=this.parameters.radius),"circulation"in this.parameters&&"left"===this.parameters.circulation&&(t.min[2]=-t.max[2],t.max[2]=0),t}}const Nn={length:1,height:1.2,frameThickness:.05,frameDepth:.1,panelLength:0,panelCount:1,materials:{frame:"#CCCCCC",panel:"asm:glass"}};class Ln extends Ur{constructor(t){super(t,"element:window"),this.parameters=JSON.parse(JSON.stringify(Nn))}setParameters(t){super.setParameters(t)}}class Rn extends ys{constructor(){super(...arguments),this.position=[0,0,0],this.rotation=0}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation,this.parameters=JSON.parse(JSON.stringify(t.parameters))}setTransform(t,e){this.position=[...t],this.rotation=e,this.emit("annotation-transform-change",this)}setParameters(t){Is(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.emit("annotation-parameters-change",this)}toJSON(){return{...super.toJSON(),position:[...this.position],parameters:JSON.parse(JSON.stringify(this.parameters)),rotation:this.rotation}}}const Bn={uri:"",drawingOrigin:[0,0],drawingUnits:"unitLess",hiddenLayers:[]};class kn extends Rn{constructor(t){super(t,"annotation:floorPlanDxf"),this.parameters=JSON.parse(JSON.stringify(Bn))}setParameters(t){super.setParameters(t)}}class Fn extends ys{copyForClone(t){super.copyForClone(t),this.parameters=JSON.parse(JSON.stringify(t.parameters))}setParameters(t){Is(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.emit("view-parameters-change",this)}toJSON(){return{...super.toJSON(),parameters:JSON.parse(JSON.stringify(this.parameters))}}}const Dn={style:{background:{fill:"#f7f8fa"},units:"metric",byId:{},byType:{},byAttribute:{program:{},usage:{}}},hidden:[]};class Un extends Fn{constructor(t){super(t,"view:2d"),this.parameters=JSON.parse(JSON.stringify(Dn))}setParameters(t){var e,i;let{style:s}=t;void 0===(null==s?void 0:s.byId)&&(this.parameters.style.byId={}),void 0===(null==s?void 0:s.byType)&&(this.parameters.style.byType={}),void 0===(null==(e=null==s?void 0:s.byAttribute)?void 0:e.program)&&(this.parameters.style.byAttribute.program={}),void 0===(null==(i=null==s?void 0:s.byAttribute)?void 0:i.usage)&&(this.parameters.style.byAttribute.usage={}),Is(this.parameters,t,{onNewKeys:{allow:!1},copyScopes:[".style.byId",".style.byType",".style.byAttribute.program",".style.byAttribute.usage"],cloneObjects:!0}),this.emit("view-parameters-change",this)}}const Gn={position:[0,0,0],normal:[0,0,1],fov:"default",scale:1,lensShiftX:0,lensShiftY:0,projection:"perspective"};class Xn extends Fn{constructor(t){super(t,"view:3d"),this.parameters=JSON.parse(JSON.stringify(Gn))}setParameters(t){super.setParameters(t)}}function Wn(t){var e;return null==(e=null==t?void 0:t.type)?void 0:e.startsWith("element")}function Yn(t){return"layout:space"===(null==t?void 0:t.type)}function Hn(t){return"product:component"===(null==t?void 0:t.type)||"product:static"===(null==t?void 0:t.type)}const $n="relation:group";class jn extends be{constructor(t){super(t,$n),this.elements=/* @__PURE__ */new Set}insertElements(t){for(let e of t)this.elements.add(e)}removeElements(t){for(let e of t)this.elements.delete(e)}copyForClone(t){super.copyForClone(t)}toJSON(){const t=super.toJSON();return t.elements=Array.from(this.elements).map(t=>t.id),t}}class zn extends gs{constructor(t,e){super(t,e)}}function Vn(t,e){e.registerNode(t),function(t,e){let{vertices:i,edges:s}=t.spatialGraph;for(let r of i)e.registerNode(r),e.emit("vertex-create",r);for(let r of s)e.registerNode(r),e.emit("edge-create",r)}(t,e);for(let s of t.spaces)e.registerNode(s);let i=t.getElementList();for(let s of i)e.registerNode(s);for(let s of t.annotations)e.registerNode(s);for(let s of t.views)e.registerNode(s);e.emit("spatial-structure-create",t)}function qn(t,e){e.unregisterNode(t),function(t,e){let{vertices:i,edges:s}=t.spatialGraph;for(let r of i)e.unregisterNode(r),e.emit("vertex-delete",r);for(let r of s)e.unregisterNode(r),e.emit("edge-delete",r)}(t,e);for(let s of t.spaces)e.unregisterNode(s);let i=t.getElementList();for(let s of i)e.unregisterNode(s);for(let s of t.annotations)e.unregisterNode(s);e.emit("spatial-structure-delete",t)}function Jn(t,e){e.registerNode(t);for(let i of t.layouts)Vn(i,e);e.emit("spatial-structure-create",t)}function Kn(t,e){e.unregisterNode(t);for(let i of t.layouts)qn(i,e);e.emit("spatial-structure-delete",t)}function Zn(t,e,...i){let s;switch(t){case"element:ceiling":case"element:floor":s=new $s(e,t,i[0]);break;case"element:boundaryWall":s=new wr(e,i[0]);break;case"element:curtainWall":s=new Pr(e,i[0]);break;case"element:spaceDivider":s=new Tr(e,i[0]);break;case"element:wall":s=new Ys(e,i[0]);break;case"element:opening":s=new Dr(e);break;case"element:asset":s=new Xr(e);break;case"element:beam":s=new Yr(e);break;case"element:casework":s=new $r(e);break;case"element:column":s=new qr(e);break;case"element:door":s=new Kr(e);break;case"element:generic":s=new tn(e);break;case"element:kitchen":s=new dn(e);break;case"element:ramp":s=new gn(e);break;case"element:roof":s=new vn(e);break;case"element:railing":s=new fn(e);break;case"element:slab":s=new _n(e);break;case"element:stairs":s=new On(e);break;case"element:stairFlight":s=new Tn(e);break;case"element:window":s=new Ln(e)}return s}const Qn={uri:"",length:1,width:1};class to extends Rn{constructor(t){super(t,"annotation:floorPlanImage"),this.parameters=JSON.parse(JSON.stringify(Qn))}setParameters(t){super.setParameters(t)}}function eo(t,e){let i;switch(t){case"annotation:floorPlanDxf":i=new kn(e);break;case"annotation:floorPlanImage":i=new to(e)}return i}function io(t,e){let i;switch(t){case"view:2d":i=new Un(e);break;case"view:3d":i=new Xn(e)}return i}class so{constructor(){this.nodeMap=/* @__PURE__ */new Map}addNode(t){return this.nodeMap.has(t)||this.nodeMap.set(t,/* @__PURE__ */new Map),this.nodeMap.get(t)}addEdge(t,e,i){var s,r;let n=this.addNode(e),o=this.addNode(i);n.has(t)||n.set(t,/* @__PURE__ */new Set),o.has(t)||o.set(t,/* @__PURE__ */new Set),null==(s=n.get(t))||s.add(i),null==(r=o.get(t))||r.add(e)}removeNode(t){if(this.nodeMap.has(t)){for(let e of this.nodeMap.get(t))for(let i of e[1])this.removeEdge(e[0],t,i);this.nodeMap.delete(t)}}removeEdge(t,e,i){var s,r,n,o;null==(r=null==(s=this.nodeMap.get(e))?void 0:s.get(t))||r.delete(i),null==(o=null==(n=this.nodeMap.get(i))?void 0:n.get(t))||o.delete(e)}findShortestPath(t,e,i,s={}){var r;let n=[[e]],o=/* @__PURE__ */new Set;for(;n.length>0;){let e=n.shift();if(!e)return null;if(s.depthLimit&&e.length-1>s.depthLimit)return null;let a=e[e.length-1];if(a===i)return e;if(!o.has(a)&&this.nodeMap.has(a)&&(null==(r=this.nodeMap.get(a))?void 0:r.has(t))){o.add(a);for(let i of this.nodeMap.get(a).get(t))n.push([...e,i])}}return null}toJSON(){const t=[],e=[];for(const[i,s]of this.nodeMap.entries()){t.push({id:i.id,type:i.type});for(const[t,r]of s.entries())for(const s of r)i.id<s.id&&e.push({type:String(t),nodes:[i.id,s.id]})}return{nodes:t,edges:e}}}const ro=t=>{const e={};for(const i in t)e[i]=[];return e},no={"element:ceiling":$s,"element:floor":$s,"element:boundaryWall":wr,"element:curtainWall":Pr,"element:spaceDivider":Tr,"element:wall":Ys,"element:opening":Dr,"element:asset":Xr,"element:beam":Yr,"element:casework":$r,"element:column":qr,"element:door":Kr,"element:generic":tn,"element:kitchen":dn,"element:railing":fn,"element:ramp":gn,"element:roof":vn,"element:slab":_n,"element:stairs":On,"element:stairFlight":Tn,"element:window":Ln},oo={"annotation:floorPlanDxf":kn,"annotation:floorPlanImage":to},ao={"view:2d":Un,"view:3d":Xn};const lo=t=>{const{min:e,max:i}=t.getAxisAlignedBoundingBox();return{id:t.id,type:t.type,minX:e[0],minY:e[2],maxX:i[0],maxY:i[2]}};class ho extends Ht{constructor(t){super(),this.nodeIds=/* @__PURE__ */new Set,this.layout=t}find({min:t,max:e,margin:i,types:s}){i??(i=0),e??(e=t);const r={minX:t[0]-i,maxX:e[0]+i,minY:t[1]-i,maxY:e[1]+i},n=this.search(r),o=[];for(const a of n)(null==s?void 0:s.length)&&!(null==s?void 0:s.includes(a.type))||(this.layout.spaceGraph.nodesById[a.id]?o.push(this.layout.spaceGraph.nodesById[a.id]):ve.warn(`Indexed node ${a.id} is not part of the layout anymore`));return o}addNode(t){const e=lo(t);this.nodeIds.has(t.id)&&this.remove(e),this.insert(e),this.nodeIds.add(t.id)}removeNode(t){const e=lo(t);this.nodeIds.has(t.id)&&this.remove(e)}remove(t){return this.nodeIds.delete(t.id),super.remove(t,(t,e)=>t.id===e.id),this}}const uo={...no,"spatialGraph:edge":ks,"spatialGraph:vertex":bs,"layout:space":Us,"view:2d":Un,"view:3d":Xn,"annotation:floorPlanDxf":kn,"annotation:floorPlanImage":to};class co extends be{constructor(t,e){super(t,e),this.position=[0,0,0],this.rotation=0,this.rotationAxis=[0,1,0],this.surfaces={},this.materials={},this.boundingBox={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}}class po extends co{constructor(t,e){super(t,e),this.normals="generator",this.uvs="generator",this.geometries=[]}}const fo={"geometry:plane":class extends po{constructor(t){super(t,"geometry:plane"),this.normal=[0,1,0],this.size=1,this.doubleSided=!1}},"geometry:cuboid":class extends po{constructor(t){super(t,"geometry:cuboid"),this.dimensions=[1,1,1]}},"geometry:sphere":class extends po{constructor(t){super(t,"geometry:sphere"),this.radius=1}},"geometry:extrusion":class extends po{constructor(t,e){super(t,"geometry:extrusion"),this.height=1,this.profile=e}},"geometry:mesh":class extends co{constructor(t){super(t,"geometry:mesh"),this.vertices=[],this.indices=[],this.normals=[],this.uvs=[]}},"geometry:uri":class extends co{constructor(t){super(t,"geometry:uri"),this.format="data3d",this.uri="",this.normals="smooth"}}},mo={"material:embedded":Ae,"material:basic":Se,"material:color":_e,"material:standard":Ee},go={"product:static":nn,"product:component":an},yo={"relation:group":jn},vo={...uo,...fo,...mo,...go,...yo,"spatialStructure:building":null,"spatialStructure:floor":null,"spatialStructure:layout":null};function xo(t,e){t.name=e.name??t.name,t.customId=e.customId??t.customId}function bo(t,e){let i;return t.type===on?(i=new an(t.id),i.products=JSON.parse(JSON.stringify(t.products))):(i=new nn(t.id),i.geometries=JSON.parse(JSON.stringify(t.geometries))),t.attributes&&i.setAttributes(t.attributes),t.customAttributes&&i.setCustomAttributes(t.customAttributes,e),xo(i,t),i}function wo(t){return JSON.parse(JSON.stringify(t))}function _o(t){let e;if(Array.isArray(t)||"string"==typeof t)ve.warn("Color literal or standard material reference not allowed in shared resources section.");else if("object"==typeof t)switch(t.type){case we:let[i,s,r,n]=function(t){let[e,i,s,r]=[1,1,1,1];return Array.isArray(t)?[e,i,s,r]=Be(t):"string"==typeof t&&([e,i,s,r]=[1,1,1,1],""===t?ve.warn("Empty string not a valid color literal."):t.startsWith("#")?[e,i,s,r]=ke(t):t.startsWith("rgb(")?[e,i,s,r]=Fe(t,!1):t.startsWith("rgba(")?[e,i,s,r]=Fe(t,!0):ve.warn(`String ${t} not a valid color literal.`)),[e,i,s,r]}(t.value);e=new _e(t.id,[i,s,r],n);break;case Pe:e=new Ee(t.id,t.reference);break;case Ie:e=new Se(t.id),xo(e,t),e.colorDiffuse=[...t.colorDiffuse],t.colorSpecular&&(e.colorSpecular=[...t.colorSpecular]),e.specularCoefficient=t.specularCoefficient??e.specularCoefficient,e.opacity=t.opacity??e.opacity;break;default:e=new _e(t.id,[1,1,1],1),ve.warn(`Unknown material type ${t.type}, creating default material.`)}else ve.warn("Material not an array, string or object.");return e}function Po(t,e){let i;if(e.type===$n){i=new jn(e.id);let s=[];for(let r of e.elements)t.nodesById[r]?s.push(t.nodesById[r]):ve.error(`Element ${r} not found, referenced by relation ${i.id}.`);i.insertElements(s)}return xo(i,e),i}function Eo(t){const e=function(t){const{id:e,attributes:{resourceType:i}}=t;return e.endsWith(`:${i}`)?e:`${e}:${i}`}(t),i=new fs(e,t.attributes);return xo(i,t),i}function To(t,e){!function(t,e){for(let i of e){let e=Eo(i);e&&t.insertCustomAttribute(e)}}(t,e.customAttributes||[]),function(t,e){for(let i of e){let e=bo(i,t.customAttributesById);t.insertProduct(e)}}(t,e.products),function(t,e){for(let i of e){let e=wo(i);t.insertGeometry(e)}}(t,e.geometries),function(t,e){for(let i of e){let e=_o(i);e&&t.insertMaterial(e)}}(t,e.materials)}function Ao(t,e){let i=function(t,e){let i;switch(e.type){case Vo:i=qo.fromJSON(e,{spaceGraph:t,skipInsert:!0});break;case jo:i=zo.fromJSON(e,{spaceGraph:t,skipInsert:!0});break;case Ho:i=$o.fromJSON(e,{spaceGraph:t,skipInsert:!0})}return i}(t,e);t.insertSpatialStructure(i)}function Io(t,e){To(t,e.sharedResources),Ao(t,e.spatialStructure),function(t,e){for(let i of e){let e=Po(t,i);e&&t.insertRelation(e)}}(t,e.sharedResources.relations||[])}class So{constructor(t){this.products=[],this.productsById={},this.productsByType=ro(go),this.customAttributes=[],this.customAttributesById={},this.customAttributesByType=ro(ms),this.geometries=[],this.geometriesById={},this.geometriesByType=ro(fo),this.materials=[],this.materialsById={},this.materialsByType=ro(mo),this.relations=[],this.relationsById={},this.relationsByType=ro(yo),this.nodes=[],this.nodesById={},this.nodesByType=ro(vo),this.spatialStructure=null,this.emitter=new ce.TinyEmitter,this.sourceSchemaVersion=t}getEvents(){return this.emitter.e??{}}copyEvents(t){let e=t.getEvents();for(let[i,s]of Object.entries(e))this.emitter.on(i,s)}deleteNodeAtIndex(t,e,i,s){let r=e[t];if(e.splice(t,1),i[r.id]!==r)return void ve.error(`Entry ${r.id} in 'nodes stored by ID' record does not contain this object.`);delete i[r.id];let n=s[r.type];if(!n)return void ve.error(`Node ${r.id} not found in 'nodes stored by type' record.`);let o=n.indexOf(r);if(-1!==o)return n.splice(o,1),r;ve.error(`Node ${r.id} not found in 'nodes stored by type' record.`)}insertNode(t,e,i,s){i[t.id]?ve.error(`Node ${t.id} already registered.`):(e.push(t),i[t.id]=t,s[t.type]||(s[t.type]=[]),s[t.type].push(t))}removeNode(t,e,i,s){let r=e.indexOf(t);if(-1!==r)return this.deleteNodeAtIndex(r,e,i,s),t;ve.warn(`Node ${t.id} not found.`)}registerNode(t){var e,i;t.spaceGraph=this;let{nodes:s,nodesById:r,nodesByType:n}=this;this.insertNode(t,s,r,n),"getBoundingBox"in t&&"layout"in t&&(null==(e=t.layout)?void 0:e.spatialIndex)&&(null==(i=t.layout)||i.spatialIndex.addNode(t))}unregisterNode(t){var e,i;t.spaceGraph=null;let{nodes:s,nodesById:r,nodesByType:n}=this;this.removeNode(t,s,r,n),"getBoundingBox"in t&&"layout"in t&&(null==(e=t.layout)?void 0:e.spatialIndex)&&(null==(i=t.layout)||i.spatialIndex.removeNode(t))}insertSpatialStructure(t){if(this.spatialStructure)ve.warn(`Space graph object already has spatial structure ${this.spatialStructure.id} attached.`);else if(t.spaceGraph)ve.warn(`Spatial structure ${t.id} already part of a space graph object.`);else{switch(t.spaceGraph=this,this.spatialStructure=t,t.type){case"spatialStructure:building":!function(t,e){e.registerNode(t);for(let i of t.floors)Jn(i,e);e.emit("spatial-structure-create",t)}(t,this);break;case"spatialStructure:floor":Jn(t,this);break;case"spatialStructure:layout":Vn(t,this)}this.emit("spatial-structure-create",t)}}removeSpatialStructure(){let t=this.spatialStructure;if(t){switch(t.spaceGraph=null,this.spatialStructure=null,t.type){case"spatialStructure:building":!function(t,e){e.unregisterNode(t);for(let i of t.floors)Kn(i,e);e.emit("spatial-structure-delete",t)}(t,this);break;case"spatialStructure:floor":Kn(t,this);break;case"spatialStructure:layout":qn(t,this)}return this.emit("spatial-structure-delete",t),t}ve.warn("No spatial structure attached to space graph object.")}insertProduct(t){t.spaceGraph?ve.warn(`Product ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.products,this.productsById,this.productsByType),this.registerNode(t),this.emit("product-create",t))}removeProduct(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.products,this.productsById,this.productsByType),this.unregisterNode(t),this.emit("product-delete",t)):ve.warn(`Product ${t.id} already in a detached state.`)}createProduct(t,e){let i;return i=e===on?new an(t):new nn(t),this.insertProduct(i),i}insertGeometry(t){let{geometries:e,geometriesById:i,geometriesByType:s}=this;e.push(t),i[t.id]=t,s[t.type].push(t)}removeGeometry(t){let{geometries:e,geometriesById:i,geometriesByType:s}=this,r=e.indexOf(t);if(-1===r)return void ve.warn(`Geometry ${t.id} not found.`);if(e.splice(r,1),i[t.id]!==t)return void ve.error(`Entry ${t.id} in 'geometries stored by ID' record does not contain this object.`);delete this.geometriesById[t.id];let n=s[t.type];if(!n)return void ve.error(`Geometry ${t.id} not found in 'geometries stored by type' record.`);let o=n.indexOf(t);-1!==o?n.splice(o,1):ve.error(`Node ${t.id} not found in 'nodes stored by type' record.`)}insertMaterial(t){t.spaceGraph?ve.warn(`Material ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.materials,this.materialsById,this.materialsByType),this.registerNode(t),this.emit("material-create",t))}removeMaterial(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.materials,this.materialsById,this.materialsByType),this.unregisterNode(t),this.emit("material-delete",t)):ve.warn(`Material ${t.id} already in a detached state.`)}createMaterial(t,e,...i){let s;switch(t){case we:s=new _e(e,i[0],i[1]);break;case Pe:s=new Ee(e,i[0]);break;case Te:s=new Ae(e,i[0],i[1]);break;case Ie:s=new Se(e)}return this.insertMaterial(s),s}insertRelation(t){t.spaceGraph?ve.warn(`Relation ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.relations,this.relationsById,this.relationsByType),this.registerNode(t),this.emit("relation-create",t))}removeRelation(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.relations,this.relationsById,this.relationsByType),this.unregisterNode(t),this.emit("relation-delete",t)):ve.warn(`Relation ${t.id} already in a detached state.`)}createRelation(t,e){let i;if(t===$n)i=new jn(e);return this.insertRelation(i),i}insertCustomAttribute(t){t.spaceGraph?ve.warn(`Custom attribute ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.customAttributes,this.customAttributesById,this.customAttributesByType),this.registerNode(t),this.emit("custom-attribute-create",t))}removeCustomAttribute(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.customAttributes,this.customAttributesById,this.customAttributesByType),this.unregisterNode(t),this.emit("custom-attribute-delete",t)):ve.warn(`Custom attribute ${t.id} already in a detached state.`)}getId(){return Ut()}emit(t,...e){this.emitter.emit(t,...e)}on(t,e,i){this.emitter.on(t,e,i)}once(t,e,i){this.emitter.once(t,e,i)}off(t,e){this.emitter.off(t,e)}toJSON(){let t=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.products),e=function(t){let e=[];for(let i of t){let t=y(i);e.push(t)}return e}(this.geometries),i=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.materials),s=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.relations),r=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.customAttributes);return{schemaVersion:"0.24.6",spatialStructure:this.spatialStructure.toJSON(),sharedResources:{products:t,geometries:e,materials:i,relations:s,customAttributes:r}}}static fromJSON(t){const e=new So(t.schemaVersion);return Io(e,t),e}}function Co(t,e){let i=t.spatialGraph,s=new hs;for(let r of e.edges){let t=i.edgesById[r];if(!t)return void ve.warn(`Edge ${r} not found, skipping boundary.`);s.edges.push(t)}if(lr(s))return s}function Mo(t,e){let i=[];for(let s of e){let e=Co(t,s);if(!e)return;i.push(e)}return i}function Oo(t,e){let{id:i,position:s}=e,r=new bs(i,s[0],s[1]);return Ss(r,e),r}function No(t,e){let i=t.spatialGraph,s=e.vertices[0],r=e.vertices[1];if(s===r)return void ve.warn(`Same vertex referenced twice, skipping edge ${e.id}.`);let n=i.verticesById[s],o=i.verticesById[r];if(!n||!o)return void ve.warn(`One or both vertices not found, skipping edge ${e.id}.`);let a=new ks(e.id,n,o);return Ss(a,e),a}function Lo(t,e,i){i??(i=t.spaceGraph.customAttributesById);let s=Mo(t,e.boundaries);if(!s)return void ve.warn(`Invalid boundaries, skipping space ${e.id}.`);let r=new Us(e.id,s);return Ss(r,e),Cs(r,e,i),e.attributes&&r.setAttributes(e.attributes),r}function Ro(t,e){let i=eo(e.type,e.id);return Ss(i,e),i.setTransform(e.position,e.rotation??0),e.parameters&&i.setParameters(e.parameters),i}function Bo(t,e){let i=io(e.type,e.id);return Ss(i,e),e.parameters&&i.setParameters(e.parameters),i}const ko={};function Fo(t,e,i){return ko[t]||(ko[t]={}),ko[t][e]=i,i}const Do={.15:t=>{if(("layout:space"===t.type||"element:floor"===t.type||"element:ceiling"===t.type)&&t.id.includes(":")){const e=JSON.parse(JSON.stringify(t));return e.id=Ut(),e}return t},.16:t=>{if("element:window"===t.type&&t.parameters&&"framePosition"in t.parameters){const e=JSON.parse(JSON.stringify(t));return delete e.parameters.framePosition,e}return t},"0.20.3":t=>{if("layout:space"===t.type||!t.parameters)return t;let e=!1;const i=JSON.parse(JSON.stringify(t.parameters));if("height"in i&&i.height<.01&&(i.height=.01,e=!0),"width"in i&&i.width<.01&&(i.width=.01,e=!0),"length"in i&&i.length<.01&&(i.length=.01,e=!0),e){const e=JSON.parse(JSON.stringify(t));return e.parameters=i,e}return t}};function Uo(t,e){return!e||function(t,e){var i;if(void 0!==(null==(i=ko[t])?void 0:i[e]))return ko[t][e];const s=t.split(".").map(t=>parseInt(t)),r=e.split(".").map(t=>parseInt(t));for(let n=0;n<Math.max(s.length,r.length);n++){const i=s[n]||0,o=r[n]||0;if(i>o)return Fo(t,e,1);if(i<o)return Fo(t,e,-1)}return Fo(t,e,0)}(e,t)<0}function Go(t,e){let i=t;for(const s in Do)Uo(s,e)&&(i=Do[s](i));return i}function Xo(t,e){var i;let{position:s,rotation:r,rotationAxis:n}=e;if(t.setTransform(s??[0,0,0],r??0,n),e.parameters){let s=!!(null==(i=e.elements)?void 0:i.length);!function(t,e,i=!1){switch(t.type){case"element:ceiling":case"element:floor":case"element:boundaryWall":case"element:curtainWall":case"element:spaceDivider":case"element:wall":case"element:opening":case"element:asset":case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:ramp":case"element:roof":case"element:railing":case"element:slab":case"element:stairFlight":case"element:window":t.setParameters(e);break;case"element:kitchen":case"element:stairs":t.setParameters(e,i)}}(t,e.parameters,s)}"element:generic"!==e.type&&"element:asset"!==e.type||(t.geometries=e.geometries?JSON.parse(JSON.stringify(e.geometries)):[])}function Wo(t,e,i){i??(i=t.spaceGraph);let s,r=Go(e,null==i?void 0:i.sourceSchemaVersion);switch(r.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":s=function(t,e){let i=Mo(t,e.boundaries);if(!i)return void ve.warn(`Invalid boundaries, skipping boundary wall ${e.id}.`);let s=Zn(e.type,e.id,i);return e.parameters&&s.setParameters(e.parameters),s}(t,r);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":s=function(t,e){let i=[];if(i=Array.isArray(e.edge)?e.edge:[e.edge],!i.length)return void ve.warn(`Element ${e.id} references no edges and is skipped.`);let s=[];for(let n of i){let i=t.spatialGraph.edgesById[n];if(!i)return void ve.warn(`Edge ${e.edge} not found, skipping edge element ${e.id}.`);s.push(i)}let r=Zn(e.type,e.id,s);return e.parameters&&r.setParameters(e.parameters),r}(t,r);break;case"element:opening":s=function(t,e){let i=Zn("element:opening",e.id);return e.parameters&&i.setParameters(e.parameters),i}(0,r);break;case"element:asset":s=function(t,e,i){let s=Zn(e.type,e.id);if(Xo(s,e),!e.product)return e.geometries||ve.warn(`Element ${s.id} does not specify a 'geometries' field and does not reference a product.`),s;let r=t.spaceGraph??i;if(r){let t=r.nodesById[e.product];if(!t)return void ve.warn(`Product ${e.product} not found, skipping element ${e.id}.`);s.setProduct(t)}else ve.warn(`Layout not attached and space graph not passed as an argument, cannot find product ${e.product}.`);return s}(t,r,i);break;case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:kitchen":case"element:railing":case"element:ramp":case"element:roof":case"element:slab":case"element:stairFlight":case"element:stairs":case"element:window":s=function(t,e){let i=Zn(e.type,e.id);return Xo(i,e),i}(0,r);break;default:return void ve.warn(`Unknown element type '${r.type}', skipping element.`)}if(!s)return;Ss(s,r),Cs(s,r,null==i?void 0:i.customAttributesById);let n=r.elements??[];for(let o of n){let e=Wo(t,o,i);e&&s.insertElement(e)}return s}function Yo(t,e,i){Cs(t,e,i.customAttributesById),Ss(t,e),function(t,e){let i=t.spatialGraph,s=e.spatialGraph;for(let r of s.vertices){let t=Oo(0,r);i.insertVertex(t)}for(let r of s.edges){let e=No(t,r);e&&i.insertEdge(e)}}(t,e),function(t,e,i){for(let s of e.spaces){let e=Lo(t,Go(s),i.customAttributesById);e&&t.insertSpace(e)}}(t,e,i),function(t,e,i){for(let s of e.elements){let e=Wo(t,s,i);e&&t.insertElement(e)}}(t,e,i),function(t,e){let i=e.annotations??[];for(let s of i){let e=Ro(0,s);t.insertAnnotation(e)}}(t,e),function(t,e){let i=e.views??[];for(let s of i){let e=Bo(0,s);t.insertView(e)}}(t,e),function(t){const e=t.spatialGraph.edges;for(const s of e)s.spaces=[null,null],s.boundaryWalls=[null,null];const i=[];for(const s of t.spaces)Qs(s),i.push(nr(s));for(const s of e){if(null!==s.spaces[0]||null!==s.spaces[1])continue;const[e,r]=s.getPoints(),n=oi(e,r,.5);for(let o=0;o<t.spaces.length;o++)if(xi(n,i[o])){s.spaces[0]=t.spaces[o],s.spaces[1]=t.spaces[o];break}}for(const s of t.elements)"element:boundaryWall"===s.type&&tr(s)}(t)}const Ho="spatialStructure:layout";class $o extends zn{constructor(t){super(t,Ho),this.parent=null,this.spaces=[],this.spacesById={},this.elements=[],this.elementsById={},this.elementsByType=ro(no),this.annotations=[],this.annotationsById={},this.annotationsByType=ro(oo),this.views=[],this.viewsById={},this.viewsByType=ro(ao),this.debugIds=!1,this.suggestedIds={},this.spatialGraph=new xr(this),this.spatialIndex=new ho(this)}copyForClone(t){super.copyForClone(t),this.debugIds=t.debugIds,this.suggestedIds={...t.suggestedIds}}insertSpace(t){ws(this,t,this.spacesById,"Space")&&(!function(t,e){for(let i of t.elements)"element:ceiling"!==i.type&&"element:floor"!==i.type||ur(e.boundaries,i.boundaries)&&e.attachSlab(i)}(this,t),t.layout=this,this.spaces.push(t),this.spacesById[t.id]=t,t.boundaries.length&&(this.spatialGraph.graphChanged=!0),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("space-create",t)))}removeSpace(t){let e=this.spaces.indexOf(t);if(-1!==e){if(function(t){let e=t.slabs.slice();for(let i of e)t.detachSlab(i);for(let i of t.boundaries)for(let e of i.edges)e.spaces[0]===t&&(e.spaces[0]=null),e.spaces[1]===t&&(e.spaces[1]=null)}(t),this.spaces.splice(e,1),this.spacesById[t.id]===t)return delete this.spacesById[t.id],this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("space-delete",t)),t.layout=null,t;ve.error(`Entry ${t.id} in 'spaces stored by ID' record does not contain this object.`)}else ve.warn(`Space ${t.id} not found.`)}createSpace(t,e){let i=new Us(t,e);return this.insertSpace(i),i}insertElement(t){ws(this,t,this.elementsById,"Element",!0)&&(!function(t,e){switch(e.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":ir(t,e);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":sr(t,e)}}(this,t),this.elements.push(t),_s(this,t))}removeElement(t){if(t.layout!==this)return void ve.warn(`Element ${t.id} not part of layout ${this.id}.`);if(t.parent)return void ve.warn(`Element ${t.id} not a root element, cannot remove from layout.`);rr(t);let e=this.elements.indexOf(t);if(-1!==e)return this.elements.splice(e,1),Ps(this,t,null),t;ve.warn(`Element ${t.id} not found.`)}createElement(t,e,...i){let s=Zn(t,e,...i);return this.insertElement(s),s}insertNode(t){let{nodes:e,nodesById:i,nodesByType:s}=vr(this,t);t.layout=this,e.push(t),i[t.id]=t,s[t.type]||(s[t.type]=[]),s[t.type].push(t)}removeNode(t){let{name:e,nodes:i,nodesById:s,nodesByType:r}=vr(this,t),n=i.indexOf(t);if(-1===n)return void ve.warn(`Node ${t.id} not found in '${e}' list.`);if(i.splice(n,1),s[t.id]!==t)return void ve.error(`Entry ${t.id} in '${e} stored by ID' record does not contain this object.`);delete s[t.id];let o=r[t.type],a=null==o?void 0:o.indexOf(t);o&&-1!==a?r[t.type].splice(a,1):ve.error(`Node ${t.id} not found in '${e} stored by type' record.`)}insertAnnotation(t){ws(this,t,this.annotationsById,"Annotation")&&(this.insertNode(t),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("annotation-create",t)))}removeAnnotation(t){return this.removeNode(t),this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("annotation-delete",t)),t.layout=null,t}createAnnotation(t,e){let i=eo(t,e);return this.insertAnnotation(i),i}insertView(t){ws(this,t,this.viewsById,"View")&&(this.insertNode(t),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("view-create",t)))}removeView(t){return this.removeNode(t),this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("view-delete",t)),t.layout=null,t}createView(t,e){let i=io(t,e);return this.insertView(i),i}clearSpaces(){let t=[...this.spaces];for(let e of t)this.removeSpace(e)}getElementList(){return Object.values(this.elementsById)}getArea(t={program:{exclude:["void"]}}){var e,i;let s=(null==(e=null==t?void 0:t.program)?void 0:e.include)??[],r=(null==(i=null==t?void 0:t.program)?void 0:i.exclude)??[];if(s.length&&r.length)return ve.warn("Cannot use 'include' and 'exclude' filters at the same time, skipping area calculation."),0;let n=0;for(let o of this.spaces){let t=!1;s.length&&(t=s.includes(o.attributes.program)),r.length&&(t=r.includes(o.attributes.program)),t||(n+=o.getArea())}return n}getLayoutGraph(){var t;let e=new so,i=this.elementsByType["element:spaceDivider"].slice();for(let s of this.elementsByType["element:opening"])"element:window"!==(null==(t=s.elements[0])?void 0:t.type)&&i.push(s);for(let s of i)for(let t of s.getSpaces())t&&e.addEdge("graph:connectedTo",t,s);for(let s of this.spatialGraph.edges)s.spaces[0]&&s.spaces[1]&&e.addEdge("graph:adjacentTo",s.spaces[0],s.spaces[1]);return e}getUniqueId(t,e){let i=0,s=t+i++;for(;this.suggestedIds[s]||e[s];)s=t+i++;return this.suggestedIds[s]=!0,s}getSpaceId(t){let e;return t=t??"space-",e=this.debugIds?this.getUniqueId(t,this.spacesById):Ut(),e}getElementId(t,e){let i;return e=e??t.type.split(":")[1]+"-",i=this.debugIds?this.getUniqueId(e,this.elementsById):Ut(),i}getBoundingBox(){const t={position:[0,0,0],rotation:0,rotationAxis:[0,1,0]};if(0===this.spaces.length&&0===this.elements.length)return{min:[0,0,0],max:[0,0,0],transform:t};const e=[];for(const r of this.spaces){const{min:t,max:i}=r.getAxisAlignedBoundingBox();e.push(t,i)}for(const r of this.getElementList()){const{min:t,max:i}=r.getAxisAlignedBoundingBox();e.push(t,i)}const{min:i,max:s}=as(e.flat());return{min:i,max:s,transform:t}}toJSON(){let t=this.spatialGraph.toJSON(),e=function(t){let e=[];for(let i of t.spaces){let t=i.toJSON();e.push(t)}return e}(this),i=function(t){let e=[];for(let i of t.elements){let t=i.toJSON();t&&e.push(t)}return e}(this),s=function(t){let e=[];for(let i of t.annotations){let t=i.toJSON();e.push(t)}return e}(this),r=function(t){let e=[];for(let i of t.views){let t=i.toJSON();e.push(t)}return e}(this);return{...super.toJSON(),spatialGraph:t,spaces:e,elements:i,annotations:s,views:r}}static fromJSON(t,e){const i=(null==e?void 0:e.spaceGraph)??new So,s=new $o(t.id);return Yo(s,t,i),(null==e?void 0:e.skipInsert)||i.insertSpatialStructure(s),s}}const jo="spatialStructure:floor";class zo extends zn{constructor(t){super(t,jo),this.parent=null,this.position=[0,0,0],this.rotation=0,this.level=null,this.layouts=[]}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation}setPosition(t){this.position=[...t],this.emit("floor-transform-change",this)}setRotation(t){this.rotation=t,this.emit("floor-transform-change",this)}setTransform(t,e){this.position=[...t],this.rotation=e,this.emit("floor-transform-change",this)}insertLayout(t){t.parent?ve.warn(`SpaceGraphLayout ${t.id} already part of floor ${t.parent.id}.`):(t.parent=this,this.layouts.push(t),this.spaceGraph&&Vn(t,this.spaceGraph))}removeLayout(t){-1!==this.layouts.indexOf(t)?(this.spaceGraph&&qn(t,this.spaceGraph),t.parent=null):ve.warn(`Floor ${t.id} not found.`)}createLayout(t){let e=new $o(t);return this.insertLayout(e),e}toJSON(){const t={...super.toJSON(),position:[...this.position],rotation:this.rotation,layouts:[]};null!==this.level&&(t.level=this.level);for(let e of this.layouts){let i=e.toJSON();t.layouts.push(i)}return t}static fromJSON(t,e){const i=(null==e?void 0:e.spaceGraph)??new So,s=new zo(t.id);xo(s,t),Cs(s,t,i.customAttributesById),s.position=[...t.position],s.rotation=t.rotation,void 0!==t.level&&(s.level=t.level);for(const r of t.layouts){const t=$o.fromJSON(r,{spaceGraph:i,skipInsert:!0});s.insertLayout(t)}return(null==e?void 0:e.skipInsert)||i.insertSpatialStructure(s),s}}const Vo="spatialStructure:building";class qo extends zn{constructor(t){super(t,Vo),this.floors=[],this.floorsByLevel={},this.location={latLong:[0,0],rotation:0}}copyForClone(t){super.copyForClone(t),this.location=JSON.parse(JSON.stringify(t.location))}getLevelOrder(){const t=Object.keys(this.floorsByLevel);return t.length?t.sort((t,e)=>{var i,s;return(null==(i=this.floorsByLevel[t][0])?void 0:i.position[1])-(null==(s=this.floorsByLevel[e][0])?void 0:s.position[1])}):[]}insertFloor(t){var e,i;t.parent?ve.warn(`Floor ${t.id} already part of building ${t.parent.id}.`):(t.parent=this,t.level&&((e=this.floorsByLevel)[i=t.level]??(e[i]=[]),this.floorsByLevel[t.level].push(t)),this.floors.push(t),this.spaceGraph&&Jn(t,this.spaceGraph))}removeFloor(t){let e=this.floors.indexOf(t);if(-1!==e){if(t.level&&this.floorsByLevel[t.level]){let e=this.floorsByLevel[t.level].indexOf(t);this.floorsByLevel[t.level].splice(e,1),this.floorsByLevel[t.level].length||delete this.floorsByLevel[t.level]}this.floors.splice(e,1),this.spaceGraph&&Kn(t,this.spaceGraph),t.parent=null}else ve.warn(`Floor ${t.id} not found.`)}createFloor(t){let e=new zo(t);return this.insertFloor(e),e}toJSON(){let t={...super.toJSON(),floors:[]},e=this.location;e.latLong[0]&&e.latLong[1]&&e.rotation&&(t.location={latLong:[...e.latLong],rotation:e.rotation});for(let i of this.floors){let e=i.toJSON();t.floors.push(e)}return t}static fromJSON(t,e){const i=e.spaceGraph??new So,s=new qo(t.id);xo(s,t),Cs(s,t,i.customAttributesById),t.location&&(s.location=JSON.parse(JSON.stringify(s.location)));for(const r of t.floors){const t=zo.fromJSON(r,{spaceGraph:i,skipInsert:!0});s.insertFloor(t)}return e.skipInsert||i.insertSpatialStructure(s),s}}function Jo(t,e,i,s){const r=1e-7*1e-7;let n=[e[0]-t[0],e[1]-t[1]],o=[s[0]-i[0],s[1]-i[1]],a=i[0]-t[0],l=i[1]-t[1],h=n[0]*o[1]-n[1]*o[0],u=h*h,c=n[0]*n[0]+n[1]*n[1];if(u>r*c*(o[0]*o[0]+o[1]*o[1])){let e=(a*o[1]-l*o[0])/h,i=(a*n[1]-l*n[0])/h;return{tag:2,intersect:!0,p:[t[0]+e*n[0],t[1]+e*n[1]],u:e,v:i}}return h=a*n[1]-l*n[0],u=h*h,u>r*c*(a*a+l*l)?{tag:0,intersect:!1}:{tag:1,intersect:!0}}function Ko(t,e,i,s){const r=[e[0]-t[0],e[1]-t[1]],n=[s[0]-i[0],s[1]-i[1]],o=i[0]-t[0],a=i[1]-t[1];let l=r[0]*n[1]-r[1]*n[0],h=l*l;const u=r[0]*r[0]+r[1]*r[1];let c,d,p,f;if(h>1e-14*u*(n[0]*n[0]+n[1]*n[1])){const e=(o*n[1]-a*n[0])/l;if(e<0||e>1)return{tag:0,intersect:!1};{const i=(o*r[1]-a*r[0])/l;return i<0||i>1?{tag:0,intersect:!1}:(c=t[0]+e*r[0],d=t[1]+e*r[1],{tag:1,intersect:!0,p:[c,d],u:e,v:i})}}if(l=o*r[1]-a*r[0],h=l*l,h>1e-14*u*(o*o+a*a))return{tag:2,intersect:!1};{const e=(r[0]*o+r[1]*a)/u,i=e+(r[0]*n[0]+r[1]*n[1])/u;let s,l;e<i?(s=e,l=i):(s=i,l=e);const h=function(t,e,i,s){if(e<i||t>s)return{tag:0,intersect:!1};if(t===i&&e===s)return{tag:1,intersect:!0};if(e>i)return e<s?{tag:3,intersect:!0,w0:t<i?i:t,w1:e>s?s:e}:{tag:2,intersect:!0,w:t};return{tag:2,intersect:!0,w:e}}(0,1,s,l);switch(h.tag){case 0:return{tag:3,intersect:!1};case 1:return{tag:4,intersect:!0};case 2:{const e=h.w;return c=t[0]+e*r[0],d=t[1]+e*r[1],{tag:5,intersect:!0,p:[c,d],u:e}}case 3:{const e=h.w0,i=h.w1;return c=t[0]+e*r[0],d=t[1]+e*r[1],p=t[0]+i*r[0],f=t[1]+i*r[1],{tag:6,intersect:!0,p:[c,d],q:[p,f],u0:e,u1:i}}default:throw new Error("Unknown tag value.")}}}function Zo(...t){}function Qo(t,e,i,s){let r=t[0],n=t[1];for(let o=1;o<e.length-1;o++){let a=e[o];if(bi(a,r,n)<1e-7)return i?t[0]=a:t[1]=a,void(s?e.splice(0,o):e.splice(o+1))}}function ta(t){let e=0;for(;e<t.length-2;){let i=t[e],s=t[e+2];bi(t[e+1],i,s)<1e-7?t.splice(e+1,1):e++}}function ea(t){if(t.length<3)return!1;let e=t.slice();e.push(t[0]);for(let i=0;i<e.length-2;i++){let t=e[i],s=e[i+1];for(let r=i+1;r<e.length-1;r++){const i=1e-7;let n=Ko(t,s,e[r],e[r+1]);if(1===n.tag&&n.u>i&&n.u<1-i)return!0}}return!1}function ia(t,e){return{position:[t,e],edges:[],geometry:{parameters:{joinStyle:{type:"miter",parameters:{distance:.05}}}}}}function sa(t,e){let i={indices:[t,e],faces:[-1,-1],geometry:{tangible:!0,skipped:!1,parameters:{width:.15,height:2.5,offset:0},fragments:[],computed:{valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}},openings:[]};return i.geometry.fragments=[{edge:i,angle:0,points:[],joinPoints:[],sidePoints:[]},{edge:i,angle:0,points:[],joinPoints:[],sidePoints:[]}],i}const ra="intersectCap",na="intersectCap";function oa(...t){}function aa(t){let e=t.toFixed(3),i=parseFloat(e);return e+=t>i?"+":t<i?"-":" ",t>=0&&(e=" "+e),e}function la(t){if(t.length>0)for(let e=0;e<t.length;e++){let i=t[e];oa((i[0],i[1]))}}function ha(t,e){for(let i of e)if(t.length>0){let e=t[0],s=t[t.length-1],r=ri(ui(i,e)),n=ri(ui(i,s));r>1e-7&&n>1e-7&&t.push(i)}else t.push(i)}function ua(t,e,i,s,r){0===t.joinPoints.length?(ha(t.joinPoints,[...s,i]),ha(t.sidePoints[0],r)):(ha(t.joinPoints,s),ha(t.sidePoints[1],r.slice().reverse())),la(t.joinPoints),la(t.sidePoints[0]),la(t.sidePoints[1])}function ca(t,e,i,s,r){ua(t,0,i,[s],[s]),ua(e,0,i,[r],[r]),t.edge.geometry.computed.skipped=!0,e.edge.geometry.computed.skipped=!0}function da(t,e,i,s){ua(t,0,i,[s],[s]),ua(e,0,i,[s],[s])}function pa(t,e,i,s,r){ua(t,0,i,[s],[s]),ua(e,0,i,[r],[r])}function fa(t,e,i,s,r,n,o,a,l,h,u){if("ignore"===u)ca(t,e,i,r,a);else{let u;if(u=h?Jo(s,r,l,a):Jo(n,r,o,a),2!==u.tag)return ve.warn("Edge side line does not intersect edge cap line, ignoring result."),void ca(t,e,i,r,a);let c=u.p;h?(ua(t,0,i,[c],[c]),ua(e,0,i,[a,c],[a])):(ua(t,0,i,[r,c],[r]),ua(e,0,i,[c],[c]))}}function ma(t,e,i,s,r,n,o,a,l,h,u,c){t.edge.id,e.edge.id;let d=Jo(s,r,a,l);if(2!==d.tag)return ve.warn("Edge side lines do not intersect, ignoring result.",d),void ca(t,e,i,r,l);let p=ri(ui(r,s)),f=ri(ui(l,a)),m=Math.max(0,1-.2/p),g=Math.max(0,1-.2/f),{p:y,u:v,v:x}=d,b="",w="";if(v>=.9999999)if(o)if(x>=.9999999){const s=1;if(ri(ui(y,i))>s){let s,n=Jo(y,i,r,l);2!==n.tag?(ve.warn("Bevel construction failed, using center point.",n),s=oi(r,l,.5)):s=n.p,ua(t,0,i,[s],[r,s]),ua(e,0,i,[s],[l,s])}else da(t,e,i,y)}else if(x>=g)da(t,e,i,y);else{let c=o&&u?ra:"ignore";fa(t,e,i,s,r,n,a,l,h,!0,c),w="ignore"===c?"* (ignore)":"* (intersectCap)"}else ca(t,e,i,r,l);else if(x>=.9999999)if(u)if(v>=m)da(t,e,i,y);else{let c=o&&u?ra:"ignore";fa(t,e,i,s,r,n,a,l,h,!1,c),b="ignore"===c?"* (ignore)":"* (intersectCap)"}else ca(t,e,i,r,l);else ve.warn("Edge side line segments cross, ignoring result."),ca(t,e,i,r,l);aa(v),m.toFixed(3),aa(x),g.toFixed(3)}function ga(t,e,i,s,r,n,o,a,l,h,u,c){t.edge.id,e.edge.id;let d=Jo(s,r,a,l);if(2!==d.tag)return ve.warn("Edge side lines do not intersect, ignoring result.",d),void ca(t,e,i,r,l);let p=ri(ui(r,s)),f=ri(ui(l,a)),m=Math.max(0,1-1/p),g=Math.max(0,1-1/f),{p:y,u:v,v:x}=d,b="",w="";if(v>=0&&v<=1+1e-7&&x>=0&&x<=1+1e-7)da(t,e,i,y);else if(v>1&&x>1)ve.warn("Edge side line segments do not cross, ignoring result."),ca(t,e,i,r,l);else if(v>1)if(x>=g)da(t,e,i,y);else{let c=o&&u?na:"ignore";fa(t,e,i,s,r,n,a,l,h,!1,c),w="ignore"===c?"* (ignore)":"* (intersectCap)"}else if(x>1)if(v>=m)da(t,e,i,y);else{let c=o&&u?na:"ignore";fa(t,e,i,s,r,n,a,l,h,!0,c),b="ignore"===c?"* (ignore)":"* (intersectCap)"}else ca(t,e,i,r,l);aa(v),m.toFixed(3),aa(x),g.toFixed(3)}function ya(t,e){let i,s,r,n=e[0];n.indices[0]===t?(i=n.geometry.fragments[0],s=i.points[0],r=i.points[1]):(i=n.geometry.fragments[1],s=i.points[1],r=i.points[0]),i.joinPoints.push(s,r),i.sidePoints[0].push(s),i.sidePoints[1].push(r)}function va(t,e,i){for(let s=0;s<e.length;s++){let r,n,o,a,l,h,u,c,d,p,f,m,g=e[s],y=s<e.length-1?e[s+1]:e[0],v=!g.geometry.skipped&&0!==g.geometry.parameters.width,x=!y.geometry.skipped&&0!==y.geometry.parameters.width;if(!v&&!x)continue;g.indices[0]===t?(r=g.geometry.fragments[0],n=g.geometry.fragments[1],o=n.points[0],a=r.points[0],l=r.points[1],h=i[g.indices[1]].position):(r=g.geometry.fragments[1],n=g.geometry.fragments[0],o=n.points[1],a=r.points[1],l=r.points[0],h=i[g.indices[0]].position),y.indices[0]===t?(u=y.geometry.fragments[0],c=y.geometry.fragments[1],d=c.points[1],p=u.points[1],f=u.points[0],m=i[y.indices[1]].position):(u=y.geometry.fragments[1],c=y.geometry.fragments[0],d=c.points[0],p=u.points[0],f=u.points[1],m=i[y.indices[0]].position);let b=i[t].position;const w=.01;let _=yi(o,a,d,p);if(_<w||_>Math.PI-w)pa(r,u,b,a,p);else{1===mi(h,b,m)?ma(r,u,b,o,a,l,v,d,p,f,x):ga(r,u,b,o,a,l,v,d,p,f,x)}}}function xa(t){let e=t.geometry;e.fragments[0].joinPoints=[],e.fragments[0].sidePoints[0]=[],e.fragments[0].sidePoints[1]=[],e.fragments[1].joinPoints=[],e.fragments[1].sidePoints[0]=[],e.fragments[1].sidePoints[1]=[],e.computed={valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}}function ba(t,e){let i=function(t){let e={};for(let i of t){let t=i.indices[0],s=i.indices[1],r=Math.min(t,s),n=Math.max(t,s);e[r.toString()+"_"+n.toString()]=i}return e}(e),s=[];for(let n of e){if(!n.geometry.tangible||n.geometry.skipped)continue;let t=n.indices[0],e=n.indices[1];s[t]=!0,s[e]=!0,xa(n)}let{vertices:r}=t;for(let n=0;n<r.length;n++){if(!s[n])continue;let t=[],e=r[n];for(let s of e.edges){if(!s.geometry.tangible||s.geometry.skipped)continue;let e=s.indices[0],r=s.indices[1],n=Math.min(e,r),o=Math.max(e,r);i[n.toString()+"_"+o.toString()]&&t.push(s)}oa(t.length),1===t.length?ya(n,t):va(n,t,r)}}function wa(t,e){let i=e.element;if(i?t.geometry.tangible="element:spaceDivider"!==i.type:e.boundaryWalls[0]||e.boundaryWalls[1]?t.geometry.tangible=!0:t.geometry.tangible=!1,i&&"element:wall"===i.type){let{width:e,height:s,offset:r}=i.parameters;t.geometry.parameters={width:e,height:s,offset:r}}else t.geometry.parameters={width:0,height:0,offset:0}}function _a(t,e){let i=[],s={};for(let a of e)for(let t of a.vertices)if(void 0===s[t.id]){let e=ia(t.position[0],t.position[1]);e.reference=t,s[t.id]=i.push(e)-1}let r=[],n={};for(let a of e){let t=a.vertices[0],e=a.vertices[1],i=sa(s[t.id],s[e.id]);wa(i,a),i.id=a.id,i.reference=a,r.push(i),n[a.id]=!0}let o=function(t,e){return{vertices:t,edges:e,cycles:[],faces:[]}}(i,r);return function(t){let{vertices:e,edges:i}=t;for(let s of e)s.edges=[];for(let s of i){let t=s.indices[0],i=s.indices[1];e[t].edges.push(s),e[i].edges.push(s)}}(o),function(t){let{vertices:e}=t;for(let i=0;i<e.length;i++){let t=e[i],s=t.edges,r=[];for(let n of s){let s=e[i===n.indices[0]?n.indices[1]:n.indices[0]],o={edge:n,angle:ei([s.position[0]-t.position[0],s.position[1]-t.position[1]]),points:[],joinPoints:[],sidePoints:[[],[]]},a={edge:n,fragment:o};i===n.indices[0]?n.geometry.fragments[0]=o:n.geometry.fragments[1]=o,r.push(a)}r.sort((t,e)=>t.fragment.angle-e.fragment.angle),t.edges=r.map(t=>t.edge)}}(o),o}function Pa(t){const e=t.map(t=>t.geometry.computed),i=function(t){var e;if(0===t.length)return[];const i={};for(const l of t)for(const t of l.indices)i[t]??(i[t]=[]),i[t].push(l);let s=(null==(e=Object.entries(i).find(([,t])=>1===t.length))?void 0:e[0])||Object.keys(i)[0];const r=[],n=/* @__PURE__ */new Set;let o=parseInt(s),a=i[o][0];for(;r.length<t.length;){if(n.has(a)){if(a=t.find(t=>!n.has(t)),!a)break;o=a.indices[0];continue}const e=a.indices[0]!==o;r.push({edge:a,reverse:e}),n.add(a);const s=e?a.indices[0]:a.indices[1],l=i[s].find(t=>!n.has(t));if(l)o=s,a=l;else{if(a=t.find(t=>!n.has(t)),!a)break;o=a.indices[0]}}return r}(t),s=t[0].geometry.computed;let r=s.valid;const n=i[0].reverse,o=i[0].edge.geometry.computed,a=i[i.length-1].reverse,l=i[i.length-1].edge.geometry.computed,h=n?o.joinPoints2:o.joinPoints1,u=a?l.joinPoints1:l.joinPoints2,c=[],d=[];for(const{edge:m,reverse:g}of i){const{computed:t}=m.geometry;g?(c.unshift(...t.sidePoints2),d.push(...t.sidePoints1)):(c.unshift(...t.sidePoints1),d.push(...t.sidePoints2))}const p=Y(e.map(t=>t.points));let f=[];if(1===p.length)f=p[0];else if(p.length>1){const t=$(p,.001,void 0,!0);t.length>0&&(f=t[0])}return 0===f.length&&(ve.warn(`Empty wall geometry after merging edge profiles: ${t.map(t=>t.id).join(", ")}`),r=!1),{valid:r,skipped:s.skipped,selfIntersecting:s.selfIntersecting,sidePoints1:c.slice(),sidePoints2:d.slice(),joinPoints1:h.slice(),joinPoints2:u.slice(),points:f}}function Ea(t,e){zs(t,e),e.emit("geometry-profile-update",e);for(let i of e.slabs)i.emit("geometry-profile-update",i)}function Ta(t){let e=function(t){let e=/* @__PURE__ */new Map;for(let i of t)for(let t of i.boundaryWalls)t&&e.set(t.id,t);return[...e.values()]}(t);for(let i of e)Mr(i)}function Aa(t){let e=t.spatialGraph.edges,i=_a(0,e);!function(t){let{vertices:e,edges:i}=t;for(let s of i){let{geometry:t}=s,i=s.indices[0],r=s.indices[1],n=t.parameters.width,o=t.parameters.offset,a=e[i].position,l=e[r].position,h=ui(l,a);if(t.skipped=ri(h)<1e-7,!t.skipped){let e=li(ai(h)),i=hi(e,.5*n+o),s=hi(e,-.5*n+o),r=ti(a,i),u=ti(a,s),c=ti(l,i),d=ti(l,s);t.fragments[0].points=[r,u],t.fragments[1].points=[c,d]}}}(i),ba(i,i.edges),function(t,e){for(let i of e){let{geometry:t}=i;if(!t.tangible||t.skipped||0===t.parameters.width)continue;let e=t.fragments[0],s=t.fragments[1],r=[...e.joinPoints],n=[...s.joinPoints],o=[...e.sidePoints[0]],a=[...e.sidePoints[1]],l=[...s.sidePoints[0]],h=[...s.sidePoints[1]],u=Jo(r[0],n[n.length-1],r[r.length-1],n[0]);2===u.tag&&u.u>0&&u.u<1&&u.v>0&&u.v<1&&(n.reverse(),l.reverse(),h.reverse(),[l,h]=[h,l]);let c=h.concat(o),d=a.concat(l);2===c.length&&2===d.length&&(Qo(c,r,!1,!0),Qo(c,n,!0,!1),Qo(d,r,!0,!1),Qo(d,n,!1,!0)),ta(c),ta(r),ta(d),ta(n),1===mi(c[0],c[c.length-1],d[0])&&(c.reverse(),d.reverse(),r.reverse(),n.reverse(),[c,d]=[d,c]);let p=c.slice(0,c.length-1),f=r.slice(0,r.length-1),m=d.slice(0,d.length-1),g=n.slice(0,n.length-1),y=tt(p.concat(f).concat(m).concat(g),.001),v=i.geometry.computed;v.sidePoints1=c,v.sidePoints2=d,v.joinPoints1=r,v.joinPoints2=n,v.points=y,v.selfIntersecting=ea(v.points),v.valid=v.points.length>=3&&!v.skipped&&!v.selfIntersecting,Zo(i.id),Zo(v.valid),Zo(v.skipped),Zo(v.selfIntersecting)}}(0,i.edges),function(t){var e;let i={};for(let s of t.edges){let t=s.reference.element;if("element:wall"===(null==t?void 0:t.type)){let r=s.geometry.computed;1===t.getEdges().length?(t.geometryProfile={valid:r.valid,skipped:r.skipped,selfIntersecting:r.selfIntersecting,sidePoints1:r.sidePoints1.slice(),sidePoints2:r.sidePoints2.slice(),joinPoints1:r.joinPoints1.slice(),joinPoints2:r.joinPoints2.slice(),points:r.points.slice()},t.emit("geometry-profile-update",t)):(i[e=t.id]??(i[e]=[]),i[t.id].push(s),i[t.id].length===t.getEdges().length&&(t.geometryProfile=Pa(i[t.id]),t.emit("geometry-profile-update",t)))}}}(i),function(t){var e;for(let i of t)"element:wall"===(null==(e=i.element)?void 0:e.type)&&Rr(i.element)}(e),Ta(e)}function Ia(t){Aa(t),function(t){let e=t.spaces;for(let i of e){Ea(t,i);for(let t of i.slabs)Zs(t)}}(t)}function Sa(t){return new Promise((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error)})}function Ca(t,e){let i;return(s,r)=>(()=>{if(i)return i;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),i=Sa(s),i.then(t=>{t.onclose=()=>i=void 0},()=>{}),i})().then(t=>r(t.transaction(e,s).objectStore(e)))}let Ma;function Oa(){return Ma||(Ma=Ca("keyval-store","keyval")),Ma}const Na=["eq","neq","gt","gte","lt","lte","in","nin","contains","null"],La=t=>{var e;return Yn(t)?null==(e=t.geometry)?void 0:e.polygons:"element:wall"===t.type?[t.geometryProfile.points]:"getBoundingBoxContour"in t?[t.getBoundingBoxContour()]:[]},Ra=(t,e)=>{var i,s;switch(e){case"localBoundingBox":{const{min:e,max:i}=t.getBoundingBox();return{min:e,max:i}}case"boundingBox":{const{min:e,max:i}="axisAlignedBoundingBox"in t?t.getAxisAlignedBoundingBox():t.getBoundingBox();return{min:e,max:i}}case"dimensions":{const e=t.getBoundingBox();return{length:e.max[0]-e.min[0],width:e.max[2]-e.min[2],height:e.max[1]-e.min[1]}}case"boundingBoxContour":return"getBoundingBoxContour"in t?t.getBoundingBoxContour():void 0;case"polygons":case"contour":return La(t);case"area":return Yn(t)?t.getArea():void 0;case"position":case"rotation":if("getWorldTransform"in t){return t.getWorldTransform()[e]}return;case"transform":if("getWorldTransform"in t){const{position:e,rotation:i}=t.getWorldTransform();return{position:e,rotation:i}}return;case"localTransform":if("getTransform"in t){const{position:e,rotation:i}=t.getTransform();return{position:e,rotation:i}}return;case"labelPoint":return Pi(La(t));case"category":return Yn(t)?t.attributes.program:Hn(t)?t.attributes.categories[0]:"product"in t?null==(i=t.product)?void 0:i.attributes.categories[0]:void 0;case"subCategory":return Yn(t)?t.attributes.usage:Hn(t)?t.attributes.subCategories[0]:"product"in t?null==(s=t.product)?void 0:s.attributes.subCategories[0]:void 0;case"seatCapacity":if(Yn(t)){return t.getElements("element:asset").reduce((t,e)=>{var i,s;return t+((null==(s=null==(i=e.product)?void 0:i.attributes)?void 0:s.seatCapacity)||0)},0)}return Hn(t)?t.attributes.seatCapacity||0:void 0;default:return}},Ba=(t,e)=>{switch(e){case"spaceGraph":case"layout":case"rotationAxis":return;default:{const i=t[e];return"function"!=typeof i?i:void 0}}},ka={id:!0,type:!0,name:!0,category:!0,subCategory:!0,dimensions:!0,boundingBox:!0},Fa={id:!0,type:!0},Da=/* @__PURE__ */new Set(["elements","parent"]);function Ua(t,e,i=0){if(!t||"object"!=typeof t)return t;const s={};for(const[r,n]of Object.entries(e)){if(Da.has(r)&&i>=3)continue;const e=Da.has(r)?i+1:i;if(!0===n||void 0===n)if("elements"!==r||Hn(t))if("parent"===r&&"parent"in t&&t.parent&&Wn(t))s[r]=Ua(t.parent,Fa,e);else if("product"===r&&"product"in t&&t.product)s[r]=Ua(t.product,ka,i);else{const e=Ra(t,r);if(void 0!==e)s[r]=e;else{const e=Ba(t,r);void 0!==e&&(s[r]=e)}}else{const i=Yn(t)?t.getElements():t.elements;s[r]=$a(i,{},e)}else if("object"==typeof n)if("elements"!==r||Hn(t)){const i=t[r];if(Array.isArray(i))s[r]=i.map(t=>Ua(t,n,e));else if(i&&"object"==typeof i)s[r]=Ua(i,n,e);else{const i=Ra(t,r);null!=i&&(s[r]=Ua(i,n,e))}}else{const i=Yn(t)?t.getElements():t.elements,o={select:n.select||Fa,where:n.where};s[r]=$a(i,o,e)}}return s}const Ga=t=>null!=t&&"object"==typeof t&&!Array.isArray(t)&&Na.some(e=>e in t);function Xa(t,e){for(const[i,s]of Object.entries(e)){const e=t[i];if(null!=s)if("object"!=typeof s||Array.isArray(s)){if(e!==s)return!1}else if(Ga(s)){if(!Wa(e,s))return!1}else if(!e||"object"!=typeof e||!Xa(e,s))return!1}return!0}function Wa(t,e){if("eq"in e&&t!==e.eq)return!1;if("ne"in e&&t===e.ne)return!1;if("gt"in e&&!("number"==typeof t&&"number"==typeof e.gt&&t>e.gt))return!1;if("gte"in e&&!("number"==typeof t&&"number"==typeof e.gte&&t>=e.gte))return!1;if("lt"in e&&!("number"==typeof t&&"number"==typeof e.lt&&t<e.lt))return!1;if("lte"in e&&!("number"==typeof t&&"number"==typeof e.lte&&t<=e.lte))return!1;if("in"in e&&Array.isArray(e.in)&&!e.in.includes(t))return!1;if("nin"in e&&Array.isArray(e.nin)&&e.nin.includes(t))return!1;if("contains"in e&&("string"!=typeof t||"string"!=typeof e.contains||!t.toLowerCase().includes(e.contains.toLowerCase())))return!1;if("null"in e){const i=null==t;if(e.null!==i)return!1}return!0}function Ya(t,e){if(!e)return t;const i=JSON.parse(JSON.stringify(t)),s=t=>"object"==typeof t&&null!==t;return function t(e,i){for(const r in i)if(e[r]){if(!0===e[r])continue;s(i[r])&&s(e[r])&&t(e[r],i[r])}else s(i[r])&&!Ga(i[r])?(e[r]={},t(e[r],i[r])):e[r]=!0}(i,e),i}function Ha(t,e){if(!e||!0===e)return t;const i={};for(const[s,r]of Object.entries(e))if(s in t)if(!0===r)i[s]=t[s];else if("object"==typeof r&&t[s])if(r&&("select"in r||"where"in r))i[s]=t[s];else if(Array.isArray(t[s])){const e=t[s];i[s]=e.map(t=>"object"==typeof t&&null!==t?Ha(t,r):t)}else"object"==typeof t[s]&&null!==t[s]&&(i[s]=Ha(t[s],r));return i}function $a(t,e,i=0){const s=(null==e?void 0:e.select)||Fa,r=Ya(s,null==e?void 0:e.where),n=[];for(const o of t){const t=Ua(o,r,i);n.push(t)}return((null==e?void 0:e.where)?n.filter(t=>Xa(t,e.where)):n).map(t=>Ha(t,s))}function ja(t){const{at:e,within:i,...s}=t;return{spatial:{at:e,within:i},nonSpatial:s}}function za(t,e,i){var s,r;if(!(null==(s=null==i?void 0:i.where)?void 0:s.at)&&!(null==(r=null==i?void 0:i.where)?void 0:r.within))return{items:t,args:i};const{spatial:n,nonSpatial:o}=ja(i.where),a=function(t,e,i){const{at:s,within:r}=i;if(!s&&!r)return t;const n=s?{min:s}:{min:r.min,max:r.max},o=e.spatialIndex.find(n),a=new Set(o.map(t=>t.id));return t.filter(t=>a.has(t.id))}(t,e,n),l=Object.keys(o).length>0?o:void 0;return{items:a,args:{...i,where:l}}}function Va(t,e){var i;const s=t.elementsById[e.id]||t.spacesById[e.id]||(null==(i=t.spaceGraph)?void 0:i.productsById[e.id]);if(!s)return!1;let r=e.where;if(e.where.at||e.where.within){const{spatial:i,nonSpatial:s}=ja(e.where),n=i.at?{min:i.at}:{min:i.within.min,max:i.within.max};if(!t.spatialIndex.find(n).some(t=>t.id===e.id))return!1;r=s}if(0===Object.keys(r).length)return!0;return Xa(Ua(s,Ya({},r)),r)}for(var qa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ja="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Ka=0;Ka<64;Ka++)Ja[qa.charCodeAt(Ka)]=Ka;var Za={exports:{}};function Qa(t,e){return t<e?-1:t>e?1:0}const tl=/* @__PURE__ */St(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:class{constructor(t=[],e=Qa){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(t){this.data.push(t),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:i}=this,s=e[t];for(;t>0;){const r=t-1>>1,n=e[r];if(i(s,n)>=0)break;e[t]=n,t=r}e[t]=s}_down(t){const{data:e,compare:i}=this,s=this.length>>1,r=e[t];for(;t<s;){let s=1+(t<<1),n=e[s];const o=s+1;if(o<this.length&&i(e[o],n)<0&&(s=o,n=e[o]),i(n,r)>=0)break;e[t]=n,t=s}e[t]=r}}},Symbol.toStringTag,{value:"Module"})));var el;!function(){if(el)return Za.exports;el=1;var t=tl;function e(e,r,n){var o,a,l,h;r=r||1;for(var u=0;u<e[0].length;u++){var c=e[0][u];(!u||c[0]<o)&&(o=c[0]),(!u||c[1]<a)&&(a=c[1]),(!u||c[0]>l)&&(l=c[0]),(!u||c[1]>h)&&(h=c[1])}var d=l-o,p=h-a,f=Math.min(d,p),m=f/2;if(0===f){var g=[o,a];return g.distance=0,g}for(var y=new t(void 0,i),v=o;v<l;v+=f)for(var x=a;x<h;x+=f)y.push(new s(v+m,x+m,m,e));var b=function(t){for(var e=0,i=0,r=0,n=t[0],o=0,a=n.length,l=a-1;o<a;l=o++){var h=n[o],u=n[l],c=h[0]*u[1]-u[0]*h[1];i+=(h[0]+u[0])*c,r+=(h[1]+u[1])*c,e+=3*c}return 0===e?new s(n[0][0],n[0][1],0,t):new s(i/e,r/e,0,t)}(e),w=new s(o+d/2,a+p/2,0,e);w.d>b.d&&(b=w);for(var _=y.length;y.length;){var P=y.pop();P.d>b.d&&(b=P,n&&console.log("found best %d after %d probes",Math.round(1e4*P.d)/1e4,_)),P.max-b.d<=r||(m=P.h/2,y.push(new s(P.x-m,P.y-m,m,e)),y.push(new s(P.x+m,P.y-m,m,e)),y.push(new s(P.x-m,P.y+m,m,e)),y.push(new s(P.x+m,P.y+m,m,e)),_+=4)}n&&(console.log("num probes: "+_),console.log("best distance: "+b.d));var E=[b.x,b.y];return E.distance=b.d,E}function i(t,e){return e.max-t.max}function s(t,e,i,s){this.x=t,this.y=e,this.h=i,this.d=function(t,e,i){for(var s=!1,n=1/0,o=0;o<i.length;o++)for(var a=i[o],l=0,h=a.length,u=h-1;l<h;u=l++){var c=a[l],d=a[u];c[1]>e!=d[1]>e&&t<(d[0]-c[0])*(e-c[1])/(d[1]-c[1])+c[0]&&(s=!s),n=Math.min(n,r(t,e,c,d))}return 0===n?0:(s?1:-1)*Math.sqrt(n)}(t,e,s),this.max=this.d+this.h*Math.SQRT2}function r(t,e,i,s){var r=i[0],n=i[1],o=s[0]-r,a=s[1]-n;if(0!==o||0!==a){var l=((t-r)*o+(e-n)*a)/(o*o+a*a);l>1?(r=s[0],n=s[1]):l>0&&(r+=o*l,n+=a*l)}return(o=t-r)*o+(a=e-n)*a}t.default&&(t=t.default),Za.exports=e,Za.exports.default=e,Za.exports}();var il,sl={exports:{}};var rl,nl,ol=(il||(il=1,rl=sl,nl=function(){var t={},e=Math.PI/180,i=180/Math.PI,s=6378137,r=20037508.342789244;function n(t){return Number(t)===t&&t%1!=0}function o(e){if(e=e||{},this.size=e.size||256,this.expansion=!0===e.antimeridian?2:1,!t[this.size]){var i=this.size,s=t[this.size]={};s.Bc=[],s.Cc=[],s.zc=[],s.Ac=[];for(var r=0;r<30;r++)s.Bc.push(i/360),s.Cc.push(i/(2*Math.PI)),s.zc.push(i/2),s.Ac.push(i),i*=2}this.Bc=t[this.size].Bc,this.Cc=t[this.size].Cc,this.zc=t[this.size].zc,this.Ac=t[this.size].Ac}return o.prototype.px=function(t,i){if(n(i)){var s=this.size*Math.pow(2,i),r=s/2,o=s/360,a=s/(2*Math.PI),l=s,h=Math.min(Math.max(Math.sin(e*t[1]),-.9999),.9999),u=r+t[0]*o,c=r+.5*Math.log((1+h)/(1-h))*-a;return u>l*this.expansion&&(u=l*this.expansion),c>l&&(c=l),[u,c]}return r=this.zc[i],h=Math.min(Math.max(Math.sin(e*t[1]),-.9999),.9999),u=Math.round(r+t[0]*this.Bc[i]),c=Math.round(r+.5*Math.log((1+h)/(1-h))*-this.Cc[i]),u>this.Ac[i]*this.expansion&&(u=this.Ac[i]*this.expansion),c>this.Ac[i]&&(c=this.Ac[i]),[u,c]},o.prototype.ll=function(t,e){if(n(e)){var s=this.size*Math.pow(2,e),r=s/360,o=s/(2*Math.PI),a=s/2,l=(t[1]-a)/-o;return[(t[0]-a)/r,i*(2*Math.atan(Math.exp(l))-.5*Math.PI)]}return l=(t[1]-this.zc[e])/-this.Cc[e],[(t[0]-this.zc[e])/this.Bc[e],i*(2*Math.atan(Math.exp(l))-.5*Math.PI)]},o.prototype.bbox=function(t,e,i,s,r){s&&(e=Math.pow(2,i)-1-e);var n=[t*this.size,(+e+1)*this.size],o=[(+t+1)*this.size,e*this.size],a=this.ll(n,i).concat(this.ll(o,i));return"900913"===r?this.convert(a,"900913"):a},o.prototype.xyz=function(t,e,i,s){"900913"===s&&(t=this.convert(t,"WGS84"));var r=[t[0],t[1]],n=[t[2],t[3]],o=this.px(r,e),a=this.px(n,e),l=[Math.floor(o[0]/this.size),Math.floor((a[0]-1)/this.size)],h=[Math.floor(a[1]/this.size),Math.floor((o[1]-1)/this.size)],u={minX:Math.min.apply(Math,l)<0?0:Math.min.apply(Math,l),minY:Math.min.apply(Math,h)<0?0:Math.min.apply(Math,h),maxX:Math.max.apply(Math,l),maxY:Math.max.apply(Math,h)};if(i){var c={minY:Math.pow(2,e)-1-u.maxY,maxY:Math.pow(2,e)-1-u.minY};u.minY=c.minY,u.maxY=c.maxY}return u},o.prototype.convert=function(t,e){return"900913"===e?this.forward(t.slice(0,2)).concat(this.forward(t.slice(2,4))):this.inverse(t.slice(0,2)).concat(this.inverse(t.slice(2,4)))},o.prototype.forward=function(t){var i=[s*t[0]*e,s*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return i[0]>r&&(i[0]=r),i[0]<-r&&(i[0]=-r),i[1]>r&&(i[1]=r),i[1]<-r&&(i[1]=-r),i},o.prototype.inverse=function(t){return[t[0]*i/s,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/s)))*i]},o}(),rl.exports=nl),sl.exports);const al=/* @__PURE__ */It(ol),ll={work:{name:"Work",isHidden:!0,description:"space for individual head-down work",spaceUsage:{privateOffice:{name:"Private office",category:["office"]},focusRoom:{name:"Focus room",category:["office"]},openWorkspace:{name:"Open workspace",category:["office"]},enclosedWorkspace:{name:"Enclosed workspace",category:["office"]},closedWorkspace:{name:"Closed workspace",isDeprecated:!0,category:["office"]},executiveOffice:{name:"Executive office",isDeprecated:!0,category:["office"]}}},meet:{name:"Meet",isHidden:!0,spaceUsage:{meetingRoom:{name:"Meeting room",category:["office"]},hub:{name:"Hub",category:["office"]},assembly:{name:"Assembly",category:["office"]},boardRoom:{name:"Board room",category:["office"]},trainingRoom:{name:"Training room",category:["office"]},collaboration:{name:"Collaboration",isDeprecated:!0,category:["office"]}}},live:{name:"live",isHidden:!0,spaceUsage:{living:{name:"Living",category:["residential"]},dining:{name:"Dining",category:["residential"]},dining_living:{name:"Living & Dining",category:["residential"]},homeOffice:{name:"Home office",category:["residential"]},bedroom:{name:"Bedroom",category:["residential"]}}},socialize:{name:"Socialize",isHidden:!0,spaceUsage:{lobby:{name:"Lobby",category:["office","residential"]},reception:{name:"Reception",category:["office"]},lounge:{name:"Lounge",category:["office"]},cafe:{name:"Cafe",category:["office"]},canteen:{name:"Canteen",category:["office"]},pantry:{name:"Pantry",category:["office"]},terrace:{name:"Terrace",isOutdoor:!0,category:["office","residential"]},balcony:{name:"Balcony",isOutdoor:!0,category:["office","residential"]},rooftop:{name:"Rooftop",isOutdoor:!0,category:["office","residential"]},courtyard:{name:"Courtyard",isOutdoor:!0,category:["office","residential"]},garden:{name:"Garden",isOutdoor:!0,category:["residential"]},common:{name:"Common",isDeprecated:!0,category:["office"]}}},support:{name:"Support",isHidden:!0,spaceUsage:{serviceKitchen:{name:"Service kitchen",category:["office"]},printStation:{name:"Print station",category:["office"]},storage:{name:"Storage",category:["lightIndustrial","residential","office","parking"]},mailRoom:{name:"Mail room",category:["office"]},operationalRoom:{name:"Operational room",category:["lightIndustrial","office","parking"]},serviceRoom:{name:"Service room",category:["office"]},laundryRoom:{name:"Laundry room",category:["residential"]},loadingDock:{name:"Loading dock",category:["lightIndustrial"]},operate:{name:"Operate",isDeprecated:!0,category:["office"]},services:{name:"Services",isDeprecated:!0,category:["office","residential"]}}},care:{name:"Care",isHidden:!0,spaceUsage:{kitchen:{name:"Kitchen",category:["residential"]},wellnessRoom:{name:"Wellness room",category:["lightIndustrial","office"]},restroom:{name:"Restroom",category:["lightIndustrial","office","parking"]},bathroom:{name:"Bathroom",category:["residential"]},shower:{name:"Shower",category:["lightIndustrial","office","residential"]},toilet:{name:"Toilet",category:["residential"]}}},circulate:{name:"Circulate",isHidden:!0,spaceUsage:{corridor:{name:"Corridor",category:["lightIndustrial","residential","office","parking"]},foyer:{name:"Foyer",category:["lightIndustrial","residential","office","parking"]},staircase:{name:"Staircase",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},elevator:{name:"Elevator",isVertical:!0,category:["lightIndustrial","residential","office","parking"]}}},drive:{name:"Drive",isHidden:!0,spaceUsage:{parkingSpot:{name:"Parking spot",category:["parking"]},driveway:{name:"Driveway",category:["parking"]},garage:{name:"Garage",category:["residential"]}}},produce:{name:"Produce",isHidden:!0,spaceUsage:{productionArea:{name:"Production area",category:["lightIndustrial"]}}},void:{isHidden:!0,name:"Void",spaceUsage:{shaft:{name:"Shaft",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},buildingOpening:{name:"Building opening",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},floorOpening:{name:"Floor opening",isVertical:!0,category:["lightIndustrial","residential","office","parking"]}}},undefined:{isHidden:!0,spaceUsage:{undefined:{name:"Undefined",category:["residential","office"],isHidden:!0}}}},hl={};function ul(t,e,i){let s=ft(...t),r=ft(...e),n=ft(...i),o=dt(),a=dt(),l=dt();return yt(o,s,n),yt(a,r,n),xt(l,o,a),vt(l,l),[...l]}function cl(t){let{indices:e,vertices:i}=t,s=[],r=[],n=[],o=as(i);for(let u=0;u<i.length;u+=3){let t=i[u],e=i[u+1],n=i[u+2];s.push([t,e,n]),r.push([t,n])}for(let u=0;u<e.length;u+=3){let t=e[u],i=e[u+1],o=e[u+2];ul(s[t],s[i],s[o])[1]<.01||n.push([r[t],r[i],r[o]])}let a=[],l=[[]];if(!n.length)return{outlines:a,holes:l,boundingBox:o};let h=Q(Y(n),.0015);h=h.filter(t=>t&&t.length&&K(t)>5e-4);for(let u of h)Ei(u)?l[0].push(u):a.push(u);return{outlines:a,holes:l,boundingBox:o}}function dl(t,e={}){let i=function(t,e=nt(),i=/* @__PURE__ */new Map,s=!0){let r=[],n=t.spaceGraph;if("geometries"in t&&t.geometries)for(let o of t.geometries){let t,a,l,h;if("string"==typeof o){if(t=n.geometriesById[o],!t){ve.warn(`Geometry ${o} not found.`);continue}a=[0,0,0],l=0,h=[0,1,0]}else{if("reference:geometry"!==o.type){ve.warn(`Operation ${o.type} not supported.`);continue}let e=o.geometry;if("string"==typeof e){if(t=n.geometriesById[e],!t){ve.warn(`Geometry ${e} not found.`);continue}}else t=e;a=o.position??[0,0,0],l=o.rotation??0,h=o.rotationAxis??[0,1,0]}let u=je(a,l);for(let o of u){let a=Ti(o.position,o.rotation,h);s&&(a=ht(nt(),e,a));let l=[];if("geometry:uri"===t.type&&"data3d"===t.format){let e=i.get(t.uri),s=(null==e?void 0:e.meshGeometries)||{};for(let t in s){let e=s[t];l.push(...os(e,n.geometriesById,n.materialsById,[]))}}else l=os(t,n.geometriesById,n.materialsById,[]);let u=_t(),c=dt();ct(u,a),ut(c,a);for(let t of l)Ii(t.vertices,a);r.push({meshes:l,rotation:u,position:c})}}return r}(t,e.applyElementMatrix?gr(t,e.parentMatrix):void 0,e.resources),s=[];for(let r of i)for(let t of r.meshes)s.push(cl(t));return s}Object.keys(ll).forEach(t=>{const e=ll[t];hl[t]={name:e.name,type:"program",category:[]},e.isHidden&&(hl[t].isHidden=e.isHidden);const i={};Object.keys(ll[t].spaceUsage).forEach(e=>{const s=ll[t].spaceUsage[e];hl[e]={...s,type:"space",program:t},s.category.forEach(t=>{i[t]=!0})}),hl[t].category=Object.keys(i)}),new al({size:256});const pl=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function fl(t){return"string"==typeof t&&pl.test(t)}const ml={programs:{care:[{name:"bathroom",tags:[],categories:["residential"]},{name:"kitchen",tags:[],categories:["residential"]},{name:"restroom",tags:[],categories:["lightIndustrial","office","parking","laboratory"]},{name:"shower",tags:[],categories:["lightIndustrial","office","residential","laboratory"]},{name:"toilet",tags:[],categories:["residential"]},{name:"wellnessRoom",tags:[],categories:["lightIndustrial","office","laboratory"]}],circulate:[{name:"corridor",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"elevator",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"foyer",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"staircase",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]}],drive:[{name:"driveway",tags:[],categories:["parking"]},{name:"garage",tags:[],categories:["residential"]},{name:"parkingSpot",tags:[],categories:["parking"]}],live:[{name:"bedroom",tags:[],categories:["residential"]},{name:"dining",tags:[],categories:["residential"]},{name:"dining_living",tags:[],categories:["residential"]},{name:"homeOffice",tags:[],categories:["residential"]},{name:"living",tags:[],categories:["residential"]}],meet:[{name:"assembly",tags:[],categories:["office"]},{name:"boardRoom",tags:[],categories:["office"]},{name:"hub",tags:[],categories:["office"]},{name:"meetingRoom",tags:[],categories:["office"]},{name:"trainingRoom",tags:[],categories:["office"]}],none:[{name:"generic",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]}],produce:[{name:"productionArea",tags:[],categories:["lightIndustrial"]}],research:[{name:"lab",tags:[],categories:["lightIndustrial","laboratory"]}],socialize:[{name:"balcony",tags:["outdoor"],categories:["office","residential"]},{name:"cafe",tags:[],categories:["office","laboratory"]},{name:"canteen",tags:[],categories:["office"]},{name:"courtyard",tags:["outdoor"],categories:["office","residential"]},{name:"garden",tags:["outdoor"],categories:["residential"]},{name:"lobby",tags:[],categories:["office","residential","laboratory"]},{name:"lounge",tags:[],categories:["office","laboratory"]},{name:"pantry",tags:[],categories:["office"]},{name:"reception",tags:[],categories:["office","laboratory"]},{name:"rooftop",tags:["outdoor"],categories:["office","residential"]},{name:"terrace",tags:["outdoor"],categories:["office","residential"]}],support:[{name:"chemicalStore",tags:[],categories:["laboratory"]},{name:"cleanRoom",tags:[],categories:["laboratory"]},{name:"coldRoom",tags:[],categories:["laboratory"]},{name:"laundryRoom",tags:[],categories:["residential"]},{name:"loadingDock",tags:[],categories:["lightIndustrial"]},{name:"mailRoom",tags:[],categories:["office"]},{name:"operationalRoom",tags:[],categories:["lightIndustrial","office","parking","laboratory"]},{name:"printStation",tags:[],categories:["office"]},{name:"serviceKitchen",tags:[],categories:["office"]},{name:"serviceRoom",tags:[],categories:["office"]},{name:"storage",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]}],void:[{name:"buildingOpening",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"floorOpening",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"shaft",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]}],work:[{name:"enclosedWorkspace",tags:[],categories:["office"]},{name:"focusRoom",tags:[],categories:["office"]},{name:"openWorkspace",tags:[],categories:["office"]},{name:"privateOffice",tags:[],categories:["office"]}]}},gl="#ffffff",yl="#0c1829",vl="#4d586b",xl="#929baa",bl="#72849e",wl="#f1f2f3",_l="#cfd5de",Pl="#e8ebef",El="#f7f8fa",Tl="#3355ff",Al="#dfecff",Il="#ab220a",Sl={api:{productDataCacheAge:864e5,productContourCacheAge:864e6},hideElements:[],panZoom:!0,preserveViewbox:"center-center",showCeilingLamps:!1,destroyOnDomRemove:!1,ui:{scale:!0,coordinates:!1},spaceLabelMapping:{},theme:{fontFamily:"Inter, Avenir, Verdana, sans-serif",background:{color:El,showGrid:!1},wallContours:!1,showAssetTextures:!1},units:{system:"metric",areaDecimals:0,lengthDecimals:3,roomDimensions:"area"},zoomRange:[3,300]};let Cl="archilogic/product",Ml="https://storage.archilogic.com";const Ol=({apiStorageUrl:t,spaceApiUrl:e,apiProductDataPath:i}={})=>{"string"==typeof t&&(Ml=t),"string"==typeof i&&(Cl=i),"string"==typeof e&&(R=e)};let Nl=new E(["info","warnings","errors"]);function Ll(t,e){let i,s=e.product.geometries[0];const r="product:component"===e.product?.type;if("string"==typeof s){let t=s;i=e.spaceGraph.geometriesById[t]}else"reference:geometry"===s?.type&&"string"!=typeof s.geometry&&(i=s.geometry);if(!r&&!("geometry:uri"===i?.type))return Promise.reject("Unsupported product geometry: "+e.product.id);const n=r?["productJson"]:["productJson","productContour"];return t.loadResources(e.product.id,e,n).catch(t=>Nl.error(t))}const Rl=t=>{const e=[];return t.layout.elementsByType["element:asset"].forEach(t=>{"product"in t&&"product:static"===t.product?.type&&e.push(t)}),Promise.allSettled(e.map(e=>Ll(t.loader,e)))};function Bl(t){return fetch(`${Ml}/${Cl}/outline/${t}.json`).then(t=>{if(t.ok)return t.json();throw Error(t.statusText)})}const kl="undefined"==typeof window||"undefined"!=typeof process;let Fl;try{Fl=!kl&&Ca("al-kvs","al-keyval")}catch(Hw){Nl.warn("indexedDb initialization failed")}async function Dl(t,e,i){if(!Fl)return Promise.resolve();i=i||2592e6;try{const s={timeStamp:/* @__PURE__ */(new Date).getTime(),content:e,maxAge:i};return await function(t,e,i=Oa()){return i("readwrite",i=>(i.put(e,t),Sa(i.transaction)))}(t,s,Fl),t}catch(s){return}}async function Ul(t,e){if(!Fl)return Promise.resolve();const i=e||2592e6,s=/* @__PURE__ */(new Date).getTime();let r;try{r=await function(t,e=Oa()){return e("readonly",e=>Sa(e.get(t)))}(t,Fl);const e=s-r.timeStamp;if(e>Math.min(r.maxAge,i))return;if(r.content)return r.content}catch(n){return}}const Gl="fpe-dc2-";var Xl=/* @__PURE__ */(t=>(t[t.None=0]="None",t[t.Default=1]="Default",t[t.Grayscale=2]="Grayscale",t))(Xl||{});class Wl extends ce.TinyEmitter{constructor(t){super(),this.promiseCache=/* @__PURE__ */new Map,this.loadStages={product:!0,productContour:!0,productTexture:!1},this.queue={productJson:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.resources={nodes:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.initialLoading=!0,this._requestCounter=0,this._loadCounter=0;const{settings:e}=t;this.floorPlan=t,this.productContourCacheAge=e.api?.productContourCacheAge,this.productDataCacheAge=e.api?.productDataCacheAge,this.loadStages.productTexture=!!e.theme?.showAssetTextures&&!1!==e.loadTextures,this.on("resource-loaded",this.loadStatus,this)}loadStatus(){const t=this._requestCounter;this._loadCounter++,this.emit("loading-status",{totalCount:t,doneCount:this._loadCounter}),t===this._loadCounter&&this.emit("loading-done",{totalCount:t})}loadResources(t,e,i){return Promise.all(i.map(i=>this.loadResource(t,e,i)))}loadResource(t,e,i){if(this.resources.nodes.has(t)||this.resources.nodes.set(t,/* @__PURE__ */new Set),this.resources.nodes.get(t).add(e),this.queue[i].has(t))return this.queue[i].get(t);let s;switch(this._requestCounter++,i){case"productJson":s=Yl(t,this,e.product);break;case"productContour":this.loadStages.productTexture&&this._requestCounter++,s=Hl(t,this).then(()=>{if(this.loadStages.productTexture&&!this.resources.texture.has(t)){if(!this.resources.productJson.has(t))return void Nl.warn("texture loading failed, no product info yet");const e=`${Ml}/${Cl}/thumb/${t}.png`;this.resources.texture.set(t,{textureUrl:e,applyFilter:1}),this.emit("product-load-texture",{resourceId:t})}})}return this.queue[i].set(t,s),s}reset(){this.resources={nodes:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.queue={productContour:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this._loadCounter=0,this._requestCounter=0,this.promiseCache=/* @__PURE__ */new Map,this.initialLoading=!0}}const Yl=(t,e,i)=>{const s=e.floorPlan.spaceGraph;t!==i?.id||s.productsById[t]||s.insertProduct(i);const r=JSON.parse(JSON.stringify(i?.attributes||{}));return Number.isFinite(r.boundingBox?.min[0])||(Nl.warn("invalid product bounding box"),delete r.boundingBox),e.resources.productJson.set(t,r),Promise.resolve().then(()=>{e.emit("resource-loaded",{resourceId:t})})},Hl=async(t,e)=>{const i=Gl+t,s=e.promiseCache.get(i);if(s)return s;const r=function(t,e){const i=e.productContourCacheAge,s=i||864e6;if(!t)return Promise.reject("product id missing");const r=Gl+t,n=e.promiseCache.get(r);if(n)return n;const o=Ul(r,i).then(e=>e||Bl(t).then(t=>(Dl(r,t,s),t))).catch(t=>{Nl.warn(t)});return e.promiseCache.set(r,o),o}(t,e).then(i=>{const s=i,r=e.resources.productJson.get(t);if(!r.boundingBox){Nl.warn("product boundingbox missing - creating from contour");let t=W(s);r.boundingBox={min:[t.min[0],0,t.min[1]],max:[t.max[0],0,t.max[1]]}}e.resources.productContour.set(t,s),e.emit("resource-loaded",{resourceId:t})}).catch(()=>{});return e.promiseCache.set(i,r),r};function $l(t){return t.max.map((e,i)=>e-t.min[i])}function jl(t,e=[0,0]){const{dimensions:i}=t.parameters,s=t.parent;let r=[];if("element:wall"===s?.type){let t=s.parameters.width;r=[[-e[0],-e[1]],[i[0]+e[0],-e[1]],[i[0]+e[0],t+e[1]],[-e[0],t+e[1]]]}return[{type:"curve:polygon",points:r}]}function zl(t,e){const i=t.elements[0]||t,s=e?.[i?.type];return void 0===s||("boolean"==typeof s?s:i.isExternal?s.external:s.internal)}function Vl(t,e={clip:{"element:door":!0,"element:window":!0}}){const i=.01,s=t.elementsByType["element:wall"],r=t.elementsByType["element:boundaryWall"],n=t.elementsByType["element:column"],o=t.elementsByType["element:opening"],a=[];for(const c of o){if(!zl(c,e.clip))continue;const t=jl(c,[0,i]),{position:s,rotation:r}=c,n={position:[s[0],s[2]],rotation:r},o=Mi(t[0].points,n);a.push([o])}const l=[];for(const c of s){let{points:t}=c.geometryProfile;t=$([t],i)[0],l.push([t])}for(const c of n){const{profile:t}=c.parameters;let{points:e}=ss(t);if("curve:rectangle"===t.type){const[i,s]=t.dimensions;e=[[-i/2,-s/2],[i/2,-s/2],[i/2,s/2],[-i/2,s/2]]}e=Mi(e,{position:[c.position[0],c.position[2]],rotation:c.rotation}),e=$([e],i)[0],l.push([e])}for(const c of r){let t=c.boundaries[0].geometryProfile;t=$([t],i)[0],l.push([t])}let{polygons:h}=function(t){if(!t.length||!t[0])return{polygons:[],polyTree:[]};let e=et(t[0]),i=[];for(let n=1;n<t.length;n++)i.push(...et(t[n]));let s=new X.Clipper;s.AddPaths(e,X.PolyType.ptSubject,!0),s.AddPaths(i,X.PolyType.ptClip,!0);let r=new X.PolyTree;return s.Execute(X.ClipType.ctUnion,r,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),H(r)}(l);h=j(h,-.01).polygons,a.length&&(h=V(h,a).polygons);const u=[];for(const c of h){const t=[];for(const e of c){let i=tt(e,.001);i.length&&t.push(i)}t.length&&u.push(t)}return u}const ql=class t{constructor({options:t={}}={}){this.settings=y(Sl),this.fpeId="fpe-"+Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,3),this.computed={wallContours:[],snapPoints:[],snapMargin:0},this.isBrowser="object"!=typeof process&&"undefined"!=typeof window,this.location={latitude:0,longitude:0,bearing:0},this._emitter=new ce.TinyEmitter,ve.setLevels("errors"),this.set(t),this.loader=new Wl(this)}on(t,e,i){return this._emitter.on(t,e,i),this}once(t,e,i){return this._emitter.once(t,e,i),this}off(t,e){return this._emitter.off(t,e),this}emit(t,...e){return this._emitter.emit(t,...e),this}loadLayout(t,{skipGeometryCompute:e=!1}={}){this.loadSpaceGraph(t.spaceGraph,{skipGeometryCompute:e,layoutId:t.id})}loadSpaceGraph(t,{skipGeometryCompute:e=!1,layoutId:i}={}){if(this.loader.initialLoading||this.loader.reset(),this.spaceGraph=t,this.layout=i?t.nodesById[i]:t.nodesByType["spatialStructure:layout"][0],"spatialStructure:building"===this.spaceGraph.spatialStructure.type?(this.building=this.spaceGraph.spatialStructure,this.settings.loadFloorLevel||(this.settings.loadFloorLevel=this.building.getLevelOrder()[0])):this.building=null,this.layout&&"spatialStructure:layout"===this.layout.type){if(!e)for(const e of t.nodesByType["spatialStructure:layout"])Ia(e),kr(e);this.settings.theme.wallContours&&(this.computed.wallContours=Vl(this.layout)),setTimeout(()=>{this.updateThemeFilter(),this.loader.emit("spaces-loaded")},0),Rl(this).then(()=>{const t=this.settings.hideElements.includes("element:asset"),e=0===Object.keys(this.spaceGraph.products).length;this.updateThemeFilter(),this.loader.emit("assets-loaded",!0),(t||e)&&this.loader.emit("loading-done",{totalCount:0})}).catch(t=>Nl.warn(t)),this.loader.initialLoading=!1}else Nl.warn("No layout to load")}loadSpaceGraphJson(t){this.loadSpaceGraph(So.fromJSON(t))}async loadFloorById(e,i=this.settings.api){return new Promise(async(r,n)=>{e&&"string"==typeof e||n(`Expected non-empty string floorId parameter; instead got: "${e}"`);try{const n=B({...i,sdkVersion:t.version}),a=new U(n);this.loader.once("assets-loaded",r);const l=await a.getFloorById(e,!1,!1,!0),h=l.properties?.address;if(o=h?.latitude,s(o,90)&&(this.location.latitude=h.latitude),function(t){return s(t,180)}(h?.longitude)&&(this.location.longitude=h.longitude),function(t){return s(t,180)}(h?.bearing)&&(this.location.bearing=h.bearing),!l.layout?.layout)throw new Error(`The floor ${e} has no space graph layout`);this.emit("space-api-floor-loaded",e),this.loadSpaceGraphJson(l.layout.layout)}catch(Hw){n(Hw)}var o}).catch(t=>{throw this.emit("space-api-floor-error",e,t),t})}async loadLayoutById(e,i=this.settings.api){return new Promise(async(s,r)=>{e&&"string"==typeof e||r(`Expected non-empty string layoutId parameter; instead got: "${e}"`);try{const r=B({...i,sdkVersion:t.version}),n=new U(r);this.loader.once("assets-loaded",s);const o=await n.getLayout(e);if(!o?.layout)throw new Error(`Loading layout ${e} failed`);this.emit("space-api-floor-loaded",e),this.loadSpaceGraphJson(o.layout)}catch(Hw){r(Hw)}}).catch(t=>{throw this.emit("space-api-floor-error",e,t),t})}set(t={}){const e=this.settings.hideElements?.includes("element:asset");let i=y(t);("roomStampSize"in i||i.theme&&"elements"in i.theme)&&(i.theme=(t=>{const e=t.theme||{};if(!e?.elements&&void 0===t.roomStampSize)return e;const i={};for(const s of Object.keys(e))"elements"!==s&&(i[s]=e[s]);if(e?.elements)for(const s of Object.keys(e.elements))if("roomStamp"===s)i.roomStamps=e.elements[s];else if("layout:space"===s){const t=y(e.elements[s]);if(delete t.program,delete t.usage,i.byType??={},i.byType[s]=t,e.elements[s]?.program){i.byFilter??=[];for(const t of Object.keys(e.elements[s].program)){const r=e.elements[s].program[t];i.byFilter.push({where:{type:"layout:space",category:t},style:r})}}if(e.elements[s]?.usage){i.byFilter??=[];for(const t of Object.keys(e.elements[s].usage)){const r=e.elements[s].usage[t];i.byFilter.push({where:{type:"layout:space",subCategory:t},style:r})}}}else"byId"===s?i.byId=e.elements[s]:"floorPlan"===s?(i.byType??={},i.byType["annotation:floorPlanImage"]=e.elements[s]):(i.byType??={},i.byType[s]=e.elements[s]);return t.roomStampSize&&(i.roomStamps??={},i.roomStamps.fontSize=t.roomStampSize),i})(i)),i.theme&&(i.theme=v(Sl.theme,i.theme)),i.ui&&(i.ui={...Sl.ui,...i.ui}),i.api&&(i.api={...Sl.api,...i.api}),i.units&&(i.units={...Sl.units,...i.units});const s=!i.hideElements?.includes("element:asset");for(let r in i)this.settings[r]=i[r];this.layout&&(e&&s&&Rl(this),i.theme?.wallContours&&!this.computed.wallContours?.length?this.computed.wallContours=Vl(this.layout):!i.theme?.wallContours&&this.computed.wallContours?.length&&(this.computed.wallContours=[])),this.updateThemeFilter(),this.emit("update-settings",this.settings)}updateThemeFilter(){this.settings?.theme?.byResolvedFilter&&(this.settings.theme.byResolvedFilter={}),this.layout&&this.settings?.theme?.byFilter&&(this.settings.theme.byResolvedFilter=function(t,e=[]){const i={};for(const s of e){const e={id:!0},r=t.getElements({select:e,where:s.where});r.push(...t.getSpaces({select:e,where:s.where}));for(const t of r)"style"in s&&(i[t.id]=s.style)}return i}(this,this.settings.theme.byFilter))}getBoundingBox(t=0){let e={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]};if(this.building&&this.settings.loadFloorLevel){const t=this.building.floorsByLevel[this.settings.loadFloorLevel]||[];for(const i of t){const{position:t,rotation:s}=i,r=i.layouts[0];if(!r)continue;const n=ls({...r.getBoundingBox(),transform:{position:t,rotation:s,rotationAxis:[0,1,0]}});for(let i=0;i<e.min.length;i++)e.min[i]=Math.min(e.min[i],n.min[i]),e.max[i]=Math.max(e.max[i],n.max[i])}}else e=this.layout.getBoundingBox();const[i,,s]=e.min,[r,,n]=e.max;return{min:[i-t,s-t],max:[r+t,n+t]}}getElements(t={}){return this.layout?function(t,e){const{items:i,args:s}=za(t.getElementList(),t,e);return $a(i,s)}(this.layout,t):[]}getElementsById(t){return this.layout?function(t,e){const i=t.elementsById[e.id];return(i?$a([i],e):[])[0]||null}(this.layout,t):null}getSpaces(t={}){return this.layout?function(t,e){const{items:i,args:s}=za(t.spaces,t,e);return $a(i,s)}(this.layout,t):[]}getSpacesById(t){return this.layout?function(t,e){const i=t.spacesById[e.id];return(i?$a([i],e):[])[0]||null}(this.layout,t):null}getResourcesFromPosition(t){const e=this.layout?.spaces?.filter(e=>xi(t,e.geometry.polygons))||[],i=[];return e.forEach(e=>{const s=e.getElements("element:asset").filter(e=>{if(e.product.attributes.subCategories.includes("ceilingLight")&&!this.settings.showCeilingLamps)return;const i=e.getBoundingBoxContour();return i?.length?q(t,i):void 0});i.push(...s)}),{spaces:e,assets:i}}destroy(){delete this.layout,delete this.settings}};ql.version="5.4.0";let Jl=ql;function Kl(t){let{length:e,hingeSide:i,doorSide:s,doorAngle:r,doorType:n,frameThickness:o,frameDepth:a}=t.parameters,l=[],h="right"===i,u="side1"===s,c=u?0:a,d=!1,p=0,f=0;if(r<5&&r>-5){r=20;const t=r/180*Math.PI;p=Math.sin(t),f=Math.cos(t),d=!0}if("singleSwing"===n){let t,i,s,n,a=e-2*o;u?h?(t=0,i=r,s=[o,c],n=[s[0]+f*a,s[1]-p*a]):(t=180-r,i=180,s=[e-o,c],n=[s[0]-f*a,s[1]-p*a]):h?(t=-180,i=-180+r,s=[e-o,c],n=[s[0]-f*a,s[1]+p*a]):(t=360-r,i=360,s=[o,c],n=[s[0]+f*a,s[1]+p*a]),l.push({type:"curve:arc",radius:a,position:s,startAngle:t,endAngle:i}),d&&l.push({type:"curve:line",start:s,end:n})}else if("doubleSwing"===n){let t,i,s,n,a,h,m,g,y=e/2-o;u?(t=0,i=r,s=[o,c],m=[e-o,c],a=180-r,h=180,n=[s[0]+f*y,s[1]-p*y],g=[m[0]-f*y,m[1]-p*y]):(t=360-r,i=360,s=[o,c],m=[e-o,c],a=180,h=180+r,n=[s[0]+f*y,s[1]+p*y],g=[m[0]-f*y,m[1]+p*y]),l.push({type:"curve:arc",radius:y,position:s,startAngle:t,endAngle:i}),l.push({type:"curve:arc",radius:y,position:m,startAngle:a,endAngle:h}),d&&(l.push({type:"curve:line",start:s,end:n}),l.push({type:"curve:line",start:m,end:g}))}return l}function Zl(t){let e=[];switch(t.type){case"element:door":e=Kl(t);break;case"element:stairFlight":e=function(t){let e=t.parent?.elements.find(t=>"element:stairFlight"===t.type);if(e?.id!==t.id||"spiral"===t.parameters.stairFlightType)return[];let{width:i,length:s,height:r}=t.parameters,n=s/Math.round(r/.17);return[{type:"curve:polyline",points:[[n/2-.06,i/2+.12],[n/2+.06,i/2],[n/2-.06,i/2-.12]]}]}(t)}return e}function Ql(t){for(const e of Object.keys(ml.programs)){if(ml.programs[e].find(e=>e.name===t))return e}return""}function th(t,e=0){return({"element:door":45,"element:window":45,"element:opening":40,"element:spaceDivider":35,"spatialGraph:edge":35,"element:column":30,"element:wall":30,"element:boundaryWall":30,"element:casework":20,"element:kitchen":20,"element:railing":20,"element:generic":11,"element:asset":10,"element:stairs":5,"element:stairFlight":5,"element:slab":5,"layout:space":1,"annotation:floorPlanDxf":0,"annotation:floorPlanImage":0}[t]||0)+e}function eh(t){if("number"==typeof t)return t;if(Array.isArray(t)||"string"==typeof t&&t.startsWith("#")){const[e,i,s]=function(t){if(Array.isArray(t))return[t[0],t[1],t[2]];if("number"==typeof t)return[t>>16&255,t>>8&255,255&t];if("string"==typeof t&&t.startsWith("#")){const e=t.slice(1);if(3===e.length)return[parseInt(e[0]+e[0],16),parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16)];if(6===e.length)return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}return[0,0,0]}(t);return(e<<16)+(i<<8)+s}}const ih={default:{fill:gl,stroke:xl,strokeWidth:"native",fillOpacity:1},selected:{fill:Al,stroke:xl,strokeWidth:1}};const sh=({settings:t,nodeId:e,parentId:i,nodeType:s})=>{const r=t?.theme;if(!r)return{};return(t=>{const{fill:e,fillOpacity:i,stroke:s,strokeWidth:r,strokeOpacity:n}=t,o={};return e&&(o.fill=eh(e)),s&&(o.stroke=eh(s)),"number"==typeof i&&Number.isFinite(i)&&(o.fillOpacity=Math.max(Math.min(i,1),0)),"number"==typeof n&&Number.isFinite(n)&&(o.strokeOpacity=Math.max(Math.min(n,1),0)),"string"==typeof r?"native"===r&&(o.strokeWidth=r):Number.isFinite(r)&&r>=0&&(o.strokeWidth=r),o})(r.byId?.[e]||r.byResolvedFilter?.[e]||r.byId?.[i]||r.byResolvedFilter?.[i]||r.byType?.[s]||null||{})},rh=t=>{if(t?.layout?.debugIds){let i=/\d+/.exec(t.id)?.[0]||"0",s=(e=parseInt(i),function(){let t=e+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296});return{fill:Math.round(5*s()*16777215)%16777215,fillOpacity:.5}}var e;return{}},nh=({style:t,settings:e,element:i,elementType:s})=>{const r="selected"===t?"selected":"default",n=function({element:t,settings:e,elementType:i,state:s="default"}){const r=e?.theme?.showAssetTextures,n={"element:wall":{default:{fill:vl,stroke:vl},selected:{fill:bl,stroke:Tl,strokeWidth:"native"}},"element:boundaryWall":{default:{fill:vl,stroke:yl},selected:{fill:bl,stroke:Tl}},"element:curtainWall":{default:{fill:wl},selected:{strokeWidth:"native"}},"element:column":{default:{fill:vl,stroke:vl},selected:{fill:bl,stroke:Tl,strokeWidth:"native"}},"element:asset":{default:{fill:r?null:wl},selected:{fill:Al,stroke:Tl,strokeWidth:.5,alignment:0}},"element:stairs":{default:{fill:El},selected:{strokeWidth:"native"}},"element:stairFlight":{default:{fill:El}},"element:slab":{default:{fill:El}},"layout:space":(()=>{const e={default:{fill:gl,stroke:_l},selected:{fill:Al,stroke:_l,strokeWidth:"native"}};if(t&&"layout:space"===t.type){const i="kitchen"!==t.attributes.usage&&Ql(t.attributes.usage),s={care:_l,circulate:El};i&&s[i]&&(e.default.fill=s[i]),"void"===i&&(e.default.fillOpacity=.05)}return e})(),"spatialGraph:edge":{default:{fill:_l,stroke:yl,strokeOpacity:.8,strokeWidth:.5},selected:{stroke:Tl,strokeWidth:.5}},"element:spaceDivider":{default:{fill:_l,stroke:yl,strokeOpacity:.8,strokeWidth:.5},selected:{stroke:Tl,strokeWidth:.5}}}[i]||ih,o=t&&"parent"in t?t.parent?.id:void 0,a=sh({settings:e,nodeId:t?.id,parentId:o,nodeType:i});return"selected"===s?{...ih.default,...n.default,...a,...ih.selected,...n.selected}:{...ih.default,...n.default,...a}}({element:i,elementType:s||i?.type,settings:e,state:r});return{...n,...t?{}:rh(i),..."object"==typeof t?t:{}}};function oh(t,e,i=.5){let s=[e[0]-t[0],e[1]-t[1]];return[t[0]+s[0]*i,t[1]+s[1]*i]}function ah(t,e,i,s=5){const r=[];let n,o,a,l=0;for(let h=0;h<=s;++h)l=h/s,n=oh(t,e,l),o=oh(e,i,l),a=oh(n,o,l),r.push(a);return r}const lh=(t,e)=>{const i=Math.ceil(48/(2*Math.PI)*t*e),s=Math.ceil(12/(2*Math.PI)*t);return Math.min(100,Math.max(s,i))},hh=t=>{const e={type:"curve:polyline",points:[],style:t.style};switch(t.type){case"curve:line":e.points=[t.start,t.end];break;case"curve:arc":const i=t.startAngle/180*Math.PI,s=t.endAngle/180*Math.PI-i,r=t.radius,n=lh(Math.abs(s),r),o=t.position,a=s/n;let l=i;for(let t=0;t<n+1;t++)e.points.push([r*Math.cos(l)+o[0],-r*Math.sin(l)+o[1]]),l+=a;break;case"curve:polyline":e.points=t.points;break;case"curve:quadraticBezier":e.points.push(t.points[0]);for(let h=0;h<=t.points.length-3;h++){let i=t.points[h],s=t.points[h+1],r=t.points[h+2],n=ah(0===h?i:oh(i,s),s,h===t.points.length-3?r:oh(s,r));e.points.push(...n.slice(1))}}return e},uh=(t,e,i=.15)=>{let s,r,n;for(const o of e)if(s=Math.abs(t[0]-o[0]),!(s>i)&&(r=Math.abs(t[1]-o[1]),s<i&&r<i)){n=o;break}return n};function ch(t){const e={10:["ceilingLight","wallLight"],9:["modularMeetingRoom","phoneBooth"],8:["floorLamp","tableLamp","deskDivider","cushion","plant","officeSupply","tableware","decoration","laundry","electronics","kitchen","car"],7:["shelf","cabinet","wardrobe","storageCombination","outdoor","bicycle","people","sink"],6:["highTable","diningTable","conferenceTable","desk"],5:["sofa","armchair","loungeChair","ottoman","sideboard","pedestal"],4:["taskChair","diningChair","conferenceChair","stool","barStool","bench"],3:["shower"],2:["singleBed","doubleBed","daybed","toilet","bathtub"],1:["sideTable","coffeeTable","radiator","nightstand"],0:["rug"]};let i=0;return t.subCategories.forEach(t=>{Object.keys(e).forEach(s=>{let r=parseInt(s);e[s].includes(t)&&r>i&&(i=r)})}),1===i&&t.categories.includes("tables")&&t.boundingBox.max[1]-t.boundingBox.min[1]>.6&&(i=6),i}var dh=/* @__PURE__ */(t=>(t[t.WEBGL_LEGACY=0]="WEBGL_LEGACY",t[t.WEBGL=1]="WEBGL",t[t.WEBGL2=2]="WEBGL2",t))(dh||{}),ph=/* @__PURE__ */(t=>(t[t.UNKNOWN=0]="UNKNOWN",t[t.WEBGL=1]="WEBGL",t[t.CANVAS=2]="CANVAS",t))(ph||{}),fh=/* @__PURE__ */(t=>(t[t.COLOR=16384]="COLOR",t[t.DEPTH=256]="DEPTH",t[t.STENCIL=1024]="STENCIL",t))(fh||{}),mh=/* @__PURE__ */(t=>(t[t.NORMAL=0]="NORMAL",t[t.ADD=1]="ADD",t[t.MULTIPLY=2]="MULTIPLY",t[t.SCREEN=3]="SCREEN",t[t.OVERLAY=4]="OVERLAY",t[t.DARKEN=5]="DARKEN",t[t.LIGHTEN=6]="LIGHTEN",t[t.COLOR_DODGE=7]="COLOR_DODGE",t[t.COLOR_BURN=8]="COLOR_BURN",t[t.HARD_LIGHT=9]="HARD_LIGHT",t[t.SOFT_LIGHT=10]="SOFT_LIGHT",t[t.DIFFERENCE=11]="DIFFERENCE",t[t.EXCLUSION=12]="EXCLUSION",t[t.HUE=13]="HUE",t[t.SATURATION=14]="SATURATION",t[t.COLOR=15]="COLOR",t[t.LUMINOSITY=16]="LUMINOSITY",t[t.NORMAL_NPM=17]="NORMAL_NPM",t[t.ADD_NPM=18]="ADD_NPM",t[t.SCREEN_NPM=19]="SCREEN_NPM",t[t.NONE=20]="NONE",t[t.SRC_OVER=0]="SRC_OVER",t[t.SRC_IN=21]="SRC_IN",t[t.SRC_OUT=22]="SRC_OUT",t[t.SRC_ATOP=23]="SRC_ATOP",t[t.DST_OVER=24]="DST_OVER",t[t.DST_IN=25]="DST_IN",t[t.DST_OUT=26]="DST_OUT",t[t.DST_ATOP=27]="DST_ATOP",t[t.ERASE=26]="ERASE",t[t.SUBTRACT=28]="SUBTRACT",t[t.XOR=29]="XOR",t))(mh||{}),gh=/* @__PURE__ */(t=>(t[t.POINTS=0]="POINTS",t[t.LINES=1]="LINES",t[t.LINE_LOOP=2]="LINE_LOOP",t[t.LINE_STRIP=3]="LINE_STRIP",t[t.TRIANGLES=4]="TRIANGLES",t[t.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",t[t.TRIANGLE_FAN=6]="TRIANGLE_FAN",t))(gh||{}),yh=/* @__PURE__ */(t=>(t[t.RGBA=6408]="RGBA",t[t.RGB=6407]="RGB",t[t.RG=33319]="RG",t[t.RED=6403]="RED",t[t.RGBA_INTEGER=36249]="RGBA_INTEGER",t[t.RGB_INTEGER=36248]="RGB_INTEGER",t[t.RG_INTEGER=33320]="RG_INTEGER",t[t.RED_INTEGER=36244]="RED_INTEGER",t[t.ALPHA=6406]="ALPHA",t[t.LUMINANCE=6409]="LUMINANCE",t[t.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",t[t.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",t[t.DEPTH_STENCIL=34041]="DEPTH_STENCIL",t))(yh||{}),vh=/* @__PURE__ */(t=>(t[t.TEXTURE_2D=3553]="TEXTURE_2D",t[t.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",t[t.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",t[t.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",t[t.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",t[t.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",t[t.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",t))(vh||{}),xh=/* @__PURE__ */(t=>(t[t.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",t[t.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",t[t.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",t[t.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",t[t.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",t[t.UNSIGNED_INT=5125]="UNSIGNED_INT",t[t.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",t[t.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",t[t.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",t[t.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",t[t.BYTE=5120]="BYTE",t[t.SHORT=5122]="SHORT",t[t.INT=5124]="INT",t[t.FLOAT=5126]="FLOAT",t[t.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",t[t.HALF_FLOAT=36193]="HALF_FLOAT",t))(xh||{}),bh=/* @__PURE__ */(t=>(t[t.FLOAT=0]="FLOAT",t[t.INT=1]="INT",t[t.UINT=2]="UINT",t))(bh||{}),wh=/* @__PURE__ */(t=>(t[t.NEAREST=0]="NEAREST",t[t.LINEAR=1]="LINEAR",t))(wh||{}),_h=/* @__PURE__ */(t=>(t[t.CLAMP=33071]="CLAMP",t[t.REPEAT=10497]="REPEAT",t[t.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",t))(_h||{}),Ph=/* @__PURE__ */(t=>(t[t.OFF=0]="OFF",t[t.POW2=1]="POW2",t[t.ON=2]="ON",t[t.ON_MANUAL=3]="ON_MANUAL",t))(Ph||{}),Eh=/* @__PURE__ */(t=>(t[t.NPM=0]="NPM",t[t.UNPACK=1]="UNPACK",t[t.PMA=2]="PMA",t[t.NO_PREMULTIPLIED_ALPHA=0]="NO_PREMULTIPLIED_ALPHA",t[t.PREMULTIPLY_ON_UPLOAD=1]="PREMULTIPLY_ON_UPLOAD",t[t.PREMULTIPLIED_ALPHA=2]="PREMULTIPLIED_ALPHA",t))(Eh||{}),Th=/* @__PURE__ */(t=>(t[t.NO=0]="NO",t[t.YES=1]="YES",t[t.AUTO=2]="AUTO",t[t.BLEND=0]="BLEND",t[t.CLEAR=1]="CLEAR",t[t.BLIT=2]="BLIT",t))(Th||{}),Ah=/* @__PURE__ */(t=>(t[t.AUTO=0]="AUTO",t[t.MANUAL=1]="MANUAL",t))(Ah||{}),Ih=/* @__PURE__ */(t=>(t.LOW="lowp",t.MEDIUM="mediump",t.HIGH="highp",t))(Ih||{}),Sh=/* @__PURE__ */(t=>(t[t.NONE=0]="NONE",t[t.SCISSOR=1]="SCISSOR",t[t.STENCIL=2]="STENCIL",t[t.SPRITE=3]="SPRITE",t[t.COLOR=4]="COLOR",t))(Sh||{}),Ch=/* @__PURE__ */(t=>(t[t.NONE=0]="NONE",t[t.LOW=2]="LOW",t[t.MEDIUM=4]="MEDIUM",t[t.HIGH=8]="HIGH",t))(Ch||{}),Mh=/* @__PURE__ */(t=>(t[t.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",t[t.ARRAY_BUFFER=34962]="ARRAY_BUFFER",t[t.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",t))(Mh||{});const Oh={ADAPTER:{createCanvas:(t,e)=>{const i=document.createElement("canvas");return i.width=t,i.height=e,i},getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(t,e)=>fetch(t,e),parseXML:t=>(new DOMParser).parseFromString(t,"text/xml")},RESOLUTION:1,CREATE_IMAGE_BITMAP:!1,ROUND_PIXELS:!1};var Nh=/iPhone/i,Lh=/iPod/i,Rh=/iPad/i,Bh=/\biOS-universal(?:.+)Mac\b/i,kh=/\bAndroid(?:.+)Mobile\b/i,Fh=/Android/i,Dh=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,Uh=/Silk/i,Gh=/Windows Phone/i,Xh=/\bWindows(?:.+)ARM\b/i,Wh=/BlackBerry/i,Yh=/BB10/i,Hh=/Opera Mini/i,$h=/\b(CriOS|Chrome)(?:.+)Mobile/i,jh=/Mobile(?:.+)Firefox\b/i,zh=function(t){return void 0!==t&&"MacIntel"===t.platform&&"number"==typeof t.maxTouchPoints&&t.maxTouchPoints>1&&"undefined"==typeof MSStream};function Vh(t){var e={userAgent:"",platform:"",maxTouchPoints:0};t||"undefined"==typeof navigator?"string"==typeof t?e.userAgent=t:t&&t.userAgent&&(e={userAgent:t.userAgent,platform:t.platform,maxTouchPoints:t.maxTouchPoints||0}):e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0};var i=e.userAgent,s=i.split("[FBAN");void 0!==s[1]&&(i=s[0]),void 0!==(s=i.split("Twitter"))[1]&&(i=s[0]);var r=function(t){return function(e){return e.test(t)}}(i),n={apple:{phone:r(Nh)&&!r(Gh),ipod:r(Lh),tablet:!r(Nh)&&(r(Rh)||zh(e))&&!r(Gh),universal:r(Bh),device:(r(Nh)||r(Lh)||r(Rh)||r(Bh)||zh(e))&&!r(Gh)},amazon:{phone:r(Dh),tablet:!r(Dh)&&r(Uh),device:r(Dh)||r(Uh)},android:{phone:!r(Gh)&&r(Dh)||!r(Gh)&&r(kh),tablet:!r(Gh)&&!r(Dh)&&!r(kh)&&(r(Uh)||r(Fh)),device:!r(Gh)&&(r(Dh)||r(Uh)||r(kh)||r(Fh))||r(/\bokhttp\b/i)},windows:{phone:r(Gh),tablet:r(Xh),device:r(Gh)||r(Xh)},other:{blackberry:r(Wh),blackberry10:r(Yh),opera:r(Hh),firefox:r(jh),chrome:r($h),device:r(Wh)||r(Yh)||r(Hh)||r(jh)||r($h)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const qh=(Vh.default??Vh)(globalThis.navigator);Oh.RETINA_PREFIX=/@([0-9\.]+)x/,Oh.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT=!1;var Jh,Kh={exports:{}};var Zh=(Jh||(Jh=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,o){if("function"!=typeof s)throw new TypeError("The listener must be a function");var a=new r(s,n||t,o),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],a]:t._events[l].push(a):(t._events[l]=a,t._eventsCount++),t}function o(t,e){0===--t._eventsCount?t._events=new s:delete t._events[e]}function a(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=/* @__PURE__ */Object.create(null),(new s).__proto__||(i=!1)),a.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},a.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,o=new Array(n);r<n;r++)o[r]=s[r].fn;return o},a.prototype.listenerCount=function(t){var e=i?i+t:t,s=this._events[e];return s?s.fn?1:s.length:0},a.prototype.emit=function(t,e,s,r,n,o){var a=i?i+t:t;if(!this._events[a])return!1;var l,h,u=this._events[a],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,s),!0;case 4:return u.fn.call(u.context,e,s,r),!0;case 5:return u.fn.call(u.context,e,s,r,n),!0;case 6:return u.fn.call(u.context,e,s,r,n,o),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];u.fn.apply(u.context,l)}else{var d,p=u.length;for(h=0;h<p;h++)switch(u[h].once&&this.removeListener(t,u[h].fn,void 0,!0),c){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,e);break;case 3:u[h].fn.call(u[h].context,e,s);break;case 4:u[h].fn.call(u[h].context,e,s,r);break;default:if(!l)for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];u[h].fn.apply(u[h].context,l)}}return!0},a.prototype.on=function(t,e,i){return n(this,t,e,i,!1)},a.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},a.prototype.removeListener=function(t,e,s,r){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return o(this,n),this;var a=this._events[n];if(a.fn)a.fn!==e||r&&!a.once||s&&a.context!==s||o(this,n);else{for(var l=0,h=[],u=a.length;l<u;l++)(a[l].fn!==e||r&&!a[l].once||s&&a[l].context!==s)&&h.push(a[l]);h.length?this._events[n]=1===h.length?h[0]:h:o(this,n)}return this},a.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&o(this,e)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,t.exports=a}(Kh)),Kh.exports);const Qh=/* @__PURE__ */It(Zh);var tu,eu,iu,su={},ru={exports:{}},nu=ru.exports;function ou(){return iu?eu:(iu=1,eu=TypeError)}const au=/* @__PURE__ */St(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var lu,hu,uu,cu,du,pu,fu,mu,gu,yu,vu,xu,bu,wu,_u,Pu,Eu,Tu,Au,Iu,Su,Cu,Mu,Ou,Nu,Lu,Ru,Bu,ku,Fu,Du,Uu,Gu,Xu,Wu,Yu,Hu,$u,ju,zu,Vu,qu,Ju,Ku,Zu,Qu,tc,ec,ic,sc,rc,nc,oc,ac,lc,hc,uc,cc,dc,pc,fc,mc,gc,yc,vc,xc,bc,wc,_c,Pc,Ec,Tc,Ac,Ic,Sc,Cc,Mc,Oc,Nc,Lc,Rc,Bc,kc,Fc,Dc,Uc,Gc,Xc,Wc;function Yc(){if(hu)return lu;hu=1;var t="function"==typeof Map&&Map.prototype,e=Object.getOwnPropertyDescriptor&&t?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,i=t&&e&&"function"==typeof e.get?e.get:null,s=t&&Map.prototype.forEach,r="function"==typeof Set&&Set.prototype,n=Object.getOwnPropertyDescriptor&&r?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,o=r&&n&&"function"==typeof n.get?n.get:null,a=r&&Set.prototype.forEach,l="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,h="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,u="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,c=Boolean.prototype.valueOf,d=Object.prototype.toString,p=Function.prototype.toString,f=String.prototype.match,m=String.prototype.slice,g=String.prototype.replace,y=String.prototype.toUpperCase,v=String.prototype.toLowerCase,x=RegExp.prototype.test,b=Array.prototype.concat,w=Array.prototype.join,_=Array.prototype.slice,P=Math.floor,E="function"==typeof BigInt?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,I="function"==typeof Symbol&&"object"==typeof Symbol.iterator,S="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===I||"symbol")?Symbol.toStringTag:null,C=Object.prototype.propertyIsEnumerable,M=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function O(t,e){if(t===1/0||t===-1/0||t!=t||t&&t>-1e3&&t<1e3||x.call(/e/,e))return e;var i=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof t){var s=t<0?-P(-t):P(t);if(s!==t){var r=String(s),n=m.call(e,r.length+1);return g.call(r,i,"$&_")+"."+g.call(g.call(n,/([0-9]{3})/g,"$&_"),/_$/,"")}}return g.call(e,i,"$&_")}var N=au,L=N.custom,R=W(L)?L:null,B={__proto__:null,double:'"',single:"'"},k={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function F(t,e,i){var s=i.quoteStyle||e,r=B[s];return r+t+r}function D(t){return g.call(String(t),/"/g,""")}function U(t){return!S||!("object"==typeof t&&(S in t||void 0!==t[S]))}function G(t){return"[object Array]"===$(t)&&U(t)}function X(t){return"[object RegExp]"===$(t)&&U(t)}function W(t){if(I)return t&&"object"==typeof t&&t instanceof Symbol;if("symbol"==typeof t)return!0;if(!t||"object"!=typeof t||!A)return!1;try{return A.call(t),!0}catch(e){}return!1}lu=function t(e,r,n,d){var y=r||{};if(H(y,"quoteStyle")&&!H(B,y.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(H(y,"maxStringLength")&&("number"==typeof y.maxStringLength?y.maxStringLength<0&&y.maxStringLength!==1/0:null!==y.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var x=!H(y,"customInspect")||y.customInspect;if("boolean"!=typeof x&&"symbol"!==x)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(H(y,"indent")&&null!==y.indent&&"\t"!==y.indent&&!(parseInt(y.indent,10)===y.indent&&y.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(H(y,"numericSeparator")&&"boolean"!=typeof y.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var P=y.numericSeparator;if(void 0===e)return"undefined";if(null===e)return"null";if("boolean"==typeof e)return e?"true":"false";if("string"==typeof e)return z(e,y);if("number"==typeof e){if(0===e)return 1/0/e>0?"0":"-0";var T=String(e);return P?O(e,T):T}if("bigint"==typeof e){var L=String(e)+"n";return P?O(e,L):L}var k=void 0===y.depth?5:y.depth;if(void 0===n&&(n=0),n>=k&&k>0&&"object"==typeof e)return G(e)?"[Array]":"[Object]";var Y=function(t,e){var i;if("\t"===t.indent)i="\t";else{if(!("number"==typeof t.indent&&t.indent>0))return null;i=w.call(Array(t.indent+1)," ")}return{base:i,prev:w.call(Array(e+1),i)}}(y,n);if(void 0===d)d=[];else if(j(d,e)>=0)return"[Circular]";function V(e,i,s){if(i&&(d=_.call(d)).push(i),s){var r={depth:y.depth};return H(y,"quoteStyle")&&(r.quoteStyle=y.quoteStyle),t(e,r,n+1,d)}return t(e,y,n+1,d)}if("function"==typeof e&&!X(e)){var tt=function(t){if(t.name)return t.name;var e=f.call(p.call(t),/^function\s*([\w$]+)/);if(e)return e[1];return null}(e),et=Q(e,V);return"[Function"+(tt?": "+tt:" (anonymous)")+"]"+(et.length>0?" { "+w.call(et,", ")+" }":"")}if(W(e)){var it=I?g.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):A.call(e);return"object"!=typeof e||I?it:q(it)}if(function(t){if(!t||"object"!=typeof t)return!1;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)return!0;return"string"==typeof t.nodeName&&"function"==typeof t.getAttribute}(e)){for(var st="<"+v.call(String(e.nodeName)),rt=e.attributes||[],nt=0;nt<rt.length;nt++)st+=" "+rt[nt].name+"="+F(D(rt[nt].value),"double",y);return st+=">",e.childNodes&&e.childNodes.length&&(st+="..."),st+="</"+v.call(String(e.nodeName))+">"}if(G(e)){if(0===e.length)return"[]";var ot=Q(e,V);return Y&&!function(t){for(var e=0;e<t.length;e++)if(j(t[e],"\n")>=0)return!1;return!0}(ot)?"["+Z(ot,Y)+"]":"[ "+w.call(ot,", ")+" ]"}if(function(t){return"[object Error]"===$(t)&&U(t)}(e)){var at=Q(e,V);return"cause"in Error.prototype||!("cause"in e)||C.call(e,"cause")?0===at.length?"["+String(e)+"]":"{ ["+String(e)+"] "+w.call(at,", ")+" }":"{ ["+String(e)+"] "+w.call(b.call("[cause]: "+V(e.cause),at),", ")+" }"}if("object"==typeof e&&x){if(R&&"function"==typeof e[R]&&N)return N(e,{depth:k-n});if("symbol"!==x&&"function"==typeof e.inspect)return e.inspect()}if(function(t){if(!i||!t||"object"!=typeof t)return!1;try{i.call(t);try{o.call(t)}catch(st){return!0}return t instanceof Map}catch(e){}return!1}(e)){var lt=[];return s&&s.call(e,function(t,i){lt.push(V(i,e,!0)+" => "+V(t,e))}),K("Map",i.call(e),lt,Y)}if(function(t){if(!o||!t||"object"!=typeof t)return!1;try{o.call(t);try{i.call(t)}catch(e){return!0}return t instanceof Set}catch(s){}return!1}(e)){var ht=[];return a&&a.call(e,function(t){ht.push(V(t,e))}),K("Set",o.call(e),ht,Y)}if(function(t){if(!l||!t||"object"!=typeof t)return!1;try{l.call(t,l);try{h.call(t,h)}catch(st){return!0}return t instanceof WeakMap}catch(e){}return!1}(e))return J("WeakMap");if(function(t){if(!h||!t||"object"!=typeof t)return!1;try{h.call(t,h);try{l.call(t,l)}catch(st){return!0}return t instanceof WeakSet}catch(e){}return!1}(e))return J("WeakSet");if(function(t){if(!u||!t||"object"!=typeof t)return!1;try{return u.call(t),!0}catch(e){}return!1}(e))return J("WeakRef");if(function(t){return"[object Number]"===$(t)&&U(t)}(e))return q(V(Number(e)));if(function(t){if(!t||"object"!=typeof t||!E)return!1;try{return E.call(t),!0}catch(e){}return!1}(e))return q(V(E.call(e)));if(function(t){return"[object Boolean]"===$(t)&&U(t)}(e))return q(c.call(e));if(function(t){return"[object String]"===$(t)&&U(t)}(e))return q(V(String(e)));if("undefined"!=typeof window&&e===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&e===globalThis||void 0!==At&&e===At)return"{ [object globalThis] }";if(!function(t){return"[object Date]"===$(t)&&U(t)}(e)&&!X(e)){var ut=Q(e,V),ct=M?M(e)===Object.prototype:e instanceof Object||e.constructor===Object,dt=e instanceof Object?"":"null prototype",pt=!ct&&S&&Object(e)===e&&S in e?m.call($(e),8,-1):dt?"Object":"",ft=(ct||"function"!=typeof e.constructor?"":e.constructor.name?e.constructor.name+" ":"")+(pt||dt?"["+w.call(b.call([],pt||[],dt||[]),": ")+"] ":"");return 0===ut.length?ft+"{}":Y?ft+"{"+Z(ut,Y)+"}":ft+"{ "+w.call(ut,", ")+" }"}return String(e)};var Y=Object.prototype.hasOwnProperty||function(t){return t in this};function H(t,e){return Y.call(t,e)}function $(t){return d.call(t)}function j(t,e){if(t.indexOf)return t.indexOf(e);for(var i=0,s=t.length;i<s;i++)if(t[i]===e)return i;return-1}function z(t,e){if(t.length>e.maxStringLength){var i=t.length-e.maxStringLength,s="... "+i+" more character"+(i>1?"s":"");return z(m.call(t,0,e.maxStringLength),e)+s}var r=k[e.quoteStyle||"single"];return r.lastIndex=0,F(g.call(g.call(t,r,"\\$1"),/[\x00-\x1f]/g,V),"single",e)}function V(t){var e=t.charCodeAt(0),i={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return i?"\\"+i:"\\x"+(e<16?"0":"")+y.call(e.toString(16))}function q(t){return"Object("+t+")"}function J(t){return t+" { ? }"}function K(t,e,i,s){return t+" ("+e+") {"+(s?Z(i,s):w.call(i,", "))+"}"}function Z(t,e){if(0===t.length)return"";var i="\n"+e.prev+e.base;return i+w.call(t,","+i)+"\n"+e.prev}function Q(t,e){var i=G(t),s=[];if(i){s.length=t.length;for(var r=0;r<t.length;r++)s[r]=H(t,r)?e(t[r],t):""}var n,o="function"==typeof T?T(t):[];if(I){n={};for(var a=0;a<o.length;a++)n["$"+o[a]]=o[a]}for(var l in t)H(t,l)&&(i&&String(Number(l))===l&&l<t.length||I&&n["$"+l]instanceof Symbol||(x.call(/[^\w$]/,l)?s.push(e(l,t)+": "+e(t[l],t)):s.push(l+": "+e(t[l],t))));if("function"==typeof T)for(var h=0;h<o.length;h++)C.call(t,o[h])&&s.push("["+e(o[h])+"]: "+e(t[o[h]],t));return s}return lu}function Hc(){if(cu)return uu;cu=1;var t=/* @__PURE__ */Yc(),e=/* @__PURE__ */ou(),i=function(t,e,i){for(var s,r=t;null!=(s=r.next);r=s)if(s.key===e)return r.next=s.next,i||(s.next=t.next,t.next=s),s};return uu=function(){var s,r={assert:function(i){if(!r.has(i))throw new e("Side channel does not contain "+t(i))},delete:function(t){var e=s&&s.next,r=function(t,e){if(t)return i(t,e,!0)}(s,t);return r&&e&&e===r&&(s=void 0),!!r},get:function(t){return function(t,e){if(t){var s=i(t,e);return s&&s.value}}(s,t)},has:function(t){return function(t,e){return!!t&&!!i(t,e)}(s,t)},set:function(t,e){s||(s={next:void 0}),function(t,e,s){var r=i(t,e);r?r.value=s:t.next={key:e,next:t.next,value:s}}(s,t,e)}};return r}}function $c(){return pu?du:(pu=1,du=Object)}function jc(){return mu?fu:(mu=1,fu=Error)}function zc(){return yu?gu:(yu=1,gu=EvalError)}function Vc(){return xu?vu:(xu=1,vu=RangeError)}function qc(){return wu?bu:(wu=1,bu=ReferenceError)}function Jc(){return Pu?_u:(Pu=1,_u=SyntaxError)}function Kc(){return Tu?Eu:(Tu=1,Eu=URIError)}function Zc(){return Iu?Au:(Iu=1,Au=Math.abs)}function Qc(){return Cu?Su:(Cu=1,Su=Math.floor)}function td(){return Ou?Mu:(Ou=1,Mu=Math.max)}function ed(){return Lu?Nu:(Lu=1,Nu=Math.min)}function id(){return Bu?Ru:(Bu=1,Ru=Math.pow)}function sd(){return Fu?ku:(Fu=1,ku=Math.round)}function rd(){return Uu?Du:(Uu=1,Du=Number.isNaN||function(t){return t!=t})}function nd(){if(Xu)return Gu;Xu=1;var t=/* @__PURE__ */rd();return Gu=function(e){return t(e)||0===e?e:e<0?-1:1}}function od(){return Yu?Wu:(Yu=1,Wu=Object.getOwnPropertyDescriptor)}function ad(){if($u)return Hu;$u=1;var t=/* @__PURE__ */od();if(t)try{t([],"length")}catch(e){t=null}return Hu=t}function ld(){if(zu)return ju;zu=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch(e){t=!1}return ju=t}function hd(){if(Ku)return Ju;Ku=1;var t="undefined"!=typeof Symbol&&Symbol,e=qu?Vu:(qu=1,Vu=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var t={},e=/* @__PURE__ */Symbol("test"),i=Object(e);if("string"==typeof e)return!1;if("[object Symbol]"!==Object.prototype.toString.call(e))return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;for(var s in t[e]=42,t)return!1;if("function"==typeof Object.keys&&0!==Object.keys(t).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(t).length)return!1;var r=Object.getOwnPropertySymbols(t);if(1!==r.length||r[0]!==e)return!1;if(!Object.prototype.propertyIsEnumerable.call(t,e))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var n=Object.getOwnPropertyDescriptor(t,e);if(42!==n.value||!0!==n.enumerable)return!1}return!0});return Ju=function(){return"function"==typeof t&&("function"==typeof Symbol&&("symbol"==typeof t("foo")&&("symbol"==typeof/* @__PURE__ */Symbol("bar")&&e())))}}function ud(){return Qu?Zu:(Qu=1,Zu="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function cd(){return ec?tc:(ec=1,tc=/* @__PURE__ */$c().getPrototypeOf||null)}function dd(){if(nc)return rc;nc=1;var t=function(){if(sc)return ic;sc=1;var t=Object.prototype.toString,e=Math.max,i=function(t,e){for(var i=[],s=0;s<t.length;s+=1)i[s]=t[s];for(var r=0;r<e.length;r+=1)i[r+t.length]=e[r];return i};return ic=function(s){var r=this;if("function"!=typeof r||"[object Function]"!==t.apply(r))throw new TypeError("Function.prototype.bind called on incompatible "+r);for(var n,o=function(t){for(var e=[],i=1,s=0;i<t.length;i+=1,s+=1)e[s]=t[i];return e}(arguments),a=e(0,r.length-o.length),l=[],h=0;h<a;h++)l[h]="$"+h;if(n=Function("binder","return function ("+function(t,e){for(var i="",s=0;s<t.length;s+=1)i+=t[s],s+1<t.length&&(i+=e);return i}(l,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof n){var t=r.apply(this,i(o,arguments));return Object(t)===t?t:this}return r.apply(s,i(o,arguments))}),r.prototype){var u=function(){};u.prototype=r.prototype,n.prototype=new u,u.prototype=null}return n},ic}();return rc=Function.prototype.bind||t}function pd(){return ac?oc:(ac=1,oc=Function.prototype.call)}function fd(){return hc?lc:(hc=1,lc=Function.prototype.apply)}function md(){if(pc)return dc;pc=1;var t=dd(),e=fd(),i=pd(),s=cc?uc:(cc=1,uc="undefined"!=typeof Reflect&&Reflect&&Reflect.apply);return dc=s||t.call(i,e)}function gd(){if(mc)return fc;mc=1;var t=dd(),e=/* @__PURE__ */ou(),i=pd(),s=md();return fc=function(r){if(r.length<1||"function"!=typeof r[0])throw new e("a function is required");return s(t,i,r)}}function yd(){if(yc)return gc;yc=1;var t,e=gd(),i=/* @__PURE__ */ad();try{t=[].__proto__===Array.prototype}catch(o){if(!o||"object"!=typeof o||!("code"in o)||"ERR_PROTO_ACCESS"!==o.code)throw o}var s=!!t&&i&&i(Object.prototype,"__proto__"),r=Object,n=r.getPrototypeOf;return gc=s&&"function"==typeof s.get?e([s.get]):"function"==typeof n&&function(t){return n(null==t?t:r(t))}}function vd(){if(wc)return bc;wc=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,i=dd();return bc=i.call(t,e)}function xd(){if(Pc)return _c;var t;Pc=1;var e=/* @__PURE__ */$c(),i=/* @__PURE__ */jc(),s=/* @__PURE__ */zc(),r=/* @__PURE__ */Vc(),n=/* @__PURE__ */qc(),o=/* @__PURE__ */Jc(),a=/* @__PURE__ */ou(),l=/* @__PURE__ */Kc(),h=/* @__PURE__ */Zc(),u=/* @__PURE__ */Qc(),c=/* @__PURE__ */td(),d=/* @__PURE__ */ed(),p=/* @__PURE__ */id(),f=/* @__PURE__ */sd(),m=/* @__PURE__ */nd(),g=Function,y=function(t){try{return g('"use strict"; return ('+t+").constructor;")()}catch(e){}},v=/* @__PURE__ */ad(),x=/* @__PURE__ */ld(),b=function(){throw new a},w=v?function(){try{return b}catch(t){try{return v(arguments,"callee").get}catch(e){return b}}}():b,_=hd()(),P=function(){if(xc)return vc;xc=1;var t=ud(),e=cd(),i=/* @__PURE__ */yd();return vc=t?function(e){return t(e)}:e?function(t){if(!t||"object"!=typeof t&&"function"!=typeof t)throw new TypeError("getProto: not an object");return e(t)}:i?function(t){return i(t)}:null}(),E=cd(),T=ud(),A=fd(),I=pd(),S={},C="undefined"!=typeof Uint8Array&&P?P(Uint8Array):t,M={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?t:ArrayBuffer,"%ArrayIteratorPrototype%":_&&P?P([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":S,"%AsyncGenerator%":S,"%AsyncGeneratorFunction%":S,"%AsyncIteratorPrototype%":S,"%Atomics%":"undefined"==typeof Atomics?t:Atomics,"%BigInt%":"undefined"==typeof BigInt?t:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?t:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":s,"%Float16Array%":"undefined"==typeof Float16Array?t:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?t:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?t:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?t:FinalizationRegistry,"%Function%":g,"%GeneratorFunction%":S,"%Int8Array%":"undefined"==typeof Int8Array?t:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?t:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":_&&P?P(P([][Symbol.iterator]())):t,"%JSON%":"object"==typeof JSON?JSON:t,"%Map%":"undefined"==typeof Map?t:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&_&&P?P(/* @__PURE__ */(new Map)[Symbol.iterator]()):t,"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":v,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?t:Promise,"%Proxy%":"undefined"==typeof Proxy?t:Proxy,"%RangeError%":r,"%ReferenceError%":n,"%Reflect%":"undefined"==typeof Reflect?t:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?t:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&_&&P?P(/* @__PURE__ */(new Set)[Symbol.iterator]()):t,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":_&&P?P(""[Symbol.iterator]()):t,"%Symbol%":_?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":w,"%TypedArray%":C,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?t:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?t:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?t:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?t:Uint32Array,"%URIError%":l,"%WeakMap%":"undefined"==typeof WeakMap?t:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?t:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?t:WeakSet,"%Function.prototype.call%":I,"%Function.prototype.apply%":A,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":h,"%Math.floor%":u,"%Math.max%":c,"%Math.min%":d,"%Math.pow%":p,"%Math.round%":f,"%Math.sign%":m,"%Reflect.getPrototypeOf%":T};if(P)try{null.error}catch(H){var O=P(P(H));M["%Error.prototype%"]=O}var N=function t(e){var i;if("%AsyncFunction%"===e)i=y("async function () {}");else if("%GeneratorFunction%"===e)i=y("function* () {}");else if("%AsyncGeneratorFunction%"===e)i=y("async function* () {}");else if("%AsyncGenerator%"===e){var s=t("%AsyncGeneratorFunction%");s&&(i=s.prototype)}else if("%AsyncIteratorPrototype%"===e){var r=t("%AsyncGenerator%");r&&P&&(i=P(r.prototype))}return M[e]=i,i},L={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},R=dd(),B=/* @__PURE__ */vd(),k=R.call(I,Array.prototype.concat),F=R.call(A,Array.prototype.splice),D=R.call(I,String.prototype.replace),U=R.call(I,String.prototype.slice),G=R.call(I,RegExp.prototype.exec),X=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,W=/\\(\\)?/g,Y=function(t,e){var i,s=t;if(B(L,s)&&(s="%"+(i=L[s])[0]+"%"),B(M,s)){var r=M[s];if(r===S&&(r=N(s)),void 0===r&&!e)throw new a("intrinsic "+t+" exists, but is not available. Please file an issue!");return{alias:i,name:s,value:r}}throw new o("intrinsic "+t+" does not exist!")};return _c=function(t,e){if("string"!=typeof t||0===t.length)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof e)throw new a('"allowMissing" argument must be a boolean');if(null===G(/^%?[^%]*%?$/,t))throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=function(t){var e=U(t,0,1),i=U(t,-1);if("%"===e&&"%"!==i)throw new o("invalid intrinsic syntax, expected closing `%`");if("%"===i&&"%"!==e)throw new o("invalid intrinsic syntax, expected opening `%`");var s=[];return D(t,X,function(t,e,i,r){s[s.length]=i?D(r,W,"$1"):e||t}),s}(t),s=i.length>0?i[0]:"",r=Y("%"+s+"%",e),n=r.name,l=r.value,h=!1,u=r.alias;u&&(s=u[0],F(i,k([0,1],u)));for(var c=1,d=!0;c<i.length;c+=1){var p=i[c],f=U(p,0,1),m=U(p,-1);if(('"'===f||"'"===f||"`"===f||'"'===m||"'"===m||"`"===m)&&f!==m)throw new o("property names with quotes must have matching quotes");if("constructor"!==p&&d||(h=!0),B(M,n="%"+(s+="."+p)+"%"))l=M[n];else if(null!=l){if(!(p in l)){if(!e)throw new a("base intrinsic for "+t+" exists, but the property is not available.");return}if(v&&c+1>=i.length){var g=v(l,p);l=(d=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:l[p]}else d=B(l,p),l=l[p];d&&!h&&(M[n]=l)}}return l},_c}function bd(){if(Tc)return Ec;Tc=1;var t=/* @__PURE__ */xd(),e=gd(),i=e([t("%String.prototype.indexOf%")]);return Ec=function(s,r){var n=t(s,!!r);return"function"==typeof n&&i(s,".prototype.")>-1?e([n]):n}}function wd(){if(Ic)return Ac;Ic=1;var t=/* @__PURE__ */xd(),e=/* @__PURE__ */bd(),i=/* @__PURE__ */Yc(),s=/* @__PURE__ */ou(),r=t("%Map%",!0),n=e("Map.prototype.get",!0),o=e("Map.prototype.set",!0),a=e("Map.prototype.has",!0),l=e("Map.prototype.delete",!0),h=e("Map.prototype.size",!0);return Ac=!!r&&function(){var t,e={assert:function(t){if(!e.has(t))throw new s("Side channel does not contain "+i(t))},delete:function(e){if(t){var i=l(t,e);return 0===h(t)&&(t=void 0),i}return!1},get:function(e){if(t)return n(t,e)},has:function(e){return!!t&&a(t,e)},set:function(e,i){t||(t=new r),o(t,e,i)}};return e}}function _d(){if(Oc)return Mc;Oc=1;var t=/* @__PURE__ */ou(),e=/* @__PURE__ */Yc(),i=Hc(),s=wd(),r=function(){if(Cc)return Sc;Cc=1;var t=/* @__PURE__ */xd(),e=/* @__PURE__ */bd(),i=/* @__PURE__ */Yc(),s=wd(),r=/* @__PURE__ */ou(),n=t("%WeakMap%",!0),o=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),h=e("WeakMap.prototype.delete",!0);return Sc=n?function(){var t,e,u={assert:function(t){if(!u.has(t))throw new r("Side channel does not contain "+i(t))},delete:function(i){if(n&&i&&("object"==typeof i||"function"==typeof i)){if(t)return h(t,i)}else if(s&&e)return e.delete(i);return!1},get:function(i){return n&&i&&("object"==typeof i||"function"==typeof i)&&t?o(t,i):e&&e.get(i)},has:function(i){return n&&i&&("object"==typeof i||"function"==typeof i)&&t?l(t,i):!!e&&e.has(i)},set:function(i,r){n&&i&&("object"==typeof i||"function"==typeof i)?(t||(t=new n),a(t,i,r)):s&&(e||(e=s()),e.set(i,r))}};return u}:s}(),n=r||s||i;return Mc=function(){var i,s={assert:function(i){if(!s.has(i))throw new t("Side channel does not contain "+e(i))},delete:function(t){return!!i&&i.delete(t)},get:function(t){return i&&i.get(t)},has:function(t){return!!i&&i.has(t)},set:function(t,e){i||(i=n()),i.set(t,e)}};return s}}function Pd(){if(Lc)return Nc;Lc=1;var t=String.prototype.replace,e=/%20/g,i="RFC3986";return Nc={default:i,formatters:{RFC1738:function(i){return t.call(i,e,"+")},RFC3986:function(t){return String(t)}},RFC1738:"RFC1738",RFC3986:i}}function Ed(){if(Bc)return Rc;Bc=1;var t=/* @__PURE__ */Pd(),e=Object.prototype.hasOwnProperty,i=Array.isArray,s=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),r=function(t,e){for(var i=e&&e.plainObjects?{__proto__:null}:{},s=0;s<t.length;++s)void 0!==t[s]&&(i[s]=t[s]);return i},n=1024;return Rc={arrayToObject:r,assign:function(t,e){return Object.keys(e).reduce(function(t,i){return t[i]=e[i],t},t)},combine:function(t,e){return[].concat(t,e)},compact:function(t){for(var e=[{obj:{o:t},prop:"o"}],s=[],r=0;r<e.length;++r)for(var n=e[r],o=n.obj[n.prop],a=Object.keys(o),l=0;l<a.length;++l){var h=a[l],u=o[h];"object"==typeof u&&null!==u&&-1===s.indexOf(u)&&(e.push({obj:o,prop:h}),s.push(u))}return function(t){for(;t.length>1;){var e=t.pop(),s=e.obj[e.prop];if(i(s)){for(var r=[],n=0;n<s.length;++n)void 0!==s[n]&&r.push(s[n]);e.obj[e.prop]=r}}}(e),t},decode:function(t,e,i){var s=t.replace(/\+/g," ");if("iso-8859-1"===i)return s.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(s)}catch(r){return s}},encode:function(e,i,r,o,a){if(0===e.length)return e;var l=e;if("symbol"==typeof e?l=Symbol.prototype.toString.call(e):"string"!=typeof e&&(l=String(e)),"iso-8859-1"===r)return escape(l).replace(/%u[0-9a-f]{4}/gi,function(t){return"%26%23"+parseInt(t.slice(2),16)+"%3B"});for(var h="",u=0;u<l.length;u+=n){for(var c=l.length>=n?l.slice(u,u+n):l,d=[],p=0;p<c.length;++p){var f=c.charCodeAt(p);45===f||46===f||95===f||126===f||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||a===t.RFC1738&&(40===f||41===f)?d[d.length]=c.charAt(p):f<128?d[d.length]=s[f]:f<2048?d[d.length]=s[192|f>>6]+s[128|63&f]:f<55296||f>=57344?d[d.length]=s[224|f>>12]+s[128|f>>6&63]+s[128|63&f]:(p+=1,f=65536+((1023&f)<<10|1023&c.charCodeAt(p)),d[d.length]=s[240|f>>18]+s[128|f>>12&63]+s[128|f>>6&63]+s[128|63&f])}h+=d.join("")}return h},isBuffer:function(t){return!(!t||"object"!=typeof t)&&!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))},isRegExp:function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},maybeMap:function(t,e){if(i(t)){for(var s=[],r=0;r<t.length;r+=1)s.push(e(t[r]));return s}return e(t)},merge:function t(s,n,o){if(!n)return s;if("object"!=typeof n&&"function"!=typeof n){if(i(s))s.push(n);else{if(!s||"object"!=typeof s)return[s,n];(o&&(o.plainObjects||o.allowPrototypes)||!e.call(Object.prototype,n))&&(s[n]=!0)}return s}if(!s||"object"!=typeof s)return[s].concat(n);var a=s;return i(s)&&!i(n)&&(a=r(s,o)),i(s)&&i(n)?(n.forEach(function(i,r){if(e.call(s,r)){var n=s[r];n&&"object"==typeof n&&i&&"object"==typeof i?s[r]=t(n,i,o):s.push(i)}else s[r]=i}),s):Object.keys(n).reduce(function(i,s){var r=n[s];return e.call(i,s)?i[s]=t(i[s],r,o):i[s]=r,i},a)}},Rc}function Td(){if(Fc)return kc;Fc=1;var t=_d(),e=/* @__PURE__ */Ed(),i=/* @__PURE__ */Pd(),s=Object.prototype.hasOwnProperty,r={brackets:function(t){return t+"[]"},comma:"comma",indices:function(t,e){return t+"["+e+"]"},repeat:function(t){return t}},n=Array.isArray,o=Array.prototype.push,a=function(t,e){o.apply(t,n(e)?e:[e])},l=Date.prototype.toISOString,h=i.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,filter:void 0,format:h,formatter:i.formatters[h],indices:!1,serializeDate:function(t){return l.call(t)},skipNulls:!1,strictNullHandling:!1},c={},d=function i(s,r,o,l,h,d,p,f,m,g,y,v,x,b,w,_,P,E){for(var T,A=s,I=E,S=0,C=!1;void 0!==(I=I.get(c))&&!C;){var M=I.get(s);if(S+=1,void 0!==M){if(M===S)throw new RangeError("Cyclic object value");C=!0}void 0===I.get(c)&&(S=0)}if("function"==typeof g?A=g(r,A):A instanceof Date?A=x(A):"comma"===o&&n(A)&&(A=e.maybeMap(A,function(t){return t instanceof Date?x(t):t})),null===A){if(d)return m&&!_?m(r,u.encoder,P,"key",b):r;A=""}if("string"==typeof(T=A)||"number"==typeof T||"boolean"==typeof T||"symbol"==typeof T||"bigint"==typeof T||e.isBuffer(A))return m?[w(_?r:m(r,u.encoder,P,"key",b))+"="+w(m(A,u.encoder,P,"value",b))]:[w(r)+"="+w(String(A))];var O,N=[];if(void 0===A)return N;if("comma"===o&&n(A))_&&m&&(A=e.maybeMap(A,m)),O=[{value:A.length>0?A.join(",")||null:void 0}];else if(n(g))O=g;else{var L=Object.keys(A);O=y?L.sort(y):L}var R=f?String(r).replace(/\./g,"%2E"):String(r),B=l&&n(A)&&1===A.length?R+"[]":R;if(h&&n(A)&&0===A.length)return B+"[]";for(var k=0;k<O.length;++k){var F=O[k],D="object"==typeof F&&F&&void 0!==F.value?F.value:A[F];if(!p||null!==D){var U=v&&f?String(F).replace(/\./g,"%2E"):String(F),G=n(A)?"function"==typeof o?o(B,U):B:B+(v?"."+U:"["+U+"]");E.set(s,S);var X=t();X.set(c,E),a(N,i(D,G,o,l,h,d,p,f,"comma"===o&&_&&n(A)?null:m,g,y,v,x,b,w,_,P,X))}}return N};return kc=function(e,o){var l,h=e,c=function(t){if(!t)return u;if(void 0!==t.allowEmptyArrays&&"boolean"!=typeof t.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==t.encodeDotInKeys&&"boolean"!=typeof t.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==t.encoder&&void 0!==t.encoder&&"function"!=typeof t.encoder)throw new TypeError("Encoder has to be a function.");var e=t.charset||u.charset;if(void 0!==t.charset&&"utf-8"!==t.charset&&"iso-8859-1"!==t.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var o=i.default;if(void 0!==t.format){if(!s.call(i.formatters,t.format))throw new TypeError("Unknown format option provided.");o=t.format}var a,l=i.formatters[o],h=u.filter;if(("function"==typeof t.filter||n(t.filter))&&(h=t.filter),a=t.arrayFormat in r?t.arrayFormat:"indices"in t?t.indices?"indices":"repeat":u.arrayFormat,"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var c=void 0===t.allowDots?!0===t.encodeDotInKeys||u.allowDots:!!t.allowDots;return{addQueryPrefix:"boolean"==typeof t.addQueryPrefix?t.addQueryPrefix:u.addQueryPrefix,allowDots:c,allowEmptyArrays:"boolean"==typeof t.allowEmptyArrays?!!t.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:"boolean"==typeof t.charsetSentinel?t.charsetSentinel:u.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:void 0===t.delimiter?u.delimiter:t.delimiter,encode:"boolean"==typeof t.encode?t.encode:u.encode,encodeDotInKeys:"boolean"==typeof t.encodeDotInKeys?t.encodeDotInKeys:u.encodeDotInKeys,encoder:"function"==typeof t.encoder?t.encoder:u.encoder,encodeValuesOnly:"boolean"==typeof t.encodeValuesOnly?t.encodeValuesOnly:u.encodeValuesOnly,filter:h,format:o,formatter:l,serializeDate:"function"==typeof t.serializeDate?t.serializeDate:u.serializeDate,skipNulls:"boolean"==typeof t.skipNulls?t.skipNulls:u.skipNulls,sort:"function"==typeof t.sort?t.sort:null,strictNullHandling:"boolean"==typeof t.strictNullHandling?t.strictNullHandling:u.strictNullHandling}}(o);"function"==typeof c.filter?h=(0,c.filter)("",h):n(c.filter)&&(l=c.filter);var p=[];if("object"!=typeof h||null===h)return"";var f=r[c.arrayFormat],m="comma"===f&&c.commaRoundTrip;l||(l=Object.keys(h)),c.sort&&l.sort(c.sort);for(var g=t(),y=0;y<l.length;++y){var v=l[y],x=h[v];c.skipNulls&&null===x||a(p,d(x,v,f,m,c.allowEmptyArrays,c.strictNullHandling,c.skipNulls,c.encodeDotInKeys,c.encode?c.encoder:null,c.filter,c.sort,c.allowDots,c.serializeDate,c.format,c.formatter,c.encodeValuesOnly,c.charset,g))}var b=p.join(c.delimiter),w=!0===c.addQueryPrefix?"?":"";return c.charsetSentinel&&("iso-8859-1"===c.charset?w+="utf8=%26%2310003%3B&":w+="utf8=%E2%9C%93&"),b.length>0?w+b:""}}function Ad(){if(Uc)return Dc;Uc=1;var t=/* @__PURE__ */Ed(),e=Object.prototype.hasOwnProperty,i=Array.isArray,s={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:t.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1,throwOnLimitExceeded:!1},r=function(t){return t.replace(/&#(\d+);/g,function(t,e){return String.fromCharCode(parseInt(e,10))})},n=function(t,e,i){if(t&&"string"==typeof t&&e.comma&&t.indexOf(",")>-1)return t.split(",");if(e.throwOnLimitExceeded&&i>=e.arrayLimit)throw new RangeError("Array limit exceeded. Only "+e.arrayLimit+" element"+(1===e.arrayLimit?"":"s")+" allowed in an array.");return t},o=function(i,s,r,o){if(i){var a=r.allowDots?i.replace(/\.([^.[]+)/g,"[$1]"):i,l=/(\[[^[\]]*])/g,h=r.depth>0&&/(\[[^[\]]*])/.exec(a),u=h?a.slice(0,h.index):a,c=[];if(u){if(!r.plainObjects&&e.call(Object.prototype,u)&&!r.allowPrototypes)return;c.push(u)}for(var d=0;r.depth>0&&null!==(h=l.exec(a))&&d<r.depth;){if(d+=1,!r.plainObjects&&e.call(Object.prototype,h[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(h[1])}if(h){if(!0===r.strictDepth)throw new RangeError("Input depth exceeded depth option of "+r.depth+" and strictDepth is true");c.push("["+a.slice(h.index)+"]")}return function(e,i,s,r){var o=0;if(e.length>0&&"[]"===e[e.length-1]){var a=e.slice(0,-1).join("");o=Array.isArray(i)&&i[a]?i[a].length:0}for(var l=r?i:n(i,s,o),h=e.length-1;h>=0;--h){var u,c=e[h];if("[]"===c&&s.parseArrays)u=s.allowEmptyArrays&&(""===l||s.strictNullHandling&&null===l)?[]:t.combine([],l);else{u=s.plainObjects?{__proto__:null}:{};var d="["===c.charAt(0)&&"]"===c.charAt(c.length-1)?c.slice(1,-1):c,p=s.decodeDotInKeys?d.replace(/%2E/g,"."):d,f=parseInt(p,10);s.parseArrays||""!==p?!isNaN(f)&&c!==p&&String(f)===p&&f>=0&&s.parseArrays&&f<=s.arrayLimit?(u=[])[f]=l:"__proto__"!==p&&(u[p]=l):u={0:l}}l=u}return l}(c,s,r,o)}};return Dc=function(a,l){var h=function(e){if(!e)return s;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.decodeDotInKeys&&"boolean"!=typeof e.decodeDotInKeys)throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(void 0!==e.throwOnLimitExceeded&&"boolean"!=typeof e.throwOnLimitExceeded)throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var i=void 0===e.charset?s.charset:e.charset,r=void 0===e.duplicates?s.duplicates:e.duplicates;if("combine"!==r&&"first"!==r&&"last"!==r)throw new TypeError("The duplicates option must be either combine, first, or last");return{allowDots:void 0===e.allowDots?!0===e.decodeDotInKeys||s.allowDots:!!e.allowDots,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:s.allowEmptyArrays,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:s.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:s.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:s.arrayLimit,charset:i,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:s.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:s.comma,decodeDotInKeys:"boolean"==typeof e.decodeDotInKeys?e.decodeDotInKeys:s.decodeDotInKeys,decoder:"function"==typeof e.decoder?e.decoder:s.decoder,delimiter:"string"==typeof e.delimiter||t.isRegExp(e.delimiter)?e.delimiter:s.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:s.depth,duplicates:r,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:s.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:s.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:s.plainObjects,strictDepth:"boolean"==typeof e.strictDepth?!!e.strictDepth:s.strictDepth,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:s.strictNullHandling,throwOnLimitExceeded:"boolean"==typeof e.throwOnLimitExceeded&&e.throwOnLimitExceeded}}(l);if(""===a||null==a)return h.plainObjects?{__proto__:null}:{};for(var u="string"==typeof a?function(o,a){var l={__proto__:null},h=a.ignoreQueryPrefix?o.replace(/^\?/,""):o;h=h.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var u=a.parameterLimit===1/0?void 0:a.parameterLimit,c=h.split(a.delimiter,a.throwOnLimitExceeded?u+1:u);if(a.throwOnLimitExceeded&&c.length>u)throw new RangeError("Parameter limit exceeded. Only "+u+" parameter"+(1===u?"":"s")+" allowed.");var d,p=-1,f=a.charset;if(a.charsetSentinel)for(d=0;d<c.length;++d)0===c[d].indexOf("utf8=")&&("utf8=%E2%9C%93"===c[d]?f="utf-8":"utf8=%26%2310003%3B"===c[d]&&(f="iso-8859-1"),p=d,d=c.length);for(d=0;d<c.length;++d)if(d!==p){var m,g,y=c[d],v=y.indexOf("]="),x=-1===v?y.indexOf("="):v+1;-1===x?(m=a.decoder(y,s.decoder,f,"key"),g=a.strictNullHandling?null:""):(m=a.decoder(y.slice(0,x),s.decoder,f,"key"),g=t.maybeMap(n(y.slice(x+1),a,i(l[m])?l[m].length:0),function(t){return a.decoder(t,s.decoder,f,"value")})),g&&a.interpretNumericEntities&&"iso-8859-1"===f&&(g=r(String(g))),y.indexOf("[]=")>-1&&(g=i(g)?[g]:g);var b=e.call(l,m);b&&"combine"===a.duplicates?l[m]=t.combine(l[m],g):b&&"last"!==a.duplicates||(l[m]=g)}return l}(a,h):a,c=h.plainObjects?{__proto__:null}:{},d=Object.keys(u),p=0;p<d.length;++p){var f=d[p],m=o(f,u[f],h,"string"==typeof a);c=t.merge(c,m,h)}return!0===h.allowSparse?c:t.compact(c)}}function Id(){if(Xc)return Gc;Xc=1;var t=/* @__PURE__ */Td(),e=/* @__PURE__ */Ad();return Gc={formats:/* @__PURE__ */Pd(),parse:e,stringify:t}}var Sd=function(){if(Wc)return su;Wc=1;var t=(tu||(tu=1,function(t,e){!function(i){var s=e&&!e.nodeType&&e,r=t&&!t.nodeType&&t,n="object"==typeof At&&At;n.global!==n&&n.window!==n&&n.self!==n||(i=n);var o,a,l=2147483647,h=36,u=/^xn--/,c=/[^\x20-\x7E]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,m=String.fromCharCode;function g(t){throw new RangeError(p[t])}function y(t,e){for(var i=t.length,s=[];i--;)s[i]=e(t[i]);return s}function v(t,e){var i=t.split("@"),s="";return i.length>1&&(s=i[0]+"@",t=i[1]),s+y((t=t.replace(d,".")).split("."),e).join(".")}function x(t){for(var e,i,s=[],r=0,n=t.length;r<n;)(e=t.charCodeAt(r++))>=55296&&e<=56319&&r<n?56320==(64512&(i=t.charCodeAt(r++)))?s.push(((1023&e)<<10)+(1023&i)+65536):(s.push(e),r--):s.push(e);return s}function b(t){return y(t,function(t){var e="";return t>65535&&(e+=m((t-=65536)>>>10&1023|55296),t=56320|1023&t),e+m(t)}).join("")}function w(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:h}function _(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function P(t,e,i){var s=0;for(t=i?f(t/700):t>>1,t+=f(t/e);t>455;s+=h)t=f(t/35);return f(s+36*t/(t+38))}function E(t){var e,i,s,r,n,o,a,u,c,d,p=[],m=t.length,y=0,v=128,x=72;for((i=t.lastIndexOf("-"))<0&&(i=0),s=0;s<i;++s)t.charCodeAt(s)>=128&&g("not-basic"),p.push(t.charCodeAt(s));for(r=i>0?i+1:0;r<m;){for(n=y,o=1,a=h;r>=m&&g("invalid-input"),((u=w(t.charCodeAt(r++)))>=h||u>f((l-y)/o))&&g("overflow"),y+=u*o,!(u<(c=a<=x?1:a>=x+26?26:a-x));a+=h)o>f(l/(d=h-c))&&g("overflow"),o*=d;x=P(y-n,e=p.length+1,0==n),f(y/e)>l-v&&g("overflow"),v+=f(y/e),y%=e,p.splice(y++,0,v)}return b(p)}function T(t){var e,i,s,r,n,o,a,u,c,d,p,y,v,b,w,E=[];for(y=(t=x(t)).length,e=128,i=0,n=72,o=0;o<y;++o)(p=t[o])<128&&E.push(m(p));for(s=r=E.length,r&&E.push("-");s<y;){for(a=l,o=0;o<y;++o)(p=t[o])>=e&&p<a&&(a=p);for(a-e>f((l-i)/(v=s+1))&&g("overflow"),i+=(a-e)*v,e=a,o=0;o<y;++o)if((p=t[o])<e&&++i>l&&g("overflow"),p==e){for(u=i,c=h;!(u<(d=c<=n?1:c>=n+26?26:c-n));c+=h)w=u-d,b=h-d,E.push(m(_(d+w%b,0))),u=f(w/b);E.push(m(_(u,0))),n=P(i,v,s==r),i=0,++s}++i,++e}return E.join("")}if(o={version:"1.4.1",ucs2:{decode:x,encode:b},decode:E,encode:T,toASCII:function(t){return v(t,function(t){return c.test(t)?"xn--"+T(t):t})},toUnicode:function(t){return v(t,function(t){return u.test(t)?E(t.slice(4).toLowerCase()):t})}},s&&r)if(t.exports==s)r.exports=o;else for(a in o)o.hasOwnProperty(a)&&(s[a]=o[a]);else i.punycode=o}(nu)}(ru,ru.exports)),ru.exports);function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var i=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,r=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),o=["'"].concat(n),a=["%","/","?",";","#"].concat(o),l=["/","?","#"],h=/^[+a-z0-9A-Z_-]{0,63}$/,u=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,c={javascript:!0,"javascript:":!0},d={javascript:!0,"javascript:":!0},p={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},f=/* @__PURE__ */Id();function m(t,i,s){if(t&&"object"==typeof t&&t instanceof e)return t;var r=new e;return r.parse(t,i,s),r}return e.prototype.parse=function(e,s,n){if("string"!=typeof e)throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var m=e.indexOf("?"),g=-1!==m&&m<e.indexOf("#")?"?":"#",y=e.split(g);y[0]=y[0].replace(/\\/g,"/");var v=e=y.join(g);if(v=v.trim(),!n&&1===e.split("#").length){var x=r.exec(v);if(x)return this.path=v,this.href=v,this.pathname=x[1],x[2]?(this.search=x[2],this.query=s?f.parse(this.search.substr(1)):this.search.substr(1)):s&&(this.search="",this.query={}),this}var b=i.exec(v);if(b){var w=(b=b[0]).toLowerCase();this.protocol=w,v=v.substr(b.length)}if(n||b||v.match(/^\/\/[^@/]+@[^@/]+/)){var _="//"===v.substr(0,2);!_||b&&d[b]||(v=v.substr(2),this.slashes=!0)}if(!d[b]&&(_||b&&!p[b])){for(var P,E,T=-1,A=0;A<l.length;A++){-1!==(I=v.indexOf(l[A]))&&(-1===T||I<T)&&(T=I)}-1!==(E=-1===T?v.lastIndexOf("@"):v.lastIndexOf("@",T))&&(P=v.slice(0,E),v=v.slice(E+1),this.auth=decodeURIComponent(P)),T=-1;for(A=0;A<a.length;A++){var I;-1!==(I=v.indexOf(a[A]))&&(-1===T||I<T)&&(T=I)}-1===T&&(T=v.length),this.host=v.slice(0,T),v=v.slice(T),this.parseHost(),this.hostname=this.hostname||"";var S="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!S)for(var C=this.hostname.split(/\./),M=(A=0,C.length);A<M;A++){var O=C[A];if(O&&!O.match(h)){for(var N="",L=0,R=O.length;L<R;L++)O.charCodeAt(L)>127?N+="x":N+=O[L];if(!N.match(h)){var B=C.slice(0,A),k=C.slice(A+1),F=O.match(u);F&&(B.push(F[1]),k.unshift(F[2])),k.length&&(v="/"+k.join(".")+v),this.hostname=B.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),S||(this.hostname=t.toASCII(this.hostname));var D=this.port?":"+this.port:"",U=this.hostname||"";this.host=U+D,this.href+=this.host,S&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==v[0]&&(v="/"+v))}if(!c[w])for(A=0,M=o.length;A<M;A++){var G=o[A];if(-1!==v.indexOf(G)){var X=encodeURIComponent(G);X===G&&(X=escape(G)),v=v.split(G).join(X)}}var W=v.indexOf("#");-1!==W&&(this.hash=v.substr(W),v=v.slice(0,W));var Y=v.indexOf("?");if(-1!==Y?(this.search=v.substr(Y),this.query=v.substr(Y+1),s&&(this.query=f.parse(this.query)),v=v.slice(0,Y)):s&&(this.search="",this.query={}),v&&(this.pathname=v),p[w]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){D=this.pathname||"";var H=this.search||"";this.path=D+H}return this.href=this.format(),this},e.prototype.format=function(){var t=this.auth||"";t&&(t=(t=encodeURIComponent(t)).replace(/%3A/i,":"),t+="@");var e=this.protocol||"",i=this.pathname||"",s=this.hash||"",r=!1,n="";this.host?r=t+this.host:this.hostname&&(r=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(r+=":"+this.port)),this.query&&"object"==typeof this.query&&Object.keys(this.query).length&&(n=f.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var o=this.search||n&&"?"+n||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||p[e])&&!1!==r?(r="//"+(r||""),i&&"/"!==i.charAt(0)&&(i="/"+i)):r||(r=""),s&&"#"!==s.charAt(0)&&(s="#"+s),o&&"?"!==o.charAt(0)&&(o="?"+o),e+r+(i=i.replace(/[?#]/g,function(t){return encodeURIComponent(t)}))+(o=o.replace("#","%23"))+s},e.prototype.resolve=function(t){return this.resolveObject(m(t,!1,!0)).format()},e.prototype.resolveObject=function(t){if("string"==typeof t){var i=new e;i.parse(t,!1,!0),t=i}for(var s=new e,r=Object.keys(this),n=0;n<r.length;n++){var o=r[n];s[o]=this[o]}if(s.hash=t.hash,""===t.href)return s.href=s.format(),s;if(t.slashes&&!t.protocol){for(var a=Object.keys(t),l=0;l<a.length;l++){var h=a[l];"protocol"!==h&&(s[h]=t[h])}return p[s.protocol]&&s.hostname&&!s.pathname&&(s.pathname="/",s.path=s.pathname),s.href=s.format(),s}if(t.protocol&&t.protocol!==s.protocol){if(!p[t.protocol]){for(var u=Object.keys(t),c=0;c<u.length;c++){var f=u[c];s[f]=t[f]}return s.href=s.format(),s}if(s.protocol=t.protocol,t.host||d[t.protocol])s.pathname=t.pathname;else{for(var m=(t.pathname||"").split("/");m.length&&!(t.host=m.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==m[0]&&m.unshift(""),m.length<2&&m.unshift(""),s.pathname=m.join("/")}if(s.search=t.search,s.query=t.query,s.host=t.host||"",s.auth=t.auth,s.hostname=t.hostname||t.host,s.port=t.port,s.pathname||s.search){var g=s.pathname||"",y=s.search||"";s.path=g+y}return s.slashes=s.slashes||t.slashes,s.href=s.format(),s}var v=s.pathname&&"/"===s.pathname.charAt(0),x=t.host||t.pathname&&"/"===t.pathname.charAt(0),b=x||v||s.host&&t.pathname,w=b,_=s.pathname&&s.pathname.split("/")||[],P=(m=t.pathname&&t.pathname.split("/")||[],s.protocol&&!p[s.protocol]);if(P&&(s.hostname="",s.port=null,s.host&&(""===_[0]?_[0]=s.host:_.unshift(s.host)),s.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===m[0]?m[0]=t.host:m.unshift(t.host)),t.host=null),b=b&&(""===m[0]||""===_[0])),x)s.host=t.host||""===t.host?t.host:s.host,s.hostname=t.hostname||""===t.hostname?t.hostname:s.hostname,s.search=t.search,s.query=t.query,_=m;else if(m.length)_||(_=[]),_.pop(),_=_.concat(m),s.search=t.search,s.query=t.query;else if(null!=t.search){if(P)s.host=_.shift(),s.hostname=s.host,(S=!!(s.host&&s.host.indexOf("@")>0)&&s.host.split("@"))&&(s.auth=S.shift(),s.hostname=S.shift(),s.host=s.hostname);return s.search=t.search,s.query=t.query,null===s.pathname&&null===s.search||(s.path=(s.pathname?s.pathname:"")+(s.search?s.search:"")),s.href=s.format(),s}if(!_.length)return s.pathname=null,s.search?s.path="/"+s.search:s.path=null,s.href=s.format(),s;for(var E=_.slice(-1)[0],T=(s.host||t.host||_.length>1)&&("."===E||".."===E)||""===E,A=0,I=_.length;I>=0;I--)"."===(E=_[I])?_.splice(I,1):".."===E?(_.splice(I,1),A++):A&&(_.splice(I,1),A--);if(!b&&!w)for(;A--;A)_.unshift("..");!b||""===_[0]||_[0]&&"/"===_[0].charAt(0)||_.unshift(""),T&&"/"!==_.join("/").substr(-1)&&_.push("");var S,C=""===_[0]||_[0]&&"/"===_[0].charAt(0);P&&(s.hostname=C?"":_.length?_.shift():"",s.host=s.hostname,(S=!!(s.host&&s.host.indexOf("@")>0)&&s.host.split("@"))&&(s.auth=S.shift(),s.hostname=S.shift(),s.host=s.hostname));return(b=b||s.host&&_.length)&&!C&&_.unshift(""),_.length>0?s.pathname=_.join("/"):(s.pathname=null,s.path=null),null===s.pathname&&null===s.search||(s.path=(s.pathname?s.pathname:"")+(s.search?s.search:"")),s.auth=t.auth||s.auth,s.slashes=s.slashes||t.slashes,s.href=s.format(),s},e.prototype.parseHost=function(){var t=this.host,e=s.exec(t);e&&(":"!==(e=e[0])&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)},su.parse=m,su.resolve=function(t,e){return m(t,!1,!0).resolve(e)},su.resolveObject=function(t,e){return t?m(t,!1,!0).resolveObject(e):e},su.format=function(t){return"string"==typeof t&&(t=m(t)),t instanceof e?t.format():e.prototype.format.call(t)},su.Url=e,su}();const Cd={};function Md(t,e,i=3){if(Cd[e])return;let s=(new Error).stack;typeof s>"u"?console.warn("PixiJS Deprecation Warning: ",`${e}\nDeprecated since v${t}`):(s=s.split("\n").splice(i).join("\n"),console.groupCollapsed?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",`${e}\nDeprecated since v${t}`),console.warn(s),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",`${e}\nDeprecated since v${t}`),console.warn(s))),Cd[e]=!0}const Od={get parse(){return Md("7.3.0","utils.url.parse is deprecated, use native URL API instead."),Sd.parse},get format(){return Md("7.3.0","utils.url.format is deprecated, use native URL API instead."),Sd.format},get resolve(){return Md("7.3.0","utils.url.resolve is deprecated, use native URL API instead."),Sd.resolve}};function Nd(t){if("string"!=typeof t)throw new TypeError(`Path must be a string. Received ${JSON.stringify(t)}`)}function Ld(t){return t.split("?")[0].split("#")[0]}const Rd={toPosix(t){return e="\\",i="/",t.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),i);var e,i},isUrl(t){return/^https?:/.test(this.toPosix(t))},isDataUrl:t=>/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(t),isBlobUrl:t=>t.startsWith("blob:"),hasProtocol(t){return/^[^/:]+:/.test(this.toPosix(t))},getProtocol(t){Nd(t),t=this.toPosix(t);const e=/^file:\/\/\//.exec(t);if(e)return e[0];const i=/^[^/:]+:\/{0,2}/.exec(t);return i?i[0]:""},toAbsolute(t,e,i){if(Nd(t),this.isDataUrl(t)||this.isBlobUrl(t))return t;const s=Ld(this.toPosix(e??Oh.ADAPTER.getBaseUrl())),r=Ld(this.toPosix(i??this.rootname(s)));return(t=this.toPosix(t)).startsWith("/")?Rd.join(r,t.slice(1)):this.isAbsolute(t)?t:this.join(s,t)},normalize(t){if(Nd(t),0===t.length)return".";if(this.isDataUrl(t)||this.isBlobUrl(t))return t;let e="";const i=(t=this.toPosix(t)).startsWith("/");this.hasProtocol(t)&&(e=this.rootname(t),t=t.slice(e.length));const s=t.endsWith("/");return(t=function(t){let e="",i=0,s=-1,r=0,n=-1;for(let o=0;o<=t.length;++o){if(o<t.length)n=t.charCodeAt(o);else{if(47===n)break;n=47}if(47===n){if(s!==o-1&&1!==r)if(s!==o-1&&2===r){if(e.length<2||2!==i||46!==e.charCodeAt(e.length-1)||46!==e.charCodeAt(e.length-2))if(e.length>2){const t=e.lastIndexOf("/");if(t!==e.length-1){-1===t?(e="",i=0):(e=e.slice(0,t),i=e.length-1-e.lastIndexOf("/")),s=o,r=0;continue}}else if(2===e.length||1===e.length){e="",i=0,s=o,r=0;continue}}else e.length>0?e+=`/${t.slice(s+1,o)}`:e=t.slice(s+1,o),i=o-s-1;s=o,r=0}else 46===n&&-1!==r?++r:r=-1}return e}(t)).length>0&&s&&(t+="/"),i?`/${t}`:e+t},isAbsolute(t){return Nd(t),t=this.toPosix(t),!!this.hasProtocol(t)||t.startsWith("/")},join(...t){if(0===t.length)return".";let e;for(let i=0;i<t.length;++i){const s=t[i];if(Nd(s),s.length>0)if(void 0===e)e=s;else{const r=t[i-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?e+=`/../${s}`:e+=`/${s}`}}return void 0===e?".":this.normalize(e)},dirname(t){if(Nd(t),0===t.length)return".";let e=(t=this.toPosix(t)).charCodeAt(0);const i=47===e;let s=-1,r=!0;const n=this.getProtocol(t),o=t;for(let a=(t=t.slice(n.length)).length-1;a>=1;--a)if(e=t.charCodeAt(a),47===e){if(!r){s=a;break}}else r=!1;return-1===s?i?"/":this.isUrl(o)?n+t:n:i&&1===s?"//":n+t.slice(0,s)},rootname(t){Nd(t);let e="";if(e=(t=this.toPosix(t)).startsWith("/")?"/":this.getProtocol(t),this.isUrl(t)){const i=t.indexOf("/",e.length);e=-1!==i?t.slice(0,i):t,e.endsWith("/")||(e+="/")}return e},basename(t,e){Nd(t),e&&Nd(e),t=Ld(this.toPosix(t));let i,s=0,r=-1,n=!0;if(void 0!==e&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";let o=e.length-1,a=-1;for(i=t.length-1;i>=0;--i){const l=t.charCodeAt(i);if(47===l){if(!n){s=i+1;break}}else-1===a&&(n=!1,a=i+1),o>=0&&(l===e.charCodeAt(o)?-1===--o&&(r=i):(o=-1,r=a))}return s===r?r=a:-1===r&&(r=t.length),t.slice(s,r)}for(i=t.length-1;i>=0;--i)if(47===t.charCodeAt(i)){if(!n){s=i+1;break}}else-1===r&&(n=!1,r=i+1);return-1===r?"":t.slice(s,r)},extname(t){Nd(t);let e=-1,i=0,s=-1,r=!0,n=0;for(let o=(t=Ld(this.toPosix(t))).length-1;o>=0;--o){const a=t.charCodeAt(o);if(47!==a)-1===s&&(r=!1,s=o+1),46===a?-1===e?e=o:1!==n&&(n=1):-1!==e&&(n=-1);else if(!r){i=o+1;break}}return-1===e||-1===s||0===n||1===n&&e===s-1&&e===i+1?"":t.slice(e,s)},parse(t){Nd(t);const e={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return e;let i=(t=Ld(this.toPosix(t))).charCodeAt(0);const s=this.isAbsolute(t);let r;e.root=this.rootname(t),r=s||this.hasProtocol(t)?1:0;let n=-1,o=0,a=-1,l=!0,h=t.length-1,u=0;for(;h>=r;--h)if(i=t.charCodeAt(h),47!==i)-1===a&&(l=!1,a=h+1),46===i?-1===n?n=h:1!==u&&(u=1):-1!==n&&(u=-1);else if(!l){o=h+1;break}return-1===n||-1===a||0===u||1===u&&n===a-1&&n===o+1?-1!==a&&(e.base=e.name=0===o&&s?t.slice(1,a):t.slice(o,a)):(0===o&&s?(e.name=t.slice(1,n),e.base=t.slice(1,a)):(e.name=t.slice(o,n),e.base=t.slice(o,a)),e.ext=t.slice(n,a)),e.dir=this.dirname(t),e},sep:"/",delimiter:":",joinExtensions:[".html"]};let Bd,kd;function Fd(){return typeof kd>"u"&&(kd=function(){const t={stencil:!0,failIfMajorPerformanceCaveat:Oh.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT};try{if(!Oh.ADAPTER.getWebGLRenderingContext())return!1;const e=Oh.ADAPTER.createCanvas();let i=e.getContext("webgl",t)||e.getContext("experimental-webgl",t);const s=!!i?.getContextAttributes()?.stencil;if(i){const t=i.getExtension("WEBGL_lose_context");t&&t.loseContext()}return i=null,s}catch{return!1}}()),kd}var Dd,Ud={grad:.9,turn:360,rad:360/(2*Math.PI)},Gd=function(t){return"string"==typeof t?t.length>0:"number"==typeof t},Xd=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=Math.pow(10,e)),Math.round(i*t)/i+0},Wd=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=1),t>i?i:t>e?t:e},Yd=function(t){return(t=isFinite(t)?t%360:0)>0?t:t+360},Hd=function(t){return{r:Wd(t.r,0,255),g:Wd(t.g,0,255),b:Wd(t.b,0,255),a:Wd(t.a)}},$d=function(t){return{r:Xd(t.r),g:Xd(t.g),b:Xd(t.b),a:Xd(t.a,3)}},jd=/^#([0-9a-f]{3,8})$/i,zd=function(t){var e=t.toString(16);return e.length<2?"0"+e:e},Vd=function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=Math.max(e,i,s),o=n-Math.min(e,i,s),a=o?n===e?(i-s)/o:n===i?2+(s-e)/o:4+(e-i)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},qd=function(t){var e=t.h,i=t.s,s=t.v,r=t.a;e=e/360*6,i/=100,s/=100;var n=Math.floor(e),o=s*(1-i),a=s*(1-(e-n)*i),l=s*(1-(1-e+n)*i),h=n%6;return{r:255*[s,a,o,o,l,s][h],g:255*[l,s,s,a,o,o][h],b:255*[o,o,l,s,s,a][h],a:r}},Jd=function(t){return{h:Yd(t.h),s:Wd(t.s,0,100),l:Wd(t.l,0,100),a:Wd(t.a)}},Kd=function(t){return{h:Xd(t.h),s:Xd(t.s),l:Xd(t.l),a:Xd(t.a,3)}},Zd=function(t){return qd((i=(e=t).s,{h:e.h,s:(i*=((s=e.l)<50?s:100-s)/100)>0?2*i/(s+i)*100:0,v:s+i,a:e.a}));var e,i,s},Qd=function(t){return{h:(e=Vd(t)).h,s:(r=(200-(i=e.s))*(s=e.v)/100)>0&&r<200?i*s/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,i,s,r},tp=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,ep=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,ip=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,sp=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,rp={string:[[function(t){var e=jd.exec(t);return e?(t=e[1]).length<=4?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16),a:4===t.length?Xd(parseInt(t[3]+t[3],16)/255,2):1}:6===t.length||8===t.length?{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16),a:8===t.length?Xd(parseInt(t.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(t){var e=ip.exec(t)||sp.exec(t);return e?e[2]!==e[4]||e[4]!==e[6]?null:Hd({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:void 0===e[7]?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(t){var e=tp.exec(t)||ep.exec(t);if(!e)return null;var i,s,r=Jd({h:(i=e[1],s=e[2],void 0===s&&(s="deg"),Number(i)*(Ud[s]||1)),s:Number(e[3]),l:Number(e[4]),a:void 0===e[5]?1:Number(e[5])/(e[6]?100:1)});return Zd(r)},"hsl"]],object:[[function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=void 0===r?1:r;return Gd(e)&&Gd(i)&&Gd(s)?Hd({r:Number(e),g:Number(i),b:Number(s),a:Number(n)}):null},"rgb"],[function(t){var e=t.h,i=t.s,s=t.l,r=t.a,n=void 0===r?1:r;if(!Gd(e)||!Gd(i)||!Gd(s))return null;var o=Jd({h:Number(e),s:Number(i),l:Number(s),a:Number(n)});return Zd(o)},"hsl"],[function(t){var e=t.h,i=t.s,s=t.v,r=t.a,n=void 0===r?1:r;if(!Gd(e)||!Gd(i)||!Gd(s))return null;var o,a=(o={h:Number(e),s:Number(i),v:Number(s),a:Number(n)},{h:Yd(o.h),s:Wd(o.s,0,100),v:Wd(o.v,0,100),a:Wd(o.a)});return qd(a)},"hsv"]]},np=function(t,e){for(var i=0;i<e.length;i++){var s=e[i][0](t);if(s)return[s,e[i][1]]}return[null,void 0]},op=function(t,e){var i=Qd(t);return{h:i.h,s:Wd(i.s+100*e,0,100),l:i.l,a:i.a}},ap=function(t){return(299*t.r+587*t.g+114*t.b)/1e3/255},lp=function(t,e){var i=Qd(t);return{h:i.h,s:i.s,l:Wd(i.l+100*e,0,100),a:i.a}},hp=function(){function t(t){this.parsed=function(t){return"string"==typeof t?np(t.trim(),rp.string):"object"==typeof t&&null!==t?np(t,rp.object):[null,void 0]}(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return t.prototype.isValid=function(){return null!==this.parsed},t.prototype.brightness=function(){return Xd(ap(this.rgba),2)},t.prototype.isDark=function(){return ap(this.rgba)<.5},t.prototype.isLight=function(){return ap(this.rgba)>=.5},t.prototype.toHex=function(){return e=(t=$d(this.rgba)).r,i=t.g,s=t.b,n=(r=t.a)<1?zd(Xd(255*r)):"","#"+zd(e)+zd(i)+zd(s)+n;var t,e,i,s,r,n},t.prototype.toRgb=function(){return $d(this.rgba)},t.prototype.toRgbString=function(){return e=(t=$d(this.rgba)).r,i=t.g,s=t.b,(r=t.a)<1?"rgba("+e+", "+i+", "+s+", "+r+")":"rgb("+e+", "+i+", "+s+")";var t,e,i,s,r},t.prototype.toHsl=function(){return Kd(Qd(this.rgba))},t.prototype.toHslString=function(){return e=(t=Kd(Qd(this.rgba))).h,i=t.s,s=t.l,(r=t.a)<1?"hsla("+e+", "+i+"%, "+s+"%, "+r+")":"hsl("+e+", "+i+"%, "+s+"%)";var t,e,i,s,r},t.prototype.toHsv=function(){return t=Vd(this.rgba),{h:Xd(t.h),s:Xd(t.s),v:Xd(t.v),a:Xd(t.a,3)};var t},t.prototype.invert=function(){return up({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},t.prototype.saturate=function(t){return void 0===t&&(t=.1),up(op(this.rgba,t))},t.prototype.desaturate=function(t){return void 0===t&&(t=.1),up(op(this.rgba,-t))},t.prototype.grayscale=function(){return up(op(this.rgba,-1))},t.prototype.lighten=function(t){return void 0===t&&(t=.1),up(lp(this.rgba,t))},t.prototype.darken=function(t){return void 0===t&&(t=.1),up(lp(this.rgba,-t))},t.prototype.rotate=function(t){return void 0===t&&(t=15),this.hue(this.hue()+t)},t.prototype.alpha=function(t){return"number"==typeof t?up({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):Xd(this.rgba.a,3);var e},t.prototype.hue=function(t){var e=Qd(this.rgba);return"number"==typeof t?up({h:t,s:e.s,l:e.l,a:e.a}):Xd(e.h)},t.prototype.isEqual=function(t){return this.toHex()===up(t).toHex()},t}(),up=function(t){return t instanceof hp?t:new hp(t)},cp=[];Dd=[function(t,e){var i={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},s={};for(var r in i)s[i[r]]=r;var n={};t.prototype.toName=function(e){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var r,o,a=s[this.toHex()];if(a)return a;if(null==e?void 0:e.closest){var l=this.toRgb(),h=1/0,u="black";if(!n.length)for(var c in i)n[c]=new t(i[c]).toRgb();for(var d in i){var p=(r=l,o=n[d],Math.pow(r.r-o.r,2)+Math.pow(r.g-o.g,2)+Math.pow(r.b-o.b,2));p<h&&(h=p,u=d)}return u}},e.string.push([function(e){var s=e.toLowerCase(),r="transparent"===s?"#0000":i[s];return r?new t(r).toRgb():null},"name"])}],Dd.forEach(function(t){cp.indexOf(t)<0&&(t(hp,rp),cp.push(t))});const dp=class t{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(t){return this.value=t,this}set value(e){if(e instanceof t)this._value=this.cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(null===e)throw new Error("Cannot set PIXI.Color#value to null");(null===this._value||!this.isSourceEqual(this._value,e))&&(this.normalize(e),this._value=this.cloneSource(e))}}get value(){return this._value}cloneSource(t){return"string"==typeof t||"number"==typeof t||t instanceof Number||null===t?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):"object"==typeof t&&null!==t?{...t}:t}isSourceEqual(t,e){const i=typeof t;if(i!==typeof e)return!1;if("number"===i||"string"===i||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length===e.length&&t.every((t,i)=>t===e[i]);if(null!==t&&null!==e){const i=Object.keys(t),s=Object.keys(e);return i.length===s.length&&i.every(i=>t[i]===e[i])}return t===e}toRgba(){const[t,e,i,s]=this._components;return{r:t,g:e,b:i,a:s}}toRgb(){const[t,e,i]=this._components;return{r:t,g:e,b:i}}toRgbaString(){const[t,e,i]=this.toUint8RgbArray();return`rgba(${t},${e},${i},${this.alpha})`}toUint8RgbArray(t){const[e,i,s]=this._components;return(t=t??[])[0]=Math.round(255*e),t[1]=Math.round(255*i),t[2]=Math.round(255*s),t}toRgbArray(t){t=t??[];const[e,i,s]=this._components;return t[0]=e,t[1]=i,t[2]=s,t}toNumber(){return this._int}toLittleEndianNumber(){const t=this._int;return(t>>16)+(65280&t)+((255&t)<<16)}multiply(e){const[i,s,r,n]=t.temp.setValue(e)._components;return this._components[0]*=i,this._components[1]*=s,this._components[2]*=r,this._components[3]*=n,this.refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this.refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(1===t)return(255<<24)+this._int;if(0===t)return e?0:this._int;let i=this._int>>16&255,s=this._int>>8&255,r=255&this._int;return e&&(i=i*t+.5|0,s=s*t+.5|0,r=r*t+.5|0),(255*t<<24)+(i<<16)+(s<<8)+r}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const t=Math.round(255*this._components[3]).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(t){return this._components[3]=this._clamp(t),this}round(t){const[e,i,s]=this._components;return this._components[0]=Math.round(e*t)/t,this._components[1]=Math.round(i*t)/t,this._components[2]=Math.round(s*t)/t,this.refreshInt(),this._value=null,this}toArray(t){t=t??[];const[e,i,s,r]=this._components;return t[0]=e,t[1]=i,t[2]=s,t[3]=r,t}normalize(e){let i,s,r,n;if(("number"==typeof e||e instanceof Number)&&e>=0&&e<=16777215){i=(e>>16&255)/255,s=(e>>8&255)/255,r=(255&e)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[i,s,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[i,s,r,n=255]=e,i/=255,s/=255,r/=255,n/=255;else if("string"==typeof e||"object"==typeof e){if("string"==typeof e){const i=t.HEX_PATTERN.exec(e);i&&(e=`#${i[2]}`)}const o=up(e);o.isValid()&&(({r:i,g:s,b:r,a:n}=o.rgba),i/=255,s/=255,r/=255)}if(void 0===i)throw new Error(`Unable to convert color ${e}`);this._components[0]=i,this._components[1]=s,this._components[2]=r,this._components[3]=n,this.refreshInt()}refreshInt(){this._clamp(this._components);const[t,e,i]=this._components;this._int=(255*t<<16)+(255*e<<8)+(255*i|0)}_clamp(t,e=0,i=1){return"number"==typeof t?Math.min(Math.max(t,e),i):(t.forEach((s,r)=>{t[r]=Math.min(Math.max(s,e),i)}),t)}};dp.shared=new dp,dp.temp=new dp,dp.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let pp=dp;const fp=function(){const t=[],e=[];for(let s=0;s<32;s++)t[s]=s,e[s]=s;t[mh.NORMAL_NPM]=mh.NORMAL,t[mh.ADD_NPM]=mh.ADD,t[mh.SCREEN_NPM]=mh.SCREEN,e[mh.NORMAL]=mh.NORMAL_NPM,e[mh.ADD]=mh.ADD_NPM,e[mh.SCREEN]=mh.SCREEN_NPM;const i=[];return i.push(e),i.push(t),i}();const mp=/^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i;function gp(t){if(4===t.BYTES_PER_ELEMENT)return t instanceof Float32Array?"Float32Array":t instanceof Uint32Array?"Uint32Array":"Int32Array";if(2===t.BYTES_PER_ELEMENT){if(t instanceof Uint16Array)return"Uint16Array"}else if(1===t.BYTES_PER_ELEMENT&&t instanceof Uint8Array)return"Uint8Array";return null}const yp={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array};function vp(t){return t+=0===t?1:0,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1}function xp(t){return!(t&t-1||!t)}function bp(t){let e=(t>65535?1:0)<<4,i=((t>>>=e)>255?1:0)<<3;return e|=i,i=((t>>>=i)>15?1:0)<<2,e|=i,i=((t>>>=i)>3?1:0)<<1,e|=i,e|(t>>>=i)>>1}function wp(t,e,i){const s=t.length;let r;if(e>=s||0===i)return;const n=s-(i=e+i>s?s-e:i);for(r=e;r<n;++r)t[r]=t[r+i];t.length=n}function _p(t){return 0===t?0:t<0?-1:1}let Pp=0;function Ep(){return++Pp}const Tp=class{constructor(t,e,i,s){this.left=t,this.top=e,this.right=i,this.bottom=s}get width(){return this.right-this.left}get height(){return this.bottom-this.top}isEmpty(){return this.left===this.right||this.top===this.bottom}};Tp.EMPTY=new Tp(0,0,0,0);let Ap=Tp;const Ip={},Sp=/* @__PURE__ */Object.create(null),Cp=/* @__PURE__ */Object.create(null);function Mp(){let t;for(t in Sp)delete Sp[t];for(t in Cp)delete Cp[t]}class Op{constructor(t,e,i){this._canvas=Oh.ADAPTER.createCanvas(),this._context=this._canvas.getContext("2d"),this.resolution=i||Oh.RESOLUTION,this.resize(t,e)}clear(){this._checkDestroyed(),this._context.setTransform(1,0,0,1,0,0),this._context.clearRect(0,0,this._canvas.width,this._canvas.height)}resize(t,e){this._checkDestroyed(),this._canvas.width=Math.round(t*this.resolution),this._canvas.height=Math.round(e*this.resolution)}destroy(){this._context=null,this._canvas=null}get width(){return this._checkDestroyed(),this._canvas.width}set width(t){this._checkDestroyed(),this._canvas.width=Math.round(t)}get height(){return this._checkDestroyed(),this._canvas.height}set height(t){this._checkDestroyed(),this._canvas.height=Math.round(t)}get canvas(){return this._checkDestroyed(),this._canvas}get context(){return this._checkDestroyed(),this._context}_checkDestroyed(){if(null===this._canvas)throw new TypeError("The CanvasRenderTarget has already been destroyed")}}function Np(t,e,i){for(let s=0,r=4*i*e;s<e;++s,r+=4)if(0!==t[r+3])return!1;return!0}function Lp(t,e,i,s,r){const n=4*e;for(let o=s,a=s*n+4*i;o<=r;++o,a+=n)if(0!==t[a+3])return!1;return!0}function Rp(t){const{width:e,height:i}=t,s=t.getContext("2d",{willReadFrequently:!0});if(null===s)throw new TypeError("Failed to get canvas 2D context");const r=s.getImageData(0,0,e,i).data;let n=0,o=0,a=e-1,l=i-1;for(;o<i&&Np(r,e,o);)++o;if(o===i)return Ap.EMPTY;for(;Np(r,e,l);)--l;for(;Lp(r,e,n,o,l);)++n;for(;Lp(r,e,a,o,l);)--a;return++a,++l,new Ap(n,o,a,l)}function Bp(t){const e=Rp(t),{width:i,height:s}=e;let r=null;if(!e.isEmpty()){const n=t.getContext("2d");if(null===n)throw new TypeError("Failed to get canvas 2D context");r=n.getImageData(e.left,e.top,i,s)}return{width:i,height:s,data:r}}function kp(t,e=globalThis.location){if(t.startsWith("data:"))return"";e=e||globalThis.location;const i=new URL(t,document.baseURI);return i.hostname!==e.hostname||i.port!==e.port||i.protocol!==e.protocol?"anonymous":""}function Fp(t,e=1){const i=Oh.RETINA_PREFIX?.exec(t);return i?parseFloat(i[1]):e}const Dp=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,BaseTextureCache:Cp,BoundingBox:Ap,CanvasRenderTarget:Op,DATA_URI:mp,EventEmitter:Qh,ProgramCache:Ip,TextureCache:Sp,clearTextureCache:Mp,correctBlendMode:function(t,e){return fp[e?1:0][t]},createIndicesForQuads:function(t,e=null){const i=6*t;if((e=e||new Uint16Array(i)).length!==i)throw new Error(`Out buffer length is incorrect, got ${e.length} and expected ${i}`);for(let s=0,r=0;s<i;s+=6,r+=4)e[s+0]=r+0,e[s+1]=r+1,e[s+2]=r+2,e[s+3]=r+0,e[s+4]=r+2,e[s+5]=r+3;return e},decomposeDataUri:function(t){const e=mp.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,charset:e[3]?e[3].toLowerCase():void 0,encoding:e[4]?e[4].toLowerCase():void 0,data:e[5]}},deprecation:Md,destroyTextureCache:function(){let t;for(t in Sp)Sp[t].destroy();for(t in Cp)Cp[t].destroy()},detectVideoAlphaMode:async function(){return Bd??(Bd=(async()=>{const t=document.createElement("canvas").getContext("webgl");if(!t)return Eh.UNPACK;const e=await new Promise(t=>{const e=document.createElement("video");e.onloadeddata=()=>t(e),e.onerror=()=>t(null),e.autoplay=!1,e.crossOrigin="anonymous",e.preload="auto",e.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",e.load()});if(!e)return Eh.UNPACK;const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i);const s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.NONE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e);const r=new Uint8Array(4);return t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,r),t.deleteFramebuffer(s),t.deleteTexture(i),t.getExtension("WEBGL_lose_context")?.loseContext(),r[0]<=r[3]?Eh.PMA:Eh.UNPACK})()),Bd},determineCrossOrigin:kp,earcut:Nt,getBufferType:gp,getCanvasBoundingBox:Rp,getResolutionOfUrl:Fp,hex2rgb:function(t,e=[]){return Md("7.2.0","utils.hex2rgb is deprecated, use Color#toRgbArray instead"),pp.shared.setValue(t).toRgbArray(e)},hex2string:function(t){return Md("7.2.0","utils.hex2string is deprecated, use Color#toHex instead"),pp.shared.setValue(t).toHex()},interleaveTypedArrays:function(t,e){let i=0,s=0;const r={};for(let l=0;l<t.length;l++)s+=e[l],i+=t[l].length;const n=new ArrayBuffer(4*i);let o=null,a=0;for(let l=0;l<t.length;l++){const i=e[l],h=t[l],u=gp(h);r[u]||(r[u]=new yp[u](n)),o=r[u];for(let t=0;t<h.length;t++){o[(t/i|0)*s+a+t%i]=h[t]}a+=i}return new Float32Array(n)},isMobile:qh,isPow2:xp,isWebGLSupported:Fd,log2:bp,nextPow2:vp,path:Rd,premultiplyBlendMode:fp,premultiplyRgba:function(t,e,i,s=!0){return Md("7.2.0","utils.premultiplyRgba has moved to Color.premultiply"),pp.shared.setValue(t).premultiply(e,s).toArray(i??new Float32Array(4))},premultiplyTint:function(t,e){return Md("7.2.0","utils.premultiplyTint has moved to Color.toPremultiplied"),pp.shared.setValue(t).toPremultiplied(e)},premultiplyTintToRgba:function(t,e,i,s=!0){return Md("7.2.0","utils.premultiplyTintToRgba has moved to Color.premultiply"),pp.shared.setValue(t).premultiply(e,s).toArray(i??new Float32Array(4))},removeItems:wp,rgb2hex:function(t){return Md("7.2.0","utils.rgb2hex is deprecated, use Color#toNumber instead"),pp.shared.setValue(t).toNumber()},sayHello:function(){Md("7.0.0",'sayHello is deprecated, please use Renderer\'s "hello" option')},sign:_p,skipHello:function(){Md("7.0.0","skipHello is deprecated, please use settings.RENDER_OPTIONS.hello")},string2hex:function(t){return Md("7.2.0","utils.string2hex is deprecated, use Color#toNumber instead"),pp.shared.setValue(t).toNumber()},trimCanvas:Bp,uid:Ep,url:Od},Symbol.toStringTag,{value:"Module"}));var Up=/* @__PURE__ */(t=>(t.Renderer="renderer",t.Application="application",t.RendererSystem="renderer-webgl-system",t.RendererPlugin="renderer-webgl-plugin",t.CanvasRendererSystem="renderer-canvas-system",t.CanvasRendererPlugin="renderer-canvas-plugin",t.Asset="asset",t.LoadParser="load-parser",t.ResolveParser="resolve-parser",t.CacheParser="cache-parser",t.DetectionParser="detection-parser",t))(Up||{});const Gp=t=>{if("function"==typeof t||"object"==typeof t&&t.extension){if(!t.extension)throw new Error("Extension class must have an extension object");t={..."object"!=typeof t.extension?{type:t.extension}:t.extension,ref:t}}if("object"!=typeof t)throw new Error("Invalid extension type");return"string"==typeof(t={...t}).type&&(t.type=[t.type]),t},Xp=(t,e)=>Gp(t).priority??e,Wp={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...t){return t.map(Gp).forEach(t=>{t.type.forEach(e=>this._removeHandlers[e]?.(t))}),this},add(...t){return t.map(Gp).forEach(t=>{t.type.forEach(e=>{const i=this._addHandlers,s=this._queue;i[e]?i[e]?.(t):(s[e]=s[e]||[],s[e]?.push(t))})}),this},handle(t,e,i){const s=this._addHandlers,r=this._removeHandlers;if(s[t]||r[t])throw new Error(`Extension type ${t} already has a handler`);s[t]=e,r[t]=i;const n=this._queue;return n[t]&&(n[t]?.forEach(t=>e(t)),delete n[t]),this},handleByMap(t,e){return this.handle(t,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByList(t,e,i=-1){return this.handle(t,t=>{e.includes(t.ref)||(e.push(t.ref),e.sort((t,e)=>Xp(e,i)-Xp(t,i)))},t=>{const i=e.indexOf(t.ref);-1!==i&&e.splice(i,1)})}};class Yp{constructor(t){"number"==typeof t?this.rawBinaryData=new ArrayBuffer(t):t instanceof Uint8Array?this.rawBinaryData=t.buffer:this.rawBinaryData=t,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData)}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get uint16View(){return this._uint16View||(this._uint16View=new Uint16Array(this.rawBinaryData)),this._uint16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}view(t){return this[`${t}View`]}destroy(){this.rawBinaryData=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._uint16View=null,this._int32View=null,this.uint32View=null,this.float32View=null}static sizeOf(t){switch(t){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${t} isn't a valid view type`)}}}const Hp=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join("\n");function $p(t){let e="";for(let i=0;i<t;++i)i>0&&(e+="\nelse "),i<t-1&&(e+=`if(test == ${i}.0){}`);return e}class jp{constructor(){this.data=0,this.blendMode=mh.NORMAL,this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(1&this.data)}set blend(t){!!(1&this.data)!==t&&(this.data^=1)}get offsets(){return!!(2&this.data)}set offsets(t){!!(2&this.data)!==t&&(this.data^=2)}get culling(){return!!(4&this.data)}set culling(t){!!(4&this.data)!==t&&(this.data^=4)}get depthTest(){return!!(8&this.data)}set depthTest(t){!!(8&this.data)!==t&&(this.data^=8)}get depthMask(){return!!(32&this.data)}set depthMask(t){!!(32&this.data)!==t&&(this.data^=32)}get clockwiseFrontFace(){return!!(16&this.data)}set clockwiseFrontFace(t){!!(16&this.data)!==t&&(this.data^=16)}get blendMode(){return this._blendMode}set blendMode(t){this.blend=t!==mh.NONE,this._blendMode=t}get polygonOffset(){return this._polygonOffset}set polygonOffset(t){this.offsets=!!t,this._polygonOffset=t}static for2d(){const t=new jp;return t.depthTest=!1,t.blend=!0,t}}jp.prototype.toString=function(){return`[@pixi/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`};const zp=[];function Vp(t,e){if(!t)return null;let i="";if("string"==typeof t){const e=/\.(\w{3,4})(?:$|\?|#)/i.exec(t);e&&(i=e[1].toLowerCase())}for(let s=zp.length-1;s>=0;--s){const r=zp[s];if(r.test&&r.test(t,i))return new r(t,e)}throw new Error("Unrecognized source type to auto-detect Resource")}class qp{constructor(t){this.items=[],this._name=t,this._aliasCount=0}emit(t,e,i,s,r,n,o,a){if(arguments.length>8)throw new Error("max arguments reached");const{name:l,items:h}=this;this._aliasCount++;for(let u=0,c=h.length;u<c;u++)h[u][l](t,e,i,s,r,n,o,a);return h===this.items&&this._aliasCount--,this}ensureNonAliasedItems(){this._aliasCount>0&&this.items.length>1&&(this._aliasCount=0,this.items=this.items.slice(0))}add(t){return t[this._name]&&(this.ensureNonAliasedItems(),this.remove(t),this.items.push(t)),this}remove(t){const e=this.items.indexOf(t);return-1!==e&&(this.ensureNonAliasedItems(),this.items.splice(e,1)),this}contains(t){return this.items.includes(t)}removeAll(){return this.ensureNonAliasedItems(),this.items.length=0,this}destroy(){this.removeAll(),this.items.length=0,this._name=""}get empty(){return 0===this.items.length}get name(){return this._name}}Object.defineProperties(qp.prototype,{dispatch:{value:qp.prototype.emit},run:{value:qp.prototype.emit}});class Jp{constructor(t=0,e=0){this._width=t,this._height=e,this.destroyed=!1,this.internal=!1,this.onResize=new qp("setRealSize"),this.onUpdate=new qp("update"),this.onError=new qp("onError")}bind(t){this.onResize.add(t),this.onUpdate.add(t),this.onError.add(t),(this._width||this._height)&&this.onResize.emit(this._width,this._height)}unbind(t){this.onResize.remove(t),this.onUpdate.remove(t),this.onError.remove(t)}resize(t,e){(t!==this._width||e!==this._height)&&(this._width=t,this._height=e,this.onResize.emit(t,e))}get valid(){return!!this._width&&!!this._height}update(){this.destroyed||this.onUpdate.emit()}load(){return Promise.resolve(this)}get width(){return this._width}get height(){return this._height}style(t,e,i){return!1}dispose(){}destroy(){this.destroyed||(this.destroyed=!0,this.dispose(),this.onError.removeAll(),this.onError=null,this.onResize.removeAll(),this.onResize=null,this.onUpdate.removeAll(),this.onUpdate=null)}static test(t,e){return!1}}class Kp extends Jp{constructor(t,e){const{width:i,height:s}=e||{};if(!i||!s)throw new Error("BufferResource width or height invalid");super(i,s),this.data=t,this.unpackAlignment=e.unpackAlignment??4}upload(t,e,i){const s=t.gl;s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.alphaMode===Eh.UNPACK);const r=e.realWidth,n=e.realHeight;return i.width===r&&i.height===n?s.texSubImage2D(e.target,0,0,0,r,n,e.format,i.type,this.data):(i.width=r,i.height=n,s.texImage2D(e.target,0,i.internalFormat,r,n,0,e.format,i.type,this.data)),!0}dispose(){this.data=null}static test(t){return null===t||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array}}const Zp={scaleMode:wh.NEAREST,alphaMode:Eh.NPM},Qp=class t extends Qh{constructor(e=null,i=null){super(),i=Object.assign({},t.defaultOptions,i);const{alphaMode:s,mipmap:r,anisotropicLevel:n,scaleMode:o,width:a,height:l,wrapMode:h,format:u,type:c,target:d,resolution:p,resourceOptions:f}=i;e&&!(e instanceof Jp)&&((e=Vp(e,f)).internal=!0),this.resolution=p||Oh.RESOLUTION,this.width=Math.round((a||0)*this.resolution)/this.resolution,this.height=Math.round((l||0)*this.resolution)/this.resolution,this._mipmap=r,this.anisotropicLevel=n,this._wrapMode=h,this._scaleMode=o,this.format=u,this.type=c,this.target=d,this.alphaMode=s,this.uid=Ep(),this.touched=0,this.isPowerOfTwo=!1,this._refreshPOT(),this._glTextures={},this.dirtyId=0,this.dirtyStyleId=0,this.cacheId=null,this.valid=a>0&&l>0,this.textureCacheIds=[],this.destroyed=!1,this.resource=null,this._batchEnabled=0,this._batchLocation=0,this.parentTextureArray=null,this.setResource(e)}get realWidth(){return Math.round(this.width*this.resolution)}get realHeight(){return Math.round(this.height*this.resolution)}get mipmap(){return this._mipmap}set mipmap(t){this._mipmap!==t&&(this._mipmap=t,this.dirtyStyleId++)}get scaleMode(){return this._scaleMode}set scaleMode(t){this._scaleMode!==t&&(this._scaleMode=t,this.dirtyStyleId++)}get wrapMode(){return this._wrapMode}set wrapMode(t){this._wrapMode!==t&&(this._wrapMode=t,this.dirtyStyleId++)}setStyle(t,e){let i;return void 0!==t&&t!==this.scaleMode&&(this.scaleMode=t,i=!0),void 0!==e&&e!==this.mipmap&&(this.mipmap=e,i=!0),i&&this.dirtyStyleId++,this}setSize(t,e,i){return i=i||this.resolution,this.setRealSize(t*i,e*i,i)}setRealSize(t,e,i){return this.resolution=i||this.resolution,this.width=Math.round(t)/this.resolution,this.height=Math.round(e)/this.resolution,this._refreshPOT(),this.update(),this}_refreshPOT(){this.isPowerOfTwo=xp(this.realWidth)&&xp(this.realHeight)}setResolution(t){const e=this.resolution;return e===t||(this.resolution=t,this.valid&&(this.width=Math.round(this.width*e)/t,this.height=Math.round(this.height*e)/t,this.emit("update",this)),this._refreshPOT()),this}setResource(t){if(this.resource===t)return this;if(this.resource)throw new Error("Resource can be set only once");return t.bind(this),this.resource=t,this}update(){this.valid?(this.dirtyId++,this.dirtyStyleId++,this.emit("update",this)):this.width>0&&this.height>0&&(this.valid=!0,this.emit("loaded",this),this.emit("update",this))}onError(t){this.emit("error",this,t)}destroy(){this.resource&&(this.resource.unbind(this),this.resource.internal&&this.resource.destroy(),this.resource=null),this.cacheId&&(delete Cp[this.cacheId],delete Sp[this.cacheId],this.cacheId=null),this.valid=!1,this.dispose(),t.removeFromCache(this),this.textureCacheIds=null,this.destroyed=!0,this.emit("destroyed",this),this.removeAllListeners()}dispose(){this.emit("dispose",this)}castToBaseTexture(){return this}static from(e,i,s=Oh.STRICT_TEXTURE_CACHE){const r="string"==typeof e;let n=null;if(r)n=e;else{if(!e._pixiId){const t=i?.pixiIdPrefix||"pixiid";e._pixiId=`${t}_${Ep()}`}n=e._pixiId}let o=Cp[n];if(r&&s&&!o)throw new Error(`The cacheId "${n}" does not exist in BaseTextureCache.`);return o||(o=new t(e,i),o.cacheId=n,t.addToCache(o,n)),o}static fromBuffer(e,i,s,r){e=e||new Float32Array(i*s*4);const n=new Kp(e,{width:i,height:s,...r?.resourceOptions});let o,a;return e instanceof Float32Array?(o=yh.RGBA,a=xh.FLOAT):e instanceof Int32Array?(o=yh.RGBA_INTEGER,a=xh.INT):e instanceof Uint32Array?(o=yh.RGBA_INTEGER,a=xh.UNSIGNED_INT):e instanceof Int16Array?(o=yh.RGBA_INTEGER,a=xh.SHORT):e instanceof Uint16Array?(o=yh.RGBA_INTEGER,a=xh.UNSIGNED_SHORT):e instanceof Int8Array?(o=yh.RGBA,a=xh.BYTE):(o=yh.RGBA,a=xh.UNSIGNED_BYTE),n.internal=!0,new t(n,Object.assign({},Zp,{type:a,format:o},r))}static addToCache(t,e){e&&(t.textureCacheIds.includes(e)||t.textureCacheIds.push(e),Cp[e]&&Cp[e]!==t&&console.warn(`BaseTexture added to the cache with an id [${e}] that already had an entry`),Cp[e]=t)}static removeFromCache(t){if("string"==typeof t){const e=Cp[t];if(e){const i=e.textureCacheIds.indexOf(t);return i>-1&&e.textureCacheIds.splice(i,1),delete Cp[t],e}}else if(t?.textureCacheIds){for(let e=0;e<t.textureCacheIds.length;++e)delete Cp[t.textureCacheIds[e]];return t.textureCacheIds.length=0,t}return null}};Qp.defaultOptions={mipmap:Ph.POW2,anisotropicLevel:0,scaleMode:wh.LINEAR,wrapMode:_h.CLAMP,alphaMode:Eh.UNPACK,target:vh.TEXTURE_2D,format:yh.RGBA,type:xh.UNSIGNED_BYTE},Qp._globalBatch=0;let tf=Qp;class ef{constructor(){this.texArray=null,this.blend=0,this.type=gh.TRIANGLES,this.start=0,this.size=0,this.data=null}}let sf=0;class rf{constructor(t,e=!0,i=!1){this.data=t||new Float32Array(1),this._glBuffers={},this._updateID=0,this.index=i,this.static=e,this.id=sf++,this.disposeRunner=new qp("disposeBuffer")}update(t){t instanceof Array&&(t=new Float32Array(t)),this.data=t||this.data,this._updateID++}dispose(){this.disposeRunner.emit(this,!1)}destroy(){this.dispose(),this.data=null}set index(t){this.type=t?Mh.ELEMENT_ARRAY_BUFFER:Mh.ARRAY_BUFFER}get index(){return this.type===Mh.ELEMENT_ARRAY_BUFFER}static from(t){return t instanceof Array&&(t=new Float32Array(t)),new rf(t)}}class nf{constructor(t,e=0,i=!1,s=xh.FLOAT,r,n,o,a=1){this.buffer=t,this.size=e,this.normalized=i,this.type=s,this.stride=r,this.start=n,this.instance=o,this.divisor=a}destroy(){this.buffer=null}static from(t,e,i,s,r){return new nf(t,e,i,s,r)}}const of={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array};const af={5126:4,5123:2,5121:1};let lf=0;const hf={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Uint16Array:Uint16Array};class uf{constructor(t=[],e={}){this.buffers=t,this.indexBuffer=null,this.attributes=e,this.glVertexArrayObjects={},this.id=lf++,this.instanced=!1,this.instanceCount=1,this.disposeRunner=new qp("disposeGeometry"),this.refCount=0}addAttribute(t,e,i=0,s=!1,r,n,o,a=!1){if(!e)throw new Error("You must pass a buffer when creating an attribute");e instanceof rf||(e instanceof Array&&(e=new Float32Array(e)),e=new rf(e));const l=t.split("|");if(l.length>1){for(let t=0;t<l.length;t++)this.addAttribute(l[t],e,i,s,r);return this}let h=this.buffers.indexOf(e);return-1===h&&(this.buffers.push(e),h=this.buffers.length-1),this.attributes[t]=new nf(h,i,s,r,n,o,a),this.instanced=this.instanced||a,this}getAttribute(t){return this.attributes[t]}getBuffer(t){return this.buffers[this.getAttribute(t).buffer]}addIndex(t){return t instanceof rf||(t instanceof Array&&(t=new Uint16Array(t)),t=new rf(t)),t.type=Mh.ELEMENT_ARRAY_BUFFER,this.indexBuffer=t,this.buffers.includes(t)||this.buffers.push(t),this}getIndex(){return this.indexBuffer}interleave(){if(1===this.buffers.length||2===this.buffers.length&&this.indexBuffer)return this;const t=[],e=[],i=new rf;let s;for(s in this.attributes){const i=this.attributes[s],r=this.buffers[i.buffer];t.push(r.data),e.push(i.size*af[i.type]/4),i.buffer=0}for(i.data=function(t,e){let i=0,s=0;const r={};for(let l=0;l<t.length;l++)s+=e[l],i+=t[l].length;const n=new ArrayBuffer(4*i);let o=null,a=0;for(let l=0;l<t.length;l++){const i=e[l],h=t[l],u=gp(h);r[u]||(r[u]=new of[u](n)),o=r[u];for(let t=0;t<h.length;t++)o[(t/i|0)*s+a+t%i]=h[t];a+=i}return new Float32Array(n)}(t,e),s=0;s<this.buffers.length;s++)this.buffers[s]!==this.indexBuffer&&this.buffers[s].destroy();return this.buffers=[i],this.indexBuffer&&this.buffers.push(this.indexBuffer),this}getSize(){for(const t in this.attributes){const e=this.attributes[t];return this.buffers[e.buffer].data.length/(e.stride/4||e.size)}return 0}dispose(){this.disposeRunner.emit(this,!1)}destroy(){this.dispose(),this.buffers=null,this.indexBuffer=null,this.attributes=null}clone(){const t=new uf;for(let e=0;e<this.buffers.length;e++)t.buffers[e]=new rf(this.buffers[e].data.slice(0));for(const e in this.attributes){const i=this.attributes[e];t.attributes[e]=new nf(i.buffer,i.size,i.normalized,i.type,i.stride,i.start,i.instance)}return this.indexBuffer&&(t.indexBuffer=t.buffers[this.buffers.indexOf(this.indexBuffer)],t.indexBuffer.type=Mh.ELEMENT_ARRAY_BUFFER),t}static merge(t){const e=new uf,i=[],s=[],r=[];let n;for(let o=0;o<t.length;o++){n=t[o];for(let t=0;t<n.buffers.length;t++)s[t]=s[t]||0,s[t]+=n.buffers[t].data.length,r[t]=0}for(let o=0;o<n.buffers.length;o++)i[o]=new(hf[gp(n.buffers[o].data)])(s[o]),e.buffers[o]=new rf(i[o]);for(let o=0;o<t.length;o++){n=t[o];for(let t=0;t<n.buffers.length;t++)i[t].set(n.buffers[t].data,r[t]),r[t]+=n.buffers[t].data.length}if(e.attributes=n.attributes,n.indexBuffer){e.indexBuffer=e.buffers[n.buffers.indexOf(n.indexBuffer)],e.indexBuffer.type=Mh.ELEMENT_ARRAY_BUFFER;let i=0,s=0,r=0,o=0;for(let t=0;t<n.buffers.length;t++)if(n.buffers[t]!==n.indexBuffer){o=t;break}for(const t in n.attributes){const e=n.attributes[t];(0|e.buffer)===o&&(s+=e.size*af[e.type]/4)}for(let n=0;n<t.length;n++){const a=t[n].indexBuffer.data;for(let t=0;t<a.length;t++)e.indexBuffer.data[t+r]+=i;i+=t[n].buffers[o].data.length/s,r+=a.length}}return e}}class cf extends uf{constructor(t=!1){super(),this._buffer=new rf(null,t,!1),this._indexBuffer=new rf(null,t,!0),this.addAttribute("aVertexPosition",this._buffer,2,!1,xh.FLOAT).addAttribute("aTextureCoord",this._buffer,2,!1,xh.FLOAT).addAttribute("aColor",this._buffer,4,!0,xh.UNSIGNED_BYTE).addAttribute("aTextureId",this._buffer,1,!0,xh.FLOAT).addIndex(this._indexBuffer)}}const df=2*Math.PI,pf=180/Math.PI,ff=Math.PI/180;var mf=/* @__PURE__ */(t=>(t[t.POLY=0]="POLY",t[t.RECT=1]="RECT",t[t.CIRC=2]="CIRC",t[t.ELIP=3]="ELIP",t[t.RREC=4]="RREC",t))(mf||{});class gf{constructor(t=0,e=0){this.x=0,this.y=0,this.x=t,this.y=e}clone(){return new gf(this.x,this.y)}copyFrom(t){return this.set(t.x,t.y),this}copyTo(t){return t.set(this.x,this.y),t}equals(t){return t.x===this.x&&t.y===this.y}set(t=0,e=t){return this.x=t,this.y=e,this}}gf.prototype.toString=function(){return`[@pixi/math:Point x=${this.x} y=${this.y}]`};const yf=[new gf,new gf,new gf,new gf];class vf{constructor(t=0,e=0,i=0,s=0){this.x=Number(t),this.y=Number(e),this.width=Number(i),this.height=Number(s),this.type=mf.RECT}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}static get EMPTY(){return new vf(0,0,0,0)}clone(){return new vf(this.x,this.y,this.width,this.height)}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t}contains(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t<this.x+this.width&&e>=this.y&&e<this.y+this.height)}intersects(t,e){if(!e){const e=this.x<t.x?t.x:this.x;if((this.right>t.right?t.right:this.right)<=e)return!1;const i=this.y<t.y?t.y:this.y;return(this.bottom>t.bottom?t.bottom:this.bottom)>i}const i=this.left,s=this.right,r=this.top,n=this.bottom;if(s<=i||n<=r)return!1;const o=yf[0].set(t.left,t.top),a=yf[1].set(t.left,t.bottom),l=yf[2].set(t.right,t.top),h=yf[3].set(t.right,t.bottom);if(l.x<=o.x||a.y<=o.y)return!1;const u=Math.sign(e.a*e.d-e.b*e.c);if(0===u||(e.apply(o,o),e.apply(a,a),e.apply(l,l),e.apply(h,h),Math.max(o.x,a.x,l.x,h.x)<=i||Math.min(o.x,a.x,l.x,h.x)>=s||Math.max(o.y,a.y,l.y,h.y)<=r||Math.min(o.y,a.y,l.y,h.y)>=n))return!1;const c=u*(a.y-o.y),d=u*(o.x-a.x),p=c*i+d*r,f=c*s+d*r,m=c*i+d*n,g=c*s+d*n;if(Math.max(p,f,m,g)<=c*o.x+d*o.y||Math.min(p,f,m,g)>=c*h.x+d*h.y)return!1;const y=u*(o.y-l.y),v=u*(l.x-o.x),x=y*i+v*r,b=y*s+v*r,w=y*i+v*n,_=y*s+v*n;return!(Math.max(x,b,w,_)<=y*o.x+v*o.y||Math.min(x,b,w,_)>=y*h.x+v*h.y)}pad(t=0,e=t){return this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e,this}fit(t){const e=Math.max(this.x,t.x),i=Math.min(this.x+this.width,t.x+t.width),s=Math.max(this.y,t.y),r=Math.min(this.y+this.height,t.y+t.height);return this.x=e,this.width=Math.max(i-e,0),this.y=s,this.height=Math.max(r-s,0),this}ceil(t=1,e=.001){const i=Math.ceil((this.x+this.width-e)*t)/t,s=Math.ceil((this.y+this.height-e)*t)/t;return this.x=Math.floor((this.x+e)*t)/t,this.y=Math.floor((this.y+e)*t)/t,this.width=i-this.x,this.height=s-this.y,this}enlarge(t){const e=Math.min(this.x,t.x),i=Math.max(this.x+this.width,t.x+t.width),s=Math.min(this.y,t.y),r=Math.max(this.y+this.height,t.y+t.height);return this.x=e,this.width=i-e,this.y=s,this.height=r-s,this}}vf.prototype.toString=function(){return`[@pixi/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`};class xf{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.radius=i,this.type=mf.CIRC}clone(){return new xf(this.x,this.y,this.radius)}contains(t,e){if(this.radius<=0)return!1;const i=this.radius*this.radius;let s=this.x-t,r=this.y-e;return s*=s,r*=r,s+r<=i}getBounds(){return new vf(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}}xf.prototype.toString=function(){return`[@pixi/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`};class bf{constructor(t=0,e=0,i=0,s=0){this.x=t,this.y=e,this.width=i,this.height=s,this.type=mf.ELIP}clone(){return new bf(this.x,this.y,this.width,this.height)}contains(t,e){if(this.width<=0||this.height<=0)return!1;let i=(t-this.x)/this.width,s=(e-this.y)/this.height;return i*=i,s*=s,i+s<=1}getBounds(){return new vf(this.x-this.width,this.y-this.height,this.width,this.height)}}bf.prototype.toString=function(){return`[@pixi/math:Ellipse x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`};class wf{constructor(...t){let e=Array.isArray(t[0])?t[0]:t;if("number"!=typeof e[0]){const t=[];for(let i=0,s=e.length;i<s;i++)t.push(e[i].x,e[i].y);e=t}this.points=e,this.type=mf.POLY,this.closeStroke=!0}clone(){const t=this.points.slice(),e=new wf(t);return e.closeStroke=this.closeStroke,e}contains(t,e){let i=!1;const s=this.points.length/2;for(let r=0,n=s-1;r<s;n=r++){const s=this.points[2*r],o=this.points[2*r+1],a=this.points[2*n],l=this.points[2*n+1];o>e!=l>e&&t<(e-o)/(l-o)*(a-s)+s&&(i=!i)}return i}}wf.prototype.toString=function(){return`[@pixi/math:PolygoncloseStroke=${this.closeStroke}points=${this.points.reduce((t,e)=>`${t}, ${e}`,"")}]`};class _f{constructor(t=0,e=0,i=0,s=0,r=20){this.x=t,this.y=e,this.width=i,this.height=s,this.radius=r,this.type=mf.RREC}clone(){return new _f(this.x,this.y,this.width,this.height,this.radius)}contains(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(e>=this.y+i&&e<=this.y+this.height-i||t>=this.x+i&&t<=this.x+this.width-i)return!0;let s=t-(this.x+i),r=e-(this.y+i);const n=i*i;if(s*s+r*r<=n||(s=t-(this.x+this.width-i),s*s+r*r<=n)||(r=e-(this.y+this.height-i),s*s+r*r<=n)||(s=t-(this.x+i),s*s+r*r<=n))return!0}return!1}}_f.prototype.toString=function(){return`[@pixi/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`};class Pf{constructor(t=1,e=0,i=0,s=1,r=0,n=0){this.array=null,this.a=t,this.b=e,this.c=i,this.d=s,this.tx=r,this.ty=n}fromArray(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]}set(t,e,i,s,r,n){return this.a=t,this.b=e,this.c=i,this.d=s,this.tx=r,this.ty=n,this}toArray(t,e){this.array||(this.array=new Float32Array(9));const i=e||this.array;return t?(i[0]=this.a,i[1]=this.b,i[2]=0,i[3]=this.c,i[4]=this.d,i[5]=0,i[6]=this.tx,i[7]=this.ty,i[8]=1):(i[0]=this.a,i[1]=this.c,i[2]=this.tx,i[3]=this.b,i[4]=this.d,i[5]=this.ty,i[6]=0,i[7]=0,i[8]=1),i}apply(t,e){e=e||new gf;const i=t.x,s=t.y;return e.x=this.a*i+this.c*s+this.tx,e.y=this.b*i+this.d*s+this.ty,e}applyInverse(t,e){e=e||new gf;const i=1/(this.a*this.d+this.c*-this.b),s=t.x,r=t.y;return e.x=this.d*i*s+-this.c*i*r+(this.ty*this.c-this.tx*this.d)*i,e.y=this.a*i*r+-this.b*i*s+(-this.ty*this.a+this.tx*this.b)*i,e}translate(t,e){return this.tx+=t,this.ty+=e,this}scale(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this}rotate(t){const e=Math.cos(t),i=Math.sin(t),s=this.a,r=this.c,n=this.tx;return this.a=s*e-this.b*i,this.b=s*i+this.b*e,this.c=r*e-this.d*i,this.d=r*i+this.d*e,this.tx=n*e-this.ty*i,this.ty=n*i+this.ty*e,this}append(t){const e=this.a,i=this.b,s=this.c,r=this.d;return this.a=t.a*e+t.b*s,this.b=t.a*i+t.b*r,this.c=t.c*e+t.d*s,this.d=t.c*i+t.d*r,this.tx=t.tx*e+t.ty*s+this.tx,this.ty=t.tx*i+t.ty*r+this.ty,this}setTransform(t,e,i,s,r,n,o,a,l){return this.a=Math.cos(o+l)*r,this.b=Math.sin(o+l)*r,this.c=-Math.sin(o-a)*n,this.d=Math.cos(o-a)*n,this.tx=t-(i*this.a+s*this.c),this.ty=e-(i*this.b+s*this.d),this}prepend(t){const e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){const e=this.a,i=this.c;this.a=e*t.a+this.b*t.c,this.b=e*t.b+this.b*t.d,this.c=i*t.a+this.d*t.c,this.d=i*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this}decompose(t){const e=this.a,i=this.b,s=this.c,r=this.d,n=t.pivot,o=-Math.atan2(-s,r),a=Math.atan2(i,e),l=Math.abs(o+a);return l<1e-5||Math.abs(df-l)<1e-5?(t.rotation=a,t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=o,t.skew.y=a),t.scale.x=Math.sqrt(e*e+i*i),t.scale.y=Math.sqrt(s*s+r*r),t.position.x=this.tx+(n.x*e+n.y*s),t.position.y=this.ty+(n.x*i+n.y*r),t}invert(){const t=this.a,e=this.b,i=this.c,s=this.d,r=this.tx,n=t*s-e*i;return this.a=s/n,this.b=-e/n,this.c=-i/n,this.d=t/n,this.tx=(i*this.ty-s*r)/n,this.ty=-(t*this.ty-e*r)/n,this}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const t=new Pf;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyTo(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyFrom(t){return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.tx=t.tx,this.ty=t.ty,this}static get IDENTITY(){return new Pf}static get TEMP_MATRIX(){return new Pf}}Pf.prototype.toString=function(){return`[@pixi/math:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`};const Ef=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],Tf=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],Af=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],If=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Sf=[],Cf=[],Mf=Math.sign;!function(){for(let t=0;t<16;t++){const e=[];Sf.push(e);for(let i=0;i<16;i++){const s=Mf(Ef[t]*Ef[i]+Af[t]*Tf[i]),r=Mf(Tf[t]*Ef[i]+If[t]*Tf[i]),n=Mf(Ef[t]*Af[i]+Af[t]*If[i]),o=Mf(Tf[t]*Af[i]+If[t]*If[i]);for(let t=0;t<16;t++)if(Ef[t]===s&&Tf[t]===r&&Af[t]===n&&If[t]===o){e.push(t);break}}}for(let t=0;t<16;t++){const e=new Pf;e.set(Ef[t],Tf[t],Af[t],If[t],0,0),Cf.push(e)}}();const Of={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:t=>Ef[t],uY:t=>Tf[t],vX:t=>Af[t],vY:t=>If[t],inv:t=>8&t?15&t:7&-t,add:(t,e)=>Sf[t][e],sub:(t,e)=>Sf[t][Of.inv(e)],rotate180:t=>4^t,isVertical:t=>2==(3&t),byDirection:(t,e)=>2*Math.abs(t)<=Math.abs(e)?e>=0?Of.S:Of.N:2*Math.abs(e)<=Math.abs(t)?t>0?Of.E:Of.W:e>0?t>0?Of.SE:Of.SW:t>0?Of.NE:Of.NW,matrixAppendRotationInv:(t,e,i=0,s=0)=>{const r=Cf[Of.inv(e)];r.tx=i,r.ty=s,t.append(r)}};class Nf{constructor(t,e,i=0,s=0){this._x=i,this._y=s,this.cb=t,this.scope=e}clone(t=this.cb,e=this.scope){return new Nf(t,e,this._x,this._y)}set(t=0,e=t){return(this._x!==t||this._y!==e)&&(this._x=t,this._y=e,this.cb.call(this.scope)),this}copyFrom(t){return(this._x!==t.x||this._y!==t.y)&&(this._x=t.x,this._y=t.y,this.cb.call(this.scope)),this}copyTo(t){return t.set(this._x,this._y),t}equals(t){return t.x===this._x&&t.y===this._y}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}Nf.prototype.toString=function(){return`[@pixi/math:ObservablePoint x=${this.x} y=${this.y} scope=${this.scope}]`};const Lf=class{constructor(){this.worldTransform=new Pf,this.localTransform=new Pf,this.position=new Nf(this.onChange,this,0,0),this.scale=new Nf(this.onChange,this,1,1),this.pivot=new Nf(this.onChange,this,0,0),this.skew=new Nf(this.updateSkew,this,0,0),this._rotation=0,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._localID=0,this._currentLocalID=0,this._worldID=0,this._parentID=0}onChange(){this._localID++}updateSkew(){this._cx=Math.cos(this._rotation+this.skew.y),this._sx=Math.sin(this._rotation+this.skew.y),this._cy=-Math.sin(this._rotation-this.skew.x),this._sy=Math.cos(this._rotation-this.skew.x),this._localID++}updateLocalTransform(){const t=this.localTransform;this._localID!==this._currentLocalID&&(t.a=this._cx*this.scale.x,t.b=this._sx*this.scale.x,t.c=this._cy*this.scale.y,t.d=this._sy*this.scale.y,t.tx=this.position.x-(this.pivot.x*t.a+this.pivot.y*t.c),t.ty=this.position.y-(this.pivot.x*t.b+this.pivot.y*t.d),this._currentLocalID=this._localID,this._parentID=-1)}updateTransform(t){const e=this.localTransform;if(this._localID!==this._currentLocalID&&(e.a=this._cx*this.scale.x,e.b=this._sx*this.scale.x,e.c=this._cy*this.scale.y,e.d=this._sy*this.scale.y,e.tx=this.position.x-(this.pivot.x*e.a+this.pivot.y*e.c),e.ty=this.position.y-(this.pivot.x*e.b+this.pivot.y*e.d),this._currentLocalID=this._localID,this._parentID=-1),this._parentID!==t._worldID){const i=t.worldTransform,s=this.worldTransform;s.a=e.a*i.a+e.b*i.c,s.b=e.a*i.b+e.b*i.d,s.c=e.c*i.a+e.d*i.c,s.d=e.c*i.b+e.d*i.d,s.tx=e.tx*i.a+e.ty*i.c+i.tx,s.ty=e.tx*i.b+e.ty*i.d+i.ty,this._parentID=t._worldID,this._worldID++}}setFromMatrix(t){t.decompose(this),this._localID++}get rotation(){return this._rotation}set rotation(t){this._rotation!==t&&(this._rotation=t,this.updateSkew())}};Lf.IDENTITY=new Lf;let Rf=Lf;Rf.prototype.toString=function(){return`[@pixi/math:Transform position=(${this.position.x}, ${this.position.y}) rotation=${this.rotation} scale=(${this.scale.x}, ${this.scale.y}) skew=(${this.skew.x}, ${this.skew.y}) ]`};function Bf(t,e,i){const s=t.createShader(e);return t.shaderSource(s,i),t.compileShader(s),s}function kf(t){const e=new Array(t);for(let i=0;i<e.length;i++)e[i]=!1;return e}function Ff(t,e){switch(t){case"float":case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"vec2":return new Float32Array(2*e);case"vec3":return new Float32Array(3*e);case"vec4":return new Float32Array(4*e);case"ivec2":return new Int32Array(2*e);case"ivec3":return new Int32Array(3*e);case"ivec4":return new Int32Array(4*e);case"uvec2":return new Uint32Array(2*e);case"uvec3":return new Uint32Array(3*e);case"uvec4":return new Uint32Array(4*e);case"bool":return!1;case"bvec2":return kf(2*e);case"bvec3":return kf(3*e);case"bvec4":return kf(4*e);case"mat2":return new Float32Array([1,0,0,1]);case"mat3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const Df=[{test:t=>"float"===t.type&&1===t.size&&!t.isArray,code:t=>`\n if(uv["${t}"] !== ud["${t}"].value)\n {\n ud["${t}"].value = uv["${t}"]\n gl.uniform1f(ud["${t}"].location, uv["${t}"])\n }\n `},{test:(t,e)=>!("sampler2D"!==t.type&&"samplerCube"!==t.type&&"sampler2DArray"!==t.type||1!==t.size||t.isArray||null!=e&&void 0===e.castToBaseTexture),code:t=>`t = syncData.textureCount++;\n\n renderer.texture.bind(uv["${t}"], t);\n\n if(ud["${t}"].value !== t)\n {\n ud["${t}"].value = t;\n gl.uniform1i(ud["${t}"].location, t);\n; // eslint-disable-line max-len\n }`},{test:(t,e)=>"mat3"===t.type&&1===t.size&&!t.isArray&&void 0!==e.a,code:t=>`\n gl.uniformMatrix3fv(ud["${t}"].location, false, uv["${t}"].toArray(true));\n `,codeUbo:t=>`\n var ${t}_matrix = uv.${t}.toArray(true);\n\n data[offset] = ${t}_matrix[0];\n data[offset+1] = ${t}_matrix[1];\n data[offset+2] = ${t}_matrix[2];\n \n data[offset + 4] = ${t}_matrix[3];\n data[offset + 5] = ${t}_matrix[4];\n data[offset + 6] = ${t}_matrix[5];\n \n data[offset + 8] = ${t}_matrix[6];\n data[offset + 9] = ${t}_matrix[7];\n data[offset + 10] = ${t}_matrix[8];\n `},{test:(t,e)=>"vec2"===t.type&&1===t.size&&!t.isArray&&void 0!==e.x,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud["${t}"].location, v.x, v.y);\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n `},{test:t=>"vec2"===t.type&&1===t.size&&!t.isArray,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud["${t}"].location, v[0], v[1]);\n }\n `},{test:(t,e)=>"vec4"===t.type&&1===t.size&&!t.isArray&&void 0!==e.width,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud["${t}"].location, v.x, v.y, v.width, v.height)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n data[offset+2] = v.width;\n data[offset+3] = v.height;\n `},{test:(t,e)=>"vec4"===t.type&&1===t.size&&!t.isArray&&void 0!==e.red,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.alpha)\n {\n cv[0] = v.red;\n cv[1] = v.green;\n cv[2] = v.blue;\n cv[3] = v.alpha;\n gl.uniform4f(ud["${t}"].location, v.red, v.green, v.blue, v.alpha)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.red;\n data[offset+1] = v.green;\n data[offset+2] = v.blue;\n data[offset+3] = v.alpha;\n `},{test:(t,e)=>"vec3"===t.type&&1===t.size&&!t.isArray&&void 0!==e.red,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.a)\n {\n cv[0] = v.red;\n cv[1] = v.green;\n cv[2] = v.blue;\n \n gl.uniform3f(ud["${t}"].location, v.red, v.green, v.blue)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.red;\n data[offset+1] = v.green;\n data[offset+2] = v.blue;\n `},{test:t=>"vec4"===t.type&&1===t.size&&!t.isArray,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud["${t}"].location, v[0], v[1], v[2], v[3])\n }`}],Uf={float:"\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1f(location, v);\n }",vec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2f(location, v[0], v[1])\n }",vec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }",vec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(location, v[0], v[1], v[2], v[3]);\n }",int:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",ivec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }",ivec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }",ivec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }",uint:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1ui(location, v);\n }",uvec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2ui(location, v[0], v[1]);\n }",uvec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3ui(location, v[0], v[1], v[2]);\n }",uvec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4ui(location, v[0], v[1], v[2], v[3]);\n }",bool:"\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1i(location, v);\n }",bvec2:"\n if (cv[0] != v[0] || cv[1] != v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }",bvec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }",bvec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }",mat2:"gl.uniformMatrix2fv(location, false, v)",mat3:"gl.uniformMatrix3fv(location, false, v)",mat4:"gl.uniformMatrix4fv(location, false, v)",sampler2D:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",samplerCube:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",sampler2DArray:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }"},Gf={float:"gl.uniform1fv(location, v)",vec2:"gl.uniform2fv(location, v)",vec3:"gl.uniform3fv(location, v)",vec4:"gl.uniform4fv(location, v)",mat4:"gl.uniformMatrix4fv(location, false, v)",mat3:"gl.uniformMatrix3fv(location, false, v)",mat2:"gl.uniformMatrix2fv(location, false, v)",int:"gl.uniform1iv(location, v)",ivec2:"gl.uniform2iv(location, v)",ivec3:"gl.uniform3iv(location, v)",ivec4:"gl.uniform4iv(location, v)",uint:"gl.uniform1uiv(location, v)",uvec2:"gl.uniform2uiv(location, v)",uvec3:"gl.uniform3uiv(location, v)",uvec4:"gl.uniform4uiv(location, v)",bool:"gl.uniform1iv(location, v)",bvec2:"gl.uniform2iv(location, v)",bvec3:"gl.uniform3iv(location, v)",bvec4:"gl.uniform4iv(location, v)",sampler2D:"gl.uniform1iv(location, v)",samplerCube:"gl.uniform1iv(location, v)",sampler2DArray:"gl.uniform1iv(location, v)"};const Xf={};let Wf,Yf=Xf;function Hf(){if(!Wf){Wf=Ih.MEDIUM;const t=function(){if(Yf===Xf||Yf?.isContextLost()){const t=Oh.ADAPTER.createCanvas();let e;Oh.PREFER_ENV>=dh.WEBGL2&&(e=t.getContext("webgl2",{})),e||(e=t.getContext("webgl",{})||t.getContext("experimental-webgl",{}),e?e.getExtension("WEBGL_draw_buffers"):e=null),Yf=e}return Yf}();if(t&&t.getShaderPrecisionFormat){const e=t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT);e&&(Wf=e.precision?Ih.HIGH:Ih.MEDIUM)}}return Wf}function $f(t,e){const i=t.getShaderSource(e).split("\n").map((t,e)=>`${e}: ${t}`),s=t.getShaderInfoLog(e),r=s.split("\n"),n={},o=r.map(t=>parseFloat(t.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(t=>!(!t||n[t])&&(n[t]=!0,!0)),a=[""];o.forEach(t=>{i[t-1]=`%c${i[t-1]}%c`,a.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const l=i.join("\n");a[0]=l,console.error(s),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}const jf={float:1,vec2:2,vec3:3,vec4:4,int:1,ivec2:2,ivec3:3,ivec4:4,uint:1,uvec2:2,uvec3:3,uvec4:4,bool:1,bvec2:2,bvec3:3,bvec4:4,mat2:4,mat3:9,mat4:16,sampler2D:1};function zf(t){return jf[t]}let Vf=null;const qf={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"};function Jf(t,e){if(!Vf){const e=Object.keys(qf);Vf={};for(let i=0;i<e.length;++i){const s=e[i];Vf[t[s]]=qf[s]}}return Vf[e]}function Kf(t,e,i){if("precision"!==t.substring(0,9)){let s=e;return e===Ih.HIGH&&i!==Ih.HIGH&&(s=Ih.MEDIUM),`precision ${s} float;\n${t}`}return i!==Ih.HIGH&&"precision highp"===t.substring(0,15)?t.replace("precision highp","precision mediump"):t}let Zf;let Qf=0;const tm={},em=class t{constructor(e,i,s="pixi-shader",r={}){this.extra={},this.id=Qf++,this.vertexSrc=e||t.defaultVertexSrc,this.fragmentSrc=i||t.defaultFragmentSrc,this.vertexSrc=this.vertexSrc.trim(),this.fragmentSrc=this.fragmentSrc.trim(),this.extra=r,"#version"!==this.vertexSrc.substring(0,8)&&(s=s.replace(/\s+/g,"-"),tm[s]?(tm[s]++,s+=`-${tm[s]}`):tm[s]=1,this.vertexSrc=`#define SHADER_NAME ${s}\n${this.vertexSrc}`,this.fragmentSrc=`#define SHADER_NAME ${s}\n${this.fragmentSrc}`,this.vertexSrc=Kf(this.vertexSrc,t.defaultVertexPrecision,Ih.HIGH),this.fragmentSrc=Kf(this.fragmentSrc,t.defaultFragmentPrecision,Hf())),this.glPrograms={},this.syncUniforms=null}static get defaultVertexSrc(){return"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"}static get defaultFragmentSrc(){return"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"}static from(e,i,s){const r=e+i;let n=Ip[r];return n||(Ip[r]=n=new t(e,i,s)),n}};em.defaultVertexPrecision=Ih.HIGH,em.defaultFragmentPrecision=qh.apple.device?Ih.HIGH:Ih.MEDIUM;let im=em,sm=0;class rm{constructor(t,e,i){this.group=!0,this.syncUniforms={},this.dirtyId=0,this.id=sm++,this.static=!!e,this.ubo=!!i,t instanceof rf?(this.buffer=t,this.buffer.type=Mh.UNIFORM_BUFFER,this.autoManage=!1,this.ubo=!0):(this.uniforms=t,this.ubo&&(this.buffer=new rf(new Float32Array(1)),this.buffer.type=Mh.UNIFORM_BUFFER,this.autoManage=!0))}update(){this.dirtyId++,!this.autoManage&&this.buffer&&this.buffer.update()}add(t,e,i){if(this.ubo)throw new Error("[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them");this.uniforms[t]=new rm(e,i)}static from(t,e,i){return new rm(t,e,i)}static uboFrom(t,e){return new rm(t,e??!0,!0)}}class nm{constructor(t,e){this.uniformBindCount=0,this.program=t,this.uniformGroup=e?e instanceof rm?e:new rm(e):new rm({}),this.disposeRunner=new qp("disposeShader")}checkUniformExists(t,e){if(e.uniforms[t])return!0;for(const i in e.uniforms){const s=e.uniforms[i];if(!0===s.group&&this.checkUniformExists(t,s))return!0}return!1}destroy(){this.uniformGroup=null,this.disposeRunner.emit(this),this.disposeRunner.destroy()}get uniforms(){return this.uniformGroup.uniforms}static from(t,e,i){const s=im.from(t,e);return new nm(s,i)}}class om{constructor(t,e){if(this.vertexSrc=t,this.fragTemplate=e,this.programCache={},this.defaultGroupCache={},!e.includes("%count%"))throw new Error('Fragment template must contain "%count%".');if(!e.includes("%forloop%"))throw new Error('Fragment template must contain "%forloop%".')}generateShader(t){if(!this.programCache[t]){const e=new Int32Array(t);for(let s=0;s<t;s++)e[s]=s;this.defaultGroupCache[t]=rm.from({uSamplers:e},!0);let i=this.fragTemplate;i=i.replace(/%count%/gi,`${t}`),i=i.replace(/%forloop%/gi,this.generateSampleSrc(t)),this.programCache[t]=new im(this.vertexSrc,i)}const e={tint:new Float32Array([1,1,1,1]),translationMatrix:new Pf,default:this.defaultGroupCache[t]};return new nm(this.programCache[t],e)}generateSampleSrc(t){let e="";e+="\n",e+="\n";for(let i=0;i<t;i++)i>0&&(e+="\nelse "),i<t-1&&(e+=`if(vTextureId < ${i}.5)`),e+="\n{",e+=`\n\tcolor = texture2D(uSamplers[${i}], vTextureCoord);`,e+="\n}";return e+="\n",e+="\n",e}}class am{constructor(){this.elements=[],this.ids=[],this.count=0}clear(){for(let t=0;t<this.count;t++)this.elements[t]=null;this.count=0}}class lm{constructor(t){this.renderer=t}flush(){}destroy(){this.renderer=null}start(){}stop(){this.flush()}render(t){}}const hm=class t extends lm{constructor(e){super(e),this.setShaderGenerator(),this.geometryClass=cf,this.vertexSize=6,this.state=jp.for2d(),this.size=4*t.defaultBatchSize,this._vertexCount=0,this._indexCount=0,this._bufferedElements=[],this._bufferedTextures=[],this._bufferSize=0,this._shader=null,this._packedGeometries=[],this._packedGeometryPoolSize=2,this._flushId=0,this._aBuffers={},this._iBuffers={},this.maxTextures=1,this.renderer.on("prerender",this.onPrerender,this),e.runners.contextChange.add(this),this._dcIndex=0,this._aIndex=0,this._iIndex=0,this._attributeBuffer=null,this._indexBuffer=null,this._tempBoundTextures=[]}static get defaultMaxTextures(){return this._defaultMaxTextures=this._defaultMaxTextures??function(t){let e=!0;const i=Oh.ADAPTER.getNavigator();if(qh.tablet||qh.phone){if(qh.apple.device){const t=i.userAgent.match(/OS (\d+)_(\d+)?/);t&&parseInt(t[1],10)<11&&(e=!1)}if(qh.android.device){const t=i.userAgent.match(/Android\s([0-9.]*)/);t&&parseInt(t[1],10)<7&&(e=!1)}}return e?t:4}(32),this._defaultMaxTextures}static set defaultMaxTextures(t){this._defaultMaxTextures=t}static get canUploadSameBuffer(){return this._canUploadSameBuffer=this._canUploadSameBuffer??!qh.apple.device,this._canUploadSameBuffer}static set canUploadSameBuffer(t){this._canUploadSameBuffer=t}get MAX_TEXTURES(){return Md("7.1.0","BatchRenderer#MAX_TEXTURES renamed to BatchRenderer#maxTextures"),this.maxTextures}static get defaultVertexSrc(){return"precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"}static get defaultFragmentTemplate(){return"varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"}setShaderGenerator({vertex:e=t.defaultVertexSrc,fragment:i=t.defaultFragmentTemplate}={}){this.shaderGenerator=new om(e,i)}contextChange(){const e=this.renderer.gl;Oh.PREFER_ENV===dh.WEBGL_LEGACY?this.maxTextures=1:(this.maxTextures=Math.min(e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),t.defaultMaxTextures),this.maxTextures=function(t,e){if(0===t)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const i=e.createShader(e.FRAGMENT_SHADER);for(;;){const s=Hp.replace(/%forloop%/gi,$p(t));if(e.shaderSource(i,s),e.compileShader(i),e.getShaderParameter(i,e.COMPILE_STATUS))break;t=t/2|0}return t}(this.maxTextures,e)),this._shader=this.shaderGenerator.generateShader(this.maxTextures);for(let t=0;t<this._packedGeometryPoolSize;t++)this._packedGeometries[t]=new this.geometryClass;this.initFlushBuffers()}initFlushBuffers(){const{_drawCallPool:e,_textureArrayPool:i}=t,s=this.size/4,r=Math.floor(s/this.maxTextures)+1;for(;e.length<s;)e.push(new ef);for(;i.length<r;)i.push(new am);for(let t=0;t<this.maxTextures;t++)this._tempBoundTextures[t]=null}onPrerender(){this._flushId=0}render(t){t._texture.valid&&(this._vertexCount+t.vertexData.length/2>this.size&&this.flush(),this._vertexCount+=t.vertexData.length/2,this._indexCount+=t.indices.length,this._bufferedTextures[this._bufferSize]=t._texture.baseTexture,this._bufferedElements[this._bufferSize++]=t)}buildTexturesAndDrawCalls(){const{_bufferedTextures:e,maxTextures:i}=this,s=t._textureArrayPool,r=this.renderer.batch,n=this._tempBoundTextures,o=this.renderer.textureGC.count;let a=++tf._globalBatch,l=0,h=s[0],u=0;r.copyBoundTextures(n,i);for(let t=0;t<this._bufferSize;++t){const c=e[t];e[t]=null,c._batchEnabled!==a&&(h.count>=i&&(r.boundArray(h,n,a,i),this.buildDrawCalls(h,u,t),u=t,h=s[++l],++a),c._batchEnabled=a,c.touched=o,h.elements[h.count++]=c)}h.count>0&&(r.boundArray(h,n,a,i),this.buildDrawCalls(h,u,this._bufferSize),++l,++a);for(let t=0;t<n.length;t++)n[t]=null;tf._globalBatch=a}buildDrawCalls(e,i,s){const{_bufferedElements:r,_attributeBuffer:n,_indexBuffer:o,vertexSize:a}=this,l=t._drawCallPool;let h=this._dcIndex,u=this._aIndex,c=this._iIndex,d=l[h];d.start=this._iIndex,d.texArray=e;for(let t=i;t<s;++t){const s=r[t],p=s._texture.baseTexture,f=fp[p.alphaMode?1:0][s.blendMode];r[t]=null,i<t&&d.blend!==f&&(d.size=c-d.start,i=t,d=l[++h],d.texArray=e,d.start=c),this.packInterleavedGeometry(s,n,o,u,c),u+=s.vertexData.length/2*a,c+=s.indices.length,d.blend=f}i<s&&(d.size=c-d.start,++h),this._dcIndex=h,this._aIndex=u,this._iIndex=c}bindAndClearTexArray(t){const e=this.renderer.texture;for(let i=0;i<t.count;i++)e.bind(t.elements[i],t.ids[i]),t.elements[i]=null;t.count=0}updateGeometry(){const{_packedGeometries:e,_attributeBuffer:i,_indexBuffer:s}=this;t.canUploadSameBuffer?(e[this._flushId]._buffer.update(i.rawBinaryData),e[this._flushId]._indexBuffer.update(s),this.renderer.geometry.updateBuffers()):(this._packedGeometryPoolSize<=this._flushId&&(this._packedGeometryPoolSize++,e[this._flushId]=new this.geometryClass),e[this._flushId]._buffer.update(i.rawBinaryData),e[this._flushId]._indexBuffer.update(s),this.renderer.geometry.bind(e[this._flushId]),this.renderer.geometry.updateBuffers(),this._flushId++)}drawBatches(){const e=this._dcIndex,{gl:i,state:s}=this.renderer,r=t._drawCallPool;let n=null;for(let t=0;t<e;t++){const{texArray:e,type:o,size:a,start:l,blend:h}=r[t];n!==e&&(n=e,this.bindAndClearTexArray(e)),this.state.blendMode=h,s.set(this.state),i.drawElements(o,a,i.UNSIGNED_SHORT,2*l)}}flush(){0!==this._vertexCount&&(this._attributeBuffer=this.getAttributeBuffer(this._vertexCount),this._indexBuffer=this.getIndexBuffer(this._indexCount),this._aIndex=0,this._iIndex=0,this._dcIndex=0,this.buildTexturesAndDrawCalls(),this.updateGeometry(),this.drawBatches(),this._bufferSize=0,this._vertexCount=0,this._indexCount=0)}start(){this.renderer.state.set(this.state),this.renderer.texture.ensureSamplerType(this.maxTextures),this.renderer.shader.bind(this._shader),t.canUploadSameBuffer&&this.renderer.geometry.bind(this._packedGeometries[this._flushId])}stop(){this.flush()}destroy(){for(let t=0;t<this._packedGeometryPoolSize;t++)this._packedGeometries[t]&&this._packedGeometries[t].destroy();this.renderer.off("prerender",this.onPrerender,this),this._aBuffers=null,this._iBuffers=null,this._packedGeometries=null,this._attributeBuffer=null,this._indexBuffer=null,this._shader&&(this._shader.destroy(),this._shader=null),super.destroy()}getAttributeBuffer(t){const e=vp(Math.ceil(t/8)),i=bp(e),s=8*e;this._aBuffers.length<=i&&(this._iBuffers.length=i+1);let r=this._aBuffers[s];return r||(this._aBuffers[s]=r=new Yp(s*this.vertexSize*4)),r}getIndexBuffer(t){const e=vp(Math.ceil(t/12)),i=bp(e),s=12*e;this._iBuffers.length<=i&&(this._iBuffers.length=i+1);let r=this._iBuffers[i];return r||(this._iBuffers[i]=r=new Uint16Array(s)),r}packInterleavedGeometry(t,e,i,s,r){const{uint32View:n,float32View:o}=e,a=s/this.vertexSize,l=t.uvs,h=t.indices,u=t.vertexData,c=t._texture.baseTexture._batchLocation,d=Math.min(t.worldAlpha,1),p=pp.shared.setValue(t._tintRGB).toPremultiplied(d,t._texture.baseTexture.alphaMode>0);for(let f=0;f<u.length;f+=2)o[s++]=u[f],o[s++]=u[f+1],o[s++]=l[f],o[s++]=l[f+1],n[s++]=p,o[s++]=c;for(let f=0;f<h.length;f++)i[r++]=a+h[f]}};hm.defaultBatchSize=4096,hm.extension={name:"batch",type:Up.RendererPlugin},hm._drawCallPool=[],hm._textureArrayPool=[];let um=hm;Wp.add(um);const cm=class t extends nm{constructor(e,i,s){super(im.from(e||t.defaultVertexSrc,i||t.defaultFragmentSrc),s),this.padding=0,this.resolution=t.defaultResolution,this.multisample=t.defaultMultisample,this.enabled=!0,this.autoFit=!0,this.state=new jp}apply(t,e,i,s,r){t.applyFilter(this,e,i,s)}get blendMode(){return this.state.blendMode}set blendMode(t){this.state.blendMode=t}get resolution(){return this._resolution}set resolution(t){this._resolution=t}static get defaultVertexSrc(){return"attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"}static get defaultFragmentSrc(){return"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"}};cm.defaultResolution=1,cm.defaultMultisample=Ch.NONE;let dm=cm;class pm{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new pp(0),this.alpha=1}init(t){this.clearBeforeRender=t.clearBeforeRender;const{backgroundColor:e,background:i,backgroundAlpha:s}=t,r=i??e;void 0!==r&&(this.color=r),this.alpha=s}get color(){return this._backgroundColor.value}set color(t){this._backgroundColor.setValue(t)}get alpha(){return this._backgroundColor.alpha}set alpha(t){this._backgroundColor.setAlpha(t)}get backgroundColor(){return this._backgroundColor}destroy(){}}pm.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0},pm.extension={type:[Up.RendererSystem,Up.CanvasRendererSystem],name:"background"},Wp.add(pm);class fm{constructor(t){this.renderer=t,this.emptyRenderer=new lm(t),this.currentRenderer=this.emptyRenderer}setObjectRenderer(t){this.currentRenderer!==t&&(this.currentRenderer.stop(),this.currentRenderer=t,this.currentRenderer.start())}flush(){this.setObjectRenderer(this.emptyRenderer)}reset(){this.setObjectRenderer(this.emptyRenderer)}copyBoundTextures(t,e){const{boundTextures:i}=this.renderer.texture;for(let s=e-1;s>=0;--s)t[s]=i[s]||null,t[s]&&(t[s]._batchLocation=s)}boundArray(t,e,i,s){const{elements:r,ids:n,count:o}=t;let a=0;for(let l=0;l<o;l++){const t=r[l],o=t._batchLocation;if(o>=0&&o<s&&e[o]===t)n[l]=o;else for(;a<s;){const s=e[a];if(!s||s._batchEnabled!==i||s._batchLocation!==a){n[l]=a,t._batchLocation=a,e[a]=t;break}a++}}}destroy(){this.renderer=null}}fm.extension={type:Up.RendererSystem,name:"batch"},Wp.add(fm);let mm=0;class gm{constructor(t){this.renderer=t,this.webGLVersion=1,this.extensions={},this.supports={uint32Indices:!1},this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(t){this.gl=t,this.renderer.gl=t,this.renderer.CONTEXT_UID=mm++}init(t){if(t.context)this.initFromContext(t.context);else{const e=this.renderer.background.alpha<1,i=t.premultipliedAlpha;this.preserveDrawingBuffer=t.preserveDrawingBuffer,this.useContextAlpha=t.useContextAlpha,this.powerPreference=t.powerPreference,this.initFromOptions({alpha:e,premultipliedAlpha:i,antialias:t.antialias,stencil:!0,preserveDrawingBuffer:t.preserveDrawingBuffer,powerPreference:t.powerPreference})}}initFromContext(t){this.gl=t,this.validateContext(t),this.renderer.gl=t,this.renderer.CONTEXT_UID=mm++,this.renderer.runners.contextChange.emit(t);const e=this.renderer.view;void 0!==e.addEventListener&&(e.addEventListener("webglcontextlost",this.handleContextLost,!1),e.addEventListener("webglcontextrestored",this.handleContextRestored,!1))}initFromOptions(t){const e=this.createContext(this.renderer.view,t);this.initFromContext(e)}createContext(t,e){let i;if(Oh.PREFER_ENV>=dh.WEBGL2&&(i=t.getContext("webgl2",e)),i)this.webGLVersion=2;else if(this.webGLVersion=1,i=t.getContext("webgl",e)||t.getContext("experimental-webgl",e),!i)throw new Error("This browser does not support WebGL. Try using the canvas renderer");return this.gl=i,this.getExtensions(),this.gl}getExtensions(){const{gl:t}=this,e={loseContext:t.getExtension("WEBGL_lose_context"),anisotropicFiltering:t.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),s3tc:t.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:t.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:t.getExtension("WEBGL_compressed_texture_etc"),etc1:t.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:t.getExtension("WEBGL_compressed_texture_atc"),astc:t.getExtension("WEBGL_compressed_texture_astc"),bptc:t.getExtension("EXT_texture_compression_bptc")};1===this.webGLVersion?Object.assign(this.extensions,e,{drawBuffers:t.getExtension("WEBGL_draw_buffers"),depthTexture:t.getExtension("WEBGL_depth_texture"),vertexArrayObject:t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:t.getExtension("OES_element_index_uint"),floatTexture:t.getExtension("OES_texture_float"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),textureHalfFloat:t.getExtension("OES_texture_half_float"),textureHalfFloatLinear:t.getExtension("OES_texture_half_float_linear")}):2===this.webGLVersion&&Object.assign(this.extensions,e,{colorBufferFloat:t.getExtension("EXT_color_buffer_float")})}handleContextLost(t){t.preventDefault(),setTimeout(()=>{this.gl.isContextLost()&&this.extensions.loseContext&&this.extensions.loseContext.restoreContext()},0)}handleContextRestored(){this.renderer.runners.contextChange.emit(this.gl)}destroy(){const t=this.renderer.view;this.renderer=null,void 0!==t.removeEventListener&&(t.removeEventListener("webglcontextlost",this.handleContextLost),t.removeEventListener("webglcontextrestored",this.handleContextRestored)),this.gl.useProgram(null),this.extensions.loseContext&&this.extensions.loseContext.loseContext()}postrender(){this.renderer.objectRenderer.renderingToScreen&&this.gl.flush()}validateContext(t){const e=t.getContextAttributes(),i="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext;i&&(this.webGLVersion=2),e&&!e.stencil&&console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const s=i||!!t.getExtension("OES_element_index_uint");this.supports.uint32Indices=s,s||console.warn("Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly")}}gm.defaultOptions={context:null,antialias:!1,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:"default"},gm.extension={type:Up.RendererSystem,name:"context"},Wp.add(gm);class ym{constructor(t,e){if(this.width=Math.round(t),this.height=Math.round(e),!this.width||!this.height)throw new Error("Framebuffer width or height is zero");this.stencil=!1,this.depth=!1,this.dirtyId=0,this.dirtyFormat=0,this.dirtySize=0,this.depthTexture=null,this.colorTextures=[],this.glFramebuffers={},this.disposeRunner=new qp("disposeFramebuffer"),this.multisample=Ch.NONE}get colorTexture(){return this.colorTextures[0]}addColorTexture(t=0,e){return this.colorTextures[t]=e||new tf(null,{scaleMode:wh.NEAREST,resolution:1,mipmap:Ph.OFF,width:this.width,height:this.height}),this.dirtyId++,this.dirtyFormat++,this}addDepthTexture(t){return this.depthTexture=t||new tf(null,{scaleMode:wh.NEAREST,resolution:1,width:this.width,height:this.height,mipmap:Ph.OFF,format:yh.DEPTH_COMPONENT,type:xh.UNSIGNED_SHORT}),this.dirtyId++,this.dirtyFormat++,this}enableDepth(){return this.depth=!0,this.dirtyId++,this.dirtyFormat++,this}enableStencil(){return this.stencil=!0,this.dirtyId++,this.dirtyFormat++,this}resize(t,e){if(t=Math.round(t),e=Math.round(e),!t||!e)throw new Error("Framebuffer width and height must not be zero");if(t!==this.width||e!==this.height){this.width=t,this.height=e,this.dirtyId++,this.dirtySize++;for(let i=0;i<this.colorTextures.length;i++){const s=this.colorTextures[i],r=s.resolution;s.setSize(t/r,e/r)}if(this.depthTexture){const i=this.depthTexture.resolution;this.depthTexture.setSize(t/i,e/i)}}}dispose(){this.disposeRunner.emit(this,!1)}destroyDepthTexture(){this.depthTexture&&(this.depthTexture.destroy(),this.depthTexture=null,++this.dirtyId,++this.dirtyFormat)}}class vm extends tf{constructor(t={}){if("number"==typeof t){t={width:arguments[0],height:arguments[1],scaleMode:arguments[2],resolution:arguments[3]}}t.width=t.width??100,t.height=t.height??100,t.multisample??(t.multisample=Ch.NONE),super(null,t),this.mipmap=Ph.OFF,this.valid=!0,this._clear=new pp([0,0,0,0]),this.framebuffer=new ym(this.realWidth,this.realHeight).addColorTexture(0,this),this.framebuffer.multisample=t.multisample,this.maskStack=[],this.filterStack=[{}]}set clearColor(t){this._clear.setValue(t)}get clearColor(){return this._clear.value}get clear(){return this._clear}get multisample(){return this.framebuffer.multisample}set multisample(t){this.framebuffer.multisample=t}resize(t,e){this.framebuffer.resize(t*this.resolution,e*this.resolution),this.setRealSize(this.framebuffer.width,this.framebuffer.height)}dispose(){this.framebuffer.dispose(),super.dispose()}destroy(){super.destroy(),this.framebuffer.destroyDepthTexture(),this.framebuffer=null}}class xm extends Jp{constructor(t){const e=t;super(e.naturalWidth||e.videoWidth||e.displayWidth||e.width,e.naturalHeight||e.videoHeight||e.displayHeight||e.height),this.source=t,this.noSubImage=!1}static crossOrigin(t,e,i){void 0!==i||e.startsWith("data:")?!1!==i&&(t.crossOrigin="string"==typeof i?i:"anonymous"):t.crossOrigin=kp(e)}upload(t,e,i,s){const r=t.gl,n=e.realWidth,o=e.realHeight;if(s=s||this.source,typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement){if(!s.complete||0===s.naturalWidth)return!1}else if(typeof HTMLVideoElement<"u"&&s instanceof HTMLVideoElement&&s.readyState<=1)return!1;return r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.alphaMode===Eh.UNPACK),this.noSubImage||e.target!==r.TEXTURE_2D||i.width!==n||i.height!==o?(i.width=n,i.height=o,r.texImage2D(e.target,0,i.internalFormat,e.format,i.type,s)):r.texSubImage2D(r.TEXTURE_2D,0,0,0,e.format,i.type,s),!0}update(){if(this.destroyed)return;const t=this.source,e=t.naturalWidth||t.videoWidth||t.width,i=t.naturalHeight||t.videoHeight||t.height;this.resize(e,i),super.update()}dispose(){this.source=null}}class bm extends xm{constructor(t,e){if(e=e||{},"string"==typeof t){const i=new Image;xm.crossOrigin(i,t,e.crossorigin),i.src=t,t=i}super(t),!t.complete&&this._width&&this._height&&(this._width=0,this._height=0),this.url=t.src,this._process=null,this.preserveBitmap=!1,this.createBitmap=(e.createBitmap??Oh.CREATE_IMAGE_BITMAP)&&!!globalThis.createImageBitmap,this.alphaMode="number"==typeof e.alphaMode?e.alphaMode:null,this.bitmap=null,this._load=null,!1!==e.autoLoad&&this.load()}load(t){return this._load||(void 0!==t&&(this.createBitmap=t),this._load=new Promise((t,e)=>{const i=this.source;this.url=i.src;const s=()=>{this.destroyed||(i.onload=null,i.onerror=null,this.update(),this._load=null,this.createBitmap?t(this.process()):t(this))};i.complete&&i.src?s():(i.onload=s,i.onerror=t=>{e(t),this.onError.emit(t)})})),this._load}process(){const t=this.source;if(null!==this._process)return this._process;if(null!==this.bitmap||!globalThis.createImageBitmap)return Promise.resolve(this);const e=globalThis.createImageBitmap,i=!t.crossOrigin||"anonymous"===t.crossOrigin;return this._process=fetch(t.src,{mode:i?"cors":"no-cors"}).then(t=>t.blob()).then(i=>e(i,0,0,t.width,t.height,{premultiplyAlpha:null===this.alphaMode||this.alphaMode===Eh.UNPACK?"premultiply":"none"})).then(t=>this.destroyed?Promise.reject():(this.bitmap=t,this.update(),this._process=null,Promise.resolve(this))),this._process}upload(t,e,i){if("number"==typeof this.alphaMode&&(e.alphaMode=this.alphaMode),!this.createBitmap)return super.upload(t,e,i);if(!this.bitmap&&(this.process(),!this.bitmap))return!1;if(super.upload(t,e,i,this.bitmap),!this.preserveBitmap){let t=!0;const s=e._glTextures;for(const r in s){const n=s[r];if(n!==i&&n.dirtyId!==e.dirtyId){t=!1;break}}t&&(this.bitmap.close&&this.bitmap.close(),this.bitmap=null)}return!0}dispose(){this.source.onload=null,this.source.onerror=null,super.dispose(),this.bitmap&&(this.bitmap.close(),this.bitmap=null),this._process=null,this._load=null}static test(t){return typeof HTMLImageElement<"u"&&("string"==typeof t||t instanceof HTMLImageElement)}}class wm{constructor(){this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsFloat32=new Float32Array(8)}set(t,e,i){const s=e.width,r=e.height;if(i){const e=t.width/2/s,n=t.height/2/r,o=t.x/s+e,a=t.y/r+n;i=Of.add(i,Of.NW),this.x0=o+e*Of.uX(i),this.y0=a+n*Of.uY(i),i=Of.add(i,2),this.x1=o+e*Of.uX(i),this.y1=a+n*Of.uY(i),i=Of.add(i,2),this.x2=o+e*Of.uX(i),this.y2=a+n*Of.uY(i),i=Of.add(i,2),this.x3=o+e*Of.uX(i),this.y3=a+n*Of.uY(i)}else this.x0=t.x/s,this.y0=t.y/r,this.x1=(t.x+t.width)/s,this.y1=t.y/r,this.x2=(t.x+t.width)/s,this.y2=(t.y+t.height)/r,this.x3=t.x/s,this.y3=(t.y+t.height)/r;this.uvsFloat32[0]=this.x0,this.uvsFloat32[1]=this.y0,this.uvsFloat32[2]=this.x1,this.uvsFloat32[3]=this.y1,this.uvsFloat32[4]=this.x2,this.uvsFloat32[5]=this.y2,this.uvsFloat32[6]=this.x3,this.uvsFloat32[7]=this.y3}}wm.prototype.toString=function(){return`[@pixi/core:TextureUvs x0=${this.x0} y0=${this.y0} x1=${this.x1} y1=${this.y1} x2=${this.x2} y2=${this.y2} x3=${this.x3} y3=${this.y3}]`};const _m=new wm;function Pm(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}class Em extends Qh{constructor(t,e,i,s,r,n,o){if(super(),this.noFrame=!1,e||(this.noFrame=!0,e=new vf(0,0,1,1)),t instanceof Em&&(t=t.baseTexture),this.baseTexture=t,this._frame=e,this.trim=s,this.valid=!1,this.destroyed=!1,this._uvs=_m,this.uvMatrix=null,this.orig=i||e,this._rotate=Number(r||0),!0===r)this._rotate=2;else if(this._rotate%2!=0)throw new Error("attempt to use diamond-shaped UVs. If you are sure, set rotation manually");this.defaultAnchor=n?new gf(n.x,n.y):new gf(0,0),this.defaultBorders=o,this._updateID=0,this.textureCacheIds=[],t.valid?this.noFrame?t.valid&&this.onBaseTextureUpdated(t):this.frame=e:t.once("loaded",this.onBaseTextureUpdated,this),this.noFrame&&t.on("update",this.onBaseTextureUpdated,this)}update(){this.baseTexture.resource&&this.baseTexture.resource.update()}onBaseTextureUpdated(t){if(this.noFrame){if(!this.baseTexture.valid)return;this._frame.width=t.width,this._frame.height=t.height,this.valid=!0,this.updateUvs()}else this.frame=this._frame;this.emit("update",this)}destroy(t){if(this.baseTexture){if(t){const{resource:t}=this.baseTexture;t?.url&&Sp[t.url]&&Em.removeFromCache(t.url),this.baseTexture.destroy()}this.baseTexture.off("loaded",this.onBaseTextureUpdated,this),this.baseTexture.off("update",this.onBaseTextureUpdated,this),this.baseTexture=null}this._frame=null,this._uvs=null,this.trim=null,this.orig=null,this.valid=!1,Em.removeFromCache(this),this.textureCacheIds=null,this.destroyed=!0,this.emit("destroyed",this),this.removeAllListeners()}clone(){const t=this._frame.clone(),e=this._frame===this.orig?t:this.orig.clone(),i=new Em(this.baseTexture,!this.noFrame&&t,e,this.trim?.clone(),this.rotate,this.defaultAnchor,this.defaultBorders);return this.noFrame&&(i._frame=t),i}updateUvs(){this._uvs===_m&&(this._uvs=new wm),this._uvs.set(this._frame,this.baseTexture,this.rotate),this._updateID++}static from(t,e={},i=Oh.STRICT_TEXTURE_CACHE){const s="string"==typeof t;let r=null;if(s)r=t;else if(t instanceof tf){if(!t.cacheId){const i=e?.pixiIdPrefix||"pixiid";t.cacheId=`${i}-${Ep()}`,tf.addToCache(t,t.cacheId)}r=t.cacheId}else{if(!t._pixiId){const i=e?.pixiIdPrefix||"pixiid";t._pixiId=`${i}_${Ep()}`}r=t._pixiId}let n=Sp[r];if(s&&i&&!n)throw new Error(`The cacheId "${r}" does not exist in TextureCache.`);return n||t instanceof tf?!n&&t instanceof tf&&(n=new Em(t),Em.addToCache(n,r)):(e.resolution||(e.resolution=Fp(t)),n=new Em(new tf(t,e)),n.baseTexture.cacheId=r,tf.addToCache(n.baseTexture,r),Em.addToCache(n,r)),n}static fromURL(t,e){const i=Object.assign({autoLoad:!1},e?.resourceOptions),s=Em.from(t,Object.assign({resourceOptions:i},e),!1),r=s.baseTexture.resource;return s.baseTexture.valid?Promise.resolve(s):r.load().then(()=>Promise.resolve(s))}static fromBuffer(t,e,i,s){return new Em(tf.fromBuffer(t,e,i,s))}static fromLoader(t,e,i,s){const r=new tf(t,Object.assign({scaleMode:tf.defaultOptions.scaleMode,resolution:Fp(e)},s)),{resource:n}=r;n instanceof bm&&(n.url=e);const o=new Em(r);return i||(i=e),tf.addToCache(o.baseTexture,i),Em.addToCache(o,i),i!==e&&(tf.addToCache(o.baseTexture,e),Em.addToCache(o,e)),o.baseTexture.valid?Promise.resolve(o):new Promise(t=>{o.baseTexture.once("loaded",()=>t(o))})}static addToCache(t,e){e&&(t.textureCacheIds.includes(e)||t.textureCacheIds.push(e),Sp[e]&&Sp[e]!==t&&console.warn(`Texture added to the cache with an id [${e}] that already had an entry`),Sp[e]=t)}static removeFromCache(t){if("string"==typeof t){const e=Sp[t];if(e){const i=e.textureCacheIds.indexOf(t);return i>-1&&e.textureCacheIds.splice(i,1),delete Sp[t],e}}else if(t?.textureCacheIds){for(let e=0;e<t.textureCacheIds.length;++e)Sp[t.textureCacheIds[e]]===t&&delete Sp[t.textureCacheIds[e]];return t.textureCacheIds.length=0,t}return null}get resolution(){return this.baseTexture.resolution}get frame(){return this._frame}set frame(t){this._frame=t,this.noFrame=!1;const{x:e,y:i,width:s,height:r}=t,n=e+s>this.baseTexture.width,o=i+r>this.baseTexture.height;if(n||o){const t=n&&o?"and":"or",a=`X: ${e} + ${s} = ${e+s} > ${this.baseTexture.width}`,l=`Y: ${i} + ${r} = ${i+r} > ${this.baseTexture.height}`;throw new Error(`Texture Error: frame does not fit inside the base Texture dimensions: ${a} ${t} ${l}`)}this.valid=s&&r&&this.baseTexture.valid,!this.trim&&!this.rotate&&(this.orig=t),this.valid&&this.updateUvs()}get rotate(){return this._rotate}set rotate(t){this._rotate=t,this.valid&&this.updateUvs()}get width(){return this.orig.width}get height(){return this.orig.height}castToBaseTexture(){return this.baseTexture}static get EMPTY(){return Em._EMPTY||(Em._EMPTY=new Em(new tf),Pm(Em._EMPTY),Pm(Em._EMPTY.baseTexture)),Em._EMPTY}static get WHITE(){if(!Em._WHITE){const t=Oh.ADAPTER.createCanvas(16,16),e=t.getContext("2d");t.width=16,t.height=16,e.fillStyle="white",e.fillRect(0,0,16,16),Em._WHITE=new Em(tf.from(t)),Pm(Em._WHITE),Pm(Em._WHITE.baseTexture)}return Em._WHITE}}class Tm extends Em{constructor(t,e){super(t,e),this.valid=!0,this.filterFrame=null,this.filterPoolKey=null,this.updateUvs()}get framebuffer(){return this.baseTexture.framebuffer}get multisample(){return this.framebuffer.multisample}set multisample(t){this.framebuffer.multisample=t}resize(t,e,i=!0){const s=this.baseTexture.resolution,r=Math.round(t*s)/s,n=Math.round(e*s)/s;this.valid=r>0&&n>0,this._frame.width=this.orig.width=r,this._frame.height=this.orig.height=n,i&&this.baseTexture.resize(r,n),this.updateUvs()}setResolution(t){const{baseTexture:e}=this;e.resolution!==t&&(e.setResolution(t),this.resize(e.width,e.height,!1))}static create(t){return new Tm(new vm(t))}}class Am{constructor(t){this.texturePool={},this.textureOptions=t||{},this.enableFullScreen=!1,this._pixelsWidth=0,this._pixelsHeight=0}createTexture(t,e,i=Ch.NONE){const s=new vm(Object.assign({width:t,height:e,resolution:1,multisample:i},this.textureOptions));return new Tm(s)}getOptimalTexture(t,e,i=1,s=Ch.NONE){let r;t=Math.max(Math.ceil(t*i-1e-6),1),e=Math.max(Math.ceil(e*i-1e-6),1),this.enableFullScreen&&t===this._pixelsWidth&&e===this._pixelsHeight?r=s>1?-s:-1:(r=((65535&(t=vp(t)))<<16|65535&(e=vp(e)))>>>0,s>1&&(r+=4294967296*s)),this.texturePool[r]||(this.texturePool[r]=[]);let n=this.texturePool[r].pop();return n||(n=this.createTexture(t,e,s)),n.filterPoolKey=r,n.setResolution(i),n}getFilterTexture(t,e,i){const s=this.getOptimalTexture(t.width,t.height,e||t.resolution,i||Ch.NONE);return s.filterFrame=t.filterFrame,s}returnTexture(t){const e=t.filterPoolKey;t.filterFrame=null,this.texturePool[e].push(t)}returnFilterTexture(t){this.returnTexture(t)}clear(t){if(t=!1!==t)for(const e in this.texturePool){const t=this.texturePool[e];if(t)for(let e=0;e<t.length;e++)t[e].destroy(!0)}this.texturePool={}}setScreenSize(t){if(t.width!==this._pixelsWidth||t.height!==this._pixelsHeight){this.enableFullScreen=t.width>0&&t.height>0;for(const t in this.texturePool){if(!(Number(t)<0))continue;const e=this.texturePool[t];if(e)for(let t=0;t<e.length;t++)e[t].destroy(!0);this.texturePool[t]=[]}this._pixelsWidth=t.width,this._pixelsHeight=t.height}}}Am.SCREEN_KEY=-1;class Im extends uf{constructor(){super(),this.addAttribute("aVertexPosition",new Float32Array([0,0,1,0,1,1,0,1])).addIndex([0,1,3,2])}}class Sm extends uf{constructor(){super(),this.vertices=new Float32Array([-1,-1,1,-1,1,1,-1,1]),this.uvs=new Float32Array([0,0,1,0,1,1,0,1]),this.vertexBuffer=new rf(this.vertices),this.uvBuffer=new rf(this.uvs),this.addAttribute("aVertexPosition",this.vertexBuffer).addAttribute("aTextureCoord",this.uvBuffer).addIndex([0,1,2,0,2,3])}map(t,e){let i=0,s=0;return this.uvs[0]=i,this.uvs[1]=s,this.uvs[2]=i+e.width/t.width,this.uvs[3]=s,this.uvs[4]=i+e.width/t.width,this.uvs[5]=s+e.height/t.height,this.uvs[6]=i,this.uvs[7]=s+e.height/t.height,i=e.x,s=e.y,this.vertices[0]=i,this.vertices[1]=s,this.vertices[2]=i+e.width,this.vertices[3]=s,this.vertices[4]=i+e.width,this.vertices[5]=s+e.height,this.vertices[6]=i,this.vertices[7]=s+e.height,this.invalidate(),this}invalidate(){return this.vertexBuffer._updateID++,this.uvBuffer._updateID++,this}}class Cm{constructor(){this.renderTexture=null,this.target=null,this.legacy=!1,this.resolution=1,this.multisample=Ch.NONE,this.sourceFrame=new vf,this.destinationFrame=new vf,this.bindingSourceFrame=new vf,this.bindingDestinationFrame=new vf,this.filters=[],this.transform=null}clear(){this.target=null,this.filters=null,this.renderTexture=null}}const Mm=[new gf,new gf,new gf,new gf],Om=new Pf;class Nm{constructor(t){this.renderer=t,this.defaultFilterStack=[{}],this.texturePool=new Am,this.statePool=[],this.quad=new Im,this.quadUv=new Sm,this.tempRect=new vf,this.activeState={},this.globalUniforms=new rm({outputFrame:new vf,inputSize:new Float32Array(4),inputPixel:new Float32Array(4),inputClamp:new Float32Array(4),resolution:1,filterArea:new Float32Array(4),filterClamp:new Float32Array(4)},!0),this.forceClear=!1,this.useMaxPadding=!1}init(){this.texturePool.setScreenSize(this.renderer.view)}push(t,e){const i=this.renderer,s=this.defaultFilterStack,r=this.statePool.pop()||new Cm,n=i.renderTexture;let o,a;if(n.current){const t=n.current;o=t.resolution,a=t.multisample}else o=i.resolution,a=i.multisample;let l=e[0].resolution||o,h=e[0].multisample??a,u=e[0].padding,c=e[0].autoFit,d=e[0].legacy??!0;for(let m=1;m<e.length;m++){const t=e[m];l=Math.min(l,t.resolution||o),h=Math.min(h,t.multisample??a),u=this.useMaxPadding?Math.max(u,t.padding):u+t.padding,c=c&&t.autoFit,d=d||(t.legacy??!0)}1===s.length&&(this.defaultFilterStack[0].renderTexture=n.current),s.push(r),r.resolution=l,r.multisample=h,r.legacy=d,r.target=t,r.sourceFrame.copyFrom(t.filterArea||t.getBounds(!0)),r.sourceFrame.pad(u);const p=this.tempRect.copyFrom(n.sourceFrame);i.projection.transform&&this.transformAABB(Om.copyFrom(i.projection.transform).invert(),p),c?(r.sourceFrame.fit(p),(r.sourceFrame.width<=0||r.sourceFrame.height<=0)&&(r.sourceFrame.width=0,r.sourceFrame.height=0)):r.sourceFrame.intersects(p)||(r.sourceFrame.width=0,r.sourceFrame.height=0),this.roundFrame(r.sourceFrame,n.current?n.current.resolution:i.resolution,n.sourceFrame,n.destinationFrame,i.projection.transform),r.renderTexture=this.getOptimalFilterTexture(r.sourceFrame.width,r.sourceFrame.height,l,h),r.filters=e,r.destinationFrame.width=r.renderTexture.width,r.destinationFrame.height=r.renderTexture.height;const f=this.tempRect;f.x=0,f.y=0,f.width=r.sourceFrame.width,f.height=r.sourceFrame.height,r.renderTexture.filterFrame=r.sourceFrame,r.bindingSourceFrame.copyFrom(n.sourceFrame),r.bindingDestinationFrame.copyFrom(n.destinationFrame),r.transform=i.projection.transform,i.projection.transform=null,n.bind(r.renderTexture,r.sourceFrame,f),i.framebuffer.clear(0,0,0,0)}pop(){const t=this.defaultFilterStack,e=t.pop(),i=e.filters;this.activeState=e;const s=this.globalUniforms.uniforms;s.outputFrame=e.sourceFrame,s.resolution=e.resolution;const r=s.inputSize,n=s.inputPixel,o=s.inputClamp;if(r[0]=e.destinationFrame.width,r[1]=e.destinationFrame.height,r[2]=1/r[0],r[3]=1/r[1],n[0]=Math.round(r[0]*e.resolution),n[1]=Math.round(r[1]*e.resolution),n[2]=1/n[0],n[3]=1/n[1],o[0]=.5*n[2],o[1]=.5*n[3],o[2]=e.sourceFrame.width*r[2]-.5*n[2],o[3]=e.sourceFrame.height*r[3]-.5*n[3],e.legacy){const t=s.filterArea;t[0]=e.destinationFrame.width,t[1]=e.destinationFrame.height,t[2]=e.sourceFrame.x,t[3]=e.sourceFrame.y,s.filterClamp=s.inputClamp}this.globalUniforms.update();const a=t[t.length-1];if(this.renderer.framebuffer.blit(),1===i.length)i[0].apply(this,e.renderTexture,a.renderTexture,Th.BLEND,e),this.returnFilterTexture(e.renderTexture);else{let t=e.renderTexture,s=this.getOptimalFilterTexture(t.width,t.height,e.resolution);s.filterFrame=t.filterFrame;let r=0;for(r=0;r<i.length-1;++r){1===r&&e.multisample>1&&(s=this.getOptimalFilterTexture(t.width,t.height,e.resolution),s.filterFrame=t.filterFrame),i[r].apply(this,t,s,Th.CLEAR,e);const n=t;t=s,s=n}i[r].apply(this,t,a.renderTexture,Th.BLEND,e),r>1&&e.multisample>1&&this.returnFilterTexture(e.renderTexture),this.returnFilterTexture(t),this.returnFilterTexture(s)}e.clear(),this.statePool.push(e)}bindAndClear(t,e=Th.CLEAR){const{renderTexture:i,state:s}=this.renderer;if(t===this.defaultFilterStack[this.defaultFilterStack.length-1].renderTexture?this.renderer.projection.transform=this.activeState.transform:this.renderer.projection.transform=null,t?.filterFrame){const e=this.tempRect;e.x=0,e.y=0,e.width=t.filterFrame.width,e.height=t.filterFrame.height,i.bind(t,t.filterFrame,e)}else t!==this.defaultFilterStack[this.defaultFilterStack.length-1].renderTexture?i.bind(t):this.renderer.renderTexture.bind(t,this.activeState.bindingSourceFrame,this.activeState.bindingDestinationFrame);const r=1&s.stateId||this.forceClear;(e===Th.CLEAR||e===Th.BLIT&&r)&&this.renderer.framebuffer.clear(0,0,0,0)}applyFilter(t,e,i,s){const r=this.renderer;r.state.set(t.state),this.bindAndClear(i,s),t.uniforms.uSampler=e,t.uniforms.filterGlobals=this.globalUniforms,r.shader.bind(t),t.legacy=!!t.program.attributeData.aTextureCoord,t.legacy?(this.quadUv.map(e._frame,e.filterFrame),r.geometry.bind(this.quadUv),r.geometry.draw(gh.TRIANGLES)):(r.geometry.bind(this.quad),r.geometry.draw(gh.TRIANGLE_STRIP))}calculateSpriteMatrix(t,e){const{sourceFrame:i,destinationFrame:s}=this.activeState,{orig:r}=e._texture,n=t.set(s.width,0,0,s.height,i.x,i.y),o=e.worldTransform.copyTo(Pf.TEMP_MATRIX);return o.invert(),n.prepend(o),n.scale(1/r.width,1/r.height),n.translate(e.anchor.x,e.anchor.y),n}destroy(){this.renderer=null,this.texturePool.clear(!1)}getOptimalFilterTexture(t,e,i=1,s=Ch.NONE){return this.texturePool.getOptimalTexture(t,e,i,s)}getFilterTexture(t,e,i){if("number"==typeof t){const i=t;t=e,e=i}t=t||this.activeState.renderTexture;const s=this.texturePool.getOptimalTexture(t.width,t.height,e||t.resolution,i||Ch.NONE);return s.filterFrame=t.filterFrame,s}returnFilterTexture(t){this.texturePool.returnTexture(t)}emptyPool(){this.texturePool.clear(!0)}resize(){this.texturePool.setScreenSize(this.renderer.view)}transformAABB(t,e){const i=Mm[0],s=Mm[1],r=Mm[2],n=Mm[3];i.set(e.left,e.top),s.set(e.left,e.bottom),r.set(e.right,e.top),n.set(e.right,e.bottom),t.apply(i,i),t.apply(s,s),t.apply(r,r),t.apply(n,n);const o=Math.min(i.x,s.x,r.x,n.x),a=Math.min(i.y,s.y,r.y,n.y),l=Math.max(i.x,s.x,r.x,n.x),h=Math.max(i.y,s.y,r.y,n.y);e.x=o,e.y=a,e.width=l-o,e.height=h-a}roundFrame(t,e,i,s,r){if(!(t.width<=0||t.height<=0||i.width<=0||i.height<=0)){if(r){const{a:t,b:e,c:i,d:s}=r;if((Math.abs(e)>1e-4||Math.abs(i)>1e-4)&&(Math.abs(t)>1e-4||Math.abs(s)>1e-4))return}(r=r?Om.copyFrom(r):Om.identity()).translate(-i.x,-i.y).scale(s.width/i.width,s.height/i.height).translate(s.x,s.y),this.transformAABB(r,t),t.ceil(e),this.transformAABB(r.invert(),t)}}}Nm.extension={type:Up.RendererSystem,name:"filter"},Wp.add(Nm);class Lm{constructor(t){this.framebuffer=t,this.stencil=null,this.dirtyId=-1,this.dirtyFormat=-1,this.dirtySize=-1,this.multisample=Ch.NONE,this.msaaBuffer=null,this.blitFramebuffer=null,this.mipLevel=0}}const Rm=new vf;class Bm{constructor(t){this.renderer=t,this.managedFramebuffers=[],this.unknownFramebuffer=new ym(10,10),this.msaaSamples=null}contextChange(){this.disposeAll(!0);const t=this.gl=this.renderer.gl;if(this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.current=this.unknownFramebuffer,this.viewport=new vf,this.hasMRT=!0,this.writeDepthTexture=!0,1===this.renderer.context.webGLVersion){let e=this.renderer.context.extensions.drawBuffers,i=this.renderer.context.extensions.depthTexture;Oh.PREFER_ENV===dh.WEBGL_LEGACY&&(e=null,i=null),e?t.drawBuffers=t=>e.drawBuffersWEBGL(t):(this.hasMRT=!1,t.drawBuffers=()=>{}),i||(this.writeDepthTexture=!1)}else this.msaaSamples=t.getInternalformatParameter(t.RENDERBUFFER,t.RGBA8,t.SAMPLES)}bind(t,e,i=0){const{gl:s}=this;if(t){const r=t.glFramebuffers[this.CONTEXT_UID]||this.initFramebuffer(t);this.current!==t&&(this.current=t,s.bindFramebuffer(s.FRAMEBUFFER,r.framebuffer)),r.mipLevel!==i&&(t.dirtyId++,t.dirtyFormat++,r.mipLevel=i),r.dirtyId!==t.dirtyId&&(r.dirtyId=t.dirtyId,r.dirtyFormat!==t.dirtyFormat?(r.dirtyFormat=t.dirtyFormat,r.dirtySize=t.dirtySize,this.updateFramebuffer(t,i)):r.dirtySize!==t.dirtySize&&(r.dirtySize=t.dirtySize,this.resizeFramebuffer(t)));for(let e=0;e<t.colorTextures.length;e++){const i=t.colorTextures[e];this.renderer.texture.unbind(i.parentTextureArray||i)}if(t.depthTexture&&this.renderer.texture.unbind(t.depthTexture),e){const t=e.width>>i,s=e.height>>i,r=t/e.width;this.setViewport(e.x*r,e.y*r,t,s)}else{const e=t.width>>i,s=t.height>>i;this.setViewport(0,0,e,s)}}else this.current&&(this.current=null,s.bindFramebuffer(s.FRAMEBUFFER,null)),e?this.setViewport(e.x,e.y,e.width,e.height):this.setViewport(0,0,this.renderer.width,this.renderer.height)}setViewport(t,e,i,s){const r=this.viewport;t=Math.round(t),e=Math.round(e),i=Math.round(i),s=Math.round(s),(r.width!==i||r.height!==s||r.x!==t||r.y!==e)&&(r.x=t,r.y=e,r.width=i,r.height=s,this.gl.viewport(t,e,i,s))}get size(){return this.current?{x:0,y:0,width:this.current.width,height:this.current.height}:{x:0,y:0,width:this.renderer.width,height:this.renderer.height}}clear(t,e,i,s,r=fh.COLOR|fh.DEPTH){const{gl:n}=this;n.clearColor(t,e,i,s),n.clear(r)}initFramebuffer(t){const{gl:e}=this,i=new Lm(e.createFramebuffer());return i.multisample=this.detectSamples(t.multisample),t.glFramebuffers[this.CONTEXT_UID]=i,this.managedFramebuffers.push(t),t.disposeRunner.add(this),i}resizeFramebuffer(t){const{gl:e}=this,i=t.glFramebuffers[this.CONTEXT_UID];if(i.stencil){let s;e.bindRenderbuffer(e.RENDERBUFFER,i.stencil),s=1===this.renderer.context.webGLVersion?e.DEPTH_STENCIL:t.depth&&t.stencil?e.DEPTH24_STENCIL8:t.depth?e.DEPTH_COMPONENT24:e.STENCIL_INDEX8,i.msaaBuffer?e.renderbufferStorageMultisample(e.RENDERBUFFER,i.multisample,s,t.width,t.height):e.renderbufferStorage(e.RENDERBUFFER,s,t.width,t.height)}const s=t.colorTextures;let r=s.length;e.drawBuffers||(r=Math.min(r,1));for(let n=0;n<r;n++){const r=s[n],o=r.parentTextureArray||r;this.renderer.texture.bind(o,0),0===n&&i.msaaBuffer&&(e.bindRenderbuffer(e.RENDERBUFFER,i.msaaBuffer),e.renderbufferStorageMultisample(e.RENDERBUFFER,i.multisample,o._glTextures[this.CONTEXT_UID].internalFormat,t.width,t.height))}t.depthTexture&&this.writeDepthTexture&&this.renderer.texture.bind(t.depthTexture,0)}updateFramebuffer(t,e){const{gl:i}=this,s=t.glFramebuffers[this.CONTEXT_UID],r=t.colorTextures;let n=r.length;i.drawBuffers||(n=Math.min(n,1)),s.multisample>1&&this.canMultisampleFramebuffer(t)?s.msaaBuffer=s.msaaBuffer||i.createRenderbuffer():s.msaaBuffer&&(i.deleteRenderbuffer(s.msaaBuffer),s.msaaBuffer=null,s.blitFramebuffer&&(s.blitFramebuffer.dispose(),s.blitFramebuffer=null));const o=[];for(let a=0;a<n;a++){const n=r[a],l=n.parentTextureArray||n;this.renderer.texture.bind(l,0),0===a&&s.msaaBuffer?(i.bindRenderbuffer(i.RENDERBUFFER,s.msaaBuffer),i.renderbufferStorageMultisample(i.RENDERBUFFER,s.multisample,l._glTextures[this.CONTEXT_UID].internalFormat,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,s.msaaBuffer)):(i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+a,n.target,l._glTextures[this.CONTEXT_UID].texture,e),o.push(i.COLOR_ATTACHMENT0+a))}if(o.length>1&&i.drawBuffers(o),t.depthTexture&&this.writeDepthTexture){const s=t.depthTexture;this.renderer.texture.bind(s,0),i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,s._glTextures[this.CONTEXT_UID].texture,e)}if(!t.stencil&&!t.depth||t.depthTexture&&this.writeDepthTexture)s.stencil&&(i.deleteRenderbuffer(s.stencil),s.stencil=null);else{let e,r;s.stencil=s.stencil||i.createRenderbuffer(),1===this.renderer.context.webGLVersion?(e=i.DEPTH_STENCIL_ATTACHMENT,r=i.DEPTH_STENCIL):t.depth&&t.stencil?(e=i.DEPTH_STENCIL_ATTACHMENT,r=i.DEPTH24_STENCIL8):t.depth?(e=i.DEPTH_ATTACHMENT,r=i.DEPTH_COMPONENT24):(e=i.STENCIL_ATTACHMENT,r=i.STENCIL_INDEX8),i.bindRenderbuffer(i.RENDERBUFFER,s.stencil),s.msaaBuffer?i.renderbufferStorageMultisample(i.RENDERBUFFER,s.multisample,r,t.width,t.height):i.renderbufferStorage(i.RENDERBUFFER,r,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,e,i.RENDERBUFFER,s.stencil)}}canMultisampleFramebuffer(t){return 1!==this.renderer.context.webGLVersion&&t.colorTextures.length<=1&&!t.depthTexture}detectSamples(t){const{msaaSamples:e}=this;let i=Ch.NONE;if(t<=1||null===e)return i;for(let s=0;s<e.length;s++)if(e[s]<=t){i=e[s];break}return 1===i&&(i=Ch.NONE),i}blit(t,e,i){const{current:s,renderer:r,gl:n,CONTEXT_UID:o}=this;if(2!==r.context.webGLVersion||!s)return;const a=s.glFramebuffers[o];if(!a)return;if(!t){if(!a.msaaBuffer)return;const e=s.colorTextures[0];if(!e)return;a.blitFramebuffer||(a.blitFramebuffer=new ym(s.width,s.height),a.blitFramebuffer.addColorTexture(0,e)),(t=a.blitFramebuffer).colorTextures[0]!==e&&(t.colorTextures[0]=e,t.dirtyId++,t.dirtyFormat++),(t.width!==s.width||t.height!==s.height)&&(t.width=s.width,t.height=s.height,t.dirtyId++,t.dirtySize++)}e||((e=Rm).width=s.width,e.height=s.height),i||(i=e);const l=e.width===i.width&&e.height===i.height;this.bind(t),n.bindFramebuffer(n.READ_FRAMEBUFFER,a.framebuffer),n.blitFramebuffer(e.left,e.top,e.right,e.bottom,i.left,i.top,i.right,i.bottom,n.COLOR_BUFFER_BIT,l?n.NEAREST:n.LINEAR),n.bindFramebuffer(n.READ_FRAMEBUFFER,t.glFramebuffers[this.CONTEXT_UID].framebuffer)}disposeFramebuffer(t,e){const i=t.glFramebuffers[this.CONTEXT_UID],s=this.gl;if(!i)return;delete t.glFramebuffers[this.CONTEXT_UID];const r=this.managedFramebuffers.indexOf(t);r>=0&&this.managedFramebuffers.splice(r,1),t.disposeRunner.remove(this),e||(s.deleteFramebuffer(i.framebuffer),i.msaaBuffer&&s.deleteRenderbuffer(i.msaaBuffer),i.stencil&&s.deleteRenderbuffer(i.stencil)),i.blitFramebuffer&&this.disposeFramebuffer(i.blitFramebuffer,e)}disposeAll(t){const e=this.managedFramebuffers;this.managedFramebuffers=[];for(let i=0;i<e.length;i++)this.disposeFramebuffer(e[i],t)}forceStencil(){const t=this.current;if(!t)return;const e=t.glFramebuffers[this.CONTEXT_UID];if(!e||e.stencil&&t.stencil)return;t.stencil=!0;const i=t.width,s=t.height,r=this.gl,n=e.stencil=r.createRenderbuffer();let o,a;r.bindRenderbuffer(r.RENDERBUFFER,n),1===this.renderer.context.webGLVersion?(o=r.DEPTH_STENCIL_ATTACHMENT,a=r.DEPTH_STENCIL):t.depth?(o=r.DEPTH_STENCIL_ATTACHMENT,a=r.DEPTH24_STENCIL8):(o=r.STENCIL_ATTACHMENT,a=r.STENCIL_INDEX8),e.msaaBuffer?r.renderbufferStorageMultisample(r.RENDERBUFFER,e.multisample,a,i,s):r.renderbufferStorage(r.RENDERBUFFER,a,i,s),r.framebufferRenderbuffer(r.FRAMEBUFFER,o,r.RENDERBUFFER,n)}reset(){this.current=this.unknownFramebuffer,this.viewport=new vf}destroy(){this.renderer=null}}Bm.extension={type:Up.RendererSystem,name:"framebuffer"},Wp.add(Bm);const km={5126:4,5123:2,5121:1};class Fm{constructor(t){this.renderer=t,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this.canUseUInt32ElementIndex=!1,this.managedGeometries={}}contextChange(){this.disposeAll(!0);const t=this.gl=this.renderer.gl,e=this.renderer.context;if(this.CONTEXT_UID=this.renderer.CONTEXT_UID,2!==e.webGLVersion){let e=this.renderer.context.extensions.vertexArrayObject;Oh.PREFER_ENV===dh.WEBGL_LEGACY&&(e=null),e?(t.createVertexArray=()=>e.createVertexArrayOES(),t.bindVertexArray=t=>e.bindVertexArrayOES(t),t.deleteVertexArray=t=>e.deleteVertexArrayOES(t)):(this.hasVao=!1,t.createVertexArray=()=>null,t.bindVertexArray=()=>null,t.deleteVertexArray=()=>null)}if(2!==e.webGLVersion){const e=t.getExtension("ANGLE_instanced_arrays");e?(t.vertexAttribDivisor=(t,i)=>e.vertexAttribDivisorANGLE(t,i),t.drawElementsInstanced=(t,i,s,r,n)=>e.drawElementsInstancedANGLE(t,i,s,r,n),t.drawArraysInstanced=(t,i,s,r)=>e.drawArraysInstancedANGLE(t,i,s,r)):this.hasInstance=!1}this.canUseUInt32ElementIndex=2===e.webGLVersion||!!e.extensions.uint32ElementIndex}bind(t,e){e=e||this.renderer.shader.shader;const{gl:i}=this;let s=t.glVertexArrayObjects[this.CONTEXT_UID],r=!1;s||(this.managedGeometries[t.id]=t,t.disposeRunner.add(this),t.glVertexArrayObjects[this.CONTEXT_UID]=s={},r=!0);const n=s[e.program.id]||this.initGeometryVao(t,e,r);this._activeGeometry=t,this._activeVao!==n&&(this._activeVao=n,this.hasVao?i.bindVertexArray(n):this.activateVao(t,e.program)),this.updateBuffers()}reset(){this.unbind()}updateBuffers(){const t=this._activeGeometry,e=this.renderer.buffer;for(let i=0;i<t.buffers.length;i++){const s=t.buffers[i];e.update(s)}}checkCompatibility(t,e){const i=t.attributes,s=e.attributeData;for(const r in s)if(!i[r])throw new Error(`shader and geometry incompatible, geometry missing the "${r}" attribute`)}getSignature(t,e){const i=t.attributes,s=e.attributeData,r=["g",t.id];for(const n in i)s[n]&&r.push(n,s[n].location);return r.join("-")}initGeometryVao(t,e,i=!0){const s=this.gl,r=this.CONTEXT_UID,n=this.renderer.buffer,o=e.program;o.glPrograms[r]||this.renderer.shader.generateProgram(e),this.checkCompatibility(t,o);const a=this.getSignature(t,o),l=t.glVertexArrayObjects[this.CONTEXT_UID];let h=l[a];if(h)return l[o.id]=h,h;const u=t.buffers,c=t.attributes,d={},p={};for(const f in u)d[f]=0,p[f]=0;for(const f in c)!c[f].size&&o.attributeData[f]?c[f].size=o.attributeData[f].size:c[f].size||console.warn(`PIXI Geometry attribute '${f}' size cannot be determined (likely the bound shader does not have the attribute)`),d[c[f].buffer]+=c[f].size*km[c[f].type];for(const f in c){const t=c[f],e=t.size;void 0===t.stride&&(d[t.buffer]===e*km[t.type]?t.stride=0:t.stride=d[t.buffer]),void 0===t.start&&(t.start=p[t.buffer],p[t.buffer]+=e*km[t.type])}h=s.createVertexArray(),s.bindVertexArray(h);for(let f=0;f<u.length;f++){const t=u[f];n.bind(t),i&&t._glBuffers[r].refCount++}return this.activateVao(t,o),l[o.id]=h,l[a]=h,s.bindVertexArray(null),n.unbind(Mh.ARRAY_BUFFER),h}disposeGeometry(t,e){if(!this.managedGeometries[t.id])return;delete this.managedGeometries[t.id];const i=t.glVertexArrayObjects[this.CONTEXT_UID],s=this.gl,r=t.buffers,n=this.renderer?.buffer;if(t.disposeRunner.remove(this),i){if(n)for(let t=0;t<r.length;t++){const i=r[t]._glBuffers[this.CONTEXT_UID];i&&(i.refCount--,0===i.refCount&&!e&&n.dispose(r[t],e))}if(!e)for(const t in i)if("g"===t[0]){const e=i[t];this._activeVao===e&&this.unbind(),s.deleteVertexArray(e)}delete t.glVertexArrayObjects[this.CONTEXT_UID]}}disposeAll(t){const e=Object.keys(this.managedGeometries);for(let i=0;i<e.length;i++)this.disposeGeometry(this.managedGeometries[e[i]],t)}activateVao(t,e){const i=this.gl,s=this.CONTEXT_UID,r=this.renderer.buffer,n=t.buffers,o=t.attributes;t.indexBuffer&&r.bind(t.indexBuffer);let a=null;for(const l in o){const t=o[l],h=n[t.buffer],u=h._glBuffers[s];if(e.attributeData[l]){a!==u&&(r.bind(h),a=u);const s=e.attributeData[l].location;if(i.enableVertexAttribArray(s),i.vertexAttribPointer(s,t.size,t.type||i.FLOAT,t.normalized,t.stride,t.start),t.instance){if(!this.hasInstance)throw new Error("geometry error, GPU Instancing is not supported on this device");i.vertexAttribDivisor(s,t.divisor)}}}}draw(t,e,i,s){const{gl:r}=this,n=this._activeGeometry;if(n.indexBuffer){const o=n.indexBuffer.data.BYTES_PER_ELEMENT,a=2===o?r.UNSIGNED_SHORT:r.UNSIGNED_INT;2===o||4===o&&this.canUseUInt32ElementIndex?n.instanced?r.drawElementsInstanced(t,e||n.indexBuffer.data.length,a,(i||0)*o,s||1):r.drawElements(t,e||n.indexBuffer.data.length,a,(i||0)*o):console.warn("unsupported index buffer type: uint32")}else n.instanced?r.drawArraysInstanced(t,i,e||n.getSize(),s||1):r.drawArrays(t,i,e||n.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this.renderer=null}}Fm.extension={type:Up.RendererSystem,name:"geometry"},Wp.add(Fm);const Dm=new Pf;class Um{constructor(t,e){this._texture=t,this.mapCoord=new Pf,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,this.clampMargin=typeof e>"u"?.5:e,this.isSimple=!1}get texture(){return this._texture}set texture(t){this._texture=t,this._textureID=-1}multiplyUvs(t,e){void 0===e&&(e=t);const i=this.mapCoord;for(let s=0;s<t.length;s+=2){const r=t[s],n=t[s+1];e[s]=r*i.a+n*i.c+i.tx,e[s+1]=r*i.b+n*i.d+i.ty}return e}update(t){const e=this._texture;if(!e||!e.valid||!t&&this._textureID===e._updateID)return!1;this._textureID=e._updateID,this._updateID++;const i=e._uvs;this.mapCoord.set(i.x1-i.x0,i.y1-i.y0,i.x3-i.x0,i.y3-i.y0,i.x0,i.y0);const s=e.orig,r=e.trim;r&&(Dm.set(s.width/r.width,0,0,s.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(Dm));const n=e.baseTexture,o=this.uClampFrame,a=this.clampMargin/n.resolution,l=this.clampOffset;return o[0]=(e._frame.x+a+l)/n.width,o[1]=(e._frame.y+a+l)/n.height,o[2]=(e._frame.x+e._frame.width-a+l)/n.width,o[3]=(e._frame.y+e._frame.height-a+l)/n.height,this.uClampOffset[0]=l/n.realWidth,this.uClampOffset[1]=l/n.realHeight,this.isSimple=e._frame.width===n.width&&e._frame.height===n.height&&0===e.rotate,!0}}class Gm extends dm{constructor(t,e,i){let s=null;"string"!=typeof t&&void 0===e&&void 0===i&&(s=t,t=void 0,e=void 0,i=void 0),super(t||"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n",e||"varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n",i),this.maskSprite=s,this.maskMatrix=new Pf}get maskSprite(){return this._maskSprite}set maskSprite(t){this._maskSprite=t,this._maskSprite&&(this._maskSprite.renderable=!1)}apply(t,e,i,s){const r=this._maskSprite,n=r._texture;n.valid&&(n.uvMatrix||(n.uvMatrix=new Um(n,0)),n.uvMatrix.update(),this.uniforms.npmAlpha=n.baseTexture.alphaMode?0:1,this.uniforms.mask=n,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,r).prepend(n.uvMatrix.mapCoord),this.uniforms.alpha=r.worldAlpha,this.uniforms.maskClamp=n.uvMatrix.uClampFrame,t.applyFilter(this,e,i,s))}}class Xm{constructor(t=null){this.type=Sh.NONE,this.autoDetect=!0,this.maskObject=t||null,this.pooled=!1,this.isMaskData=!0,this.resolution=null,this.multisample=dm.defaultMultisample,this.enabled=!0,this.colorMask=15,this._filters=null,this._stencilCounter=0,this._scissorCounter=0,this._scissorRect=null,this._scissorRectLocal=null,this._colorMask=15,this._target=null}get filter(){return this._filters?this._filters[0]:null}set filter(t){t?this._filters?this._filters[0]=t:this._filters=[t]:this._filters=null}reset(){this.pooled&&(this.maskObject=null,this.type=Sh.NONE,this.autoDetect=!0),this._target=null,this._scissorRectLocal=null}copyCountersOrReset(t){t?(this._stencilCounter=t._stencilCounter,this._scissorCounter=t._scissorCounter,this._scissorRect=t._scissorRect):(this._stencilCounter=0,this._scissorCounter=0,this._scissorRect=null)}}class Wm{constructor(t){this.renderer=t,this.enableScissor=!0,this.alphaMaskPool=[],this.maskDataPool=[],this.maskStack=[],this.alphaMaskIndex=0}setMaskStack(t){this.maskStack=t,this.renderer.scissor.setMaskStack(t),this.renderer.stencil.setMaskStack(t)}push(t,e){let i=e;if(!i.isMaskData){const t=this.maskDataPool.pop()||new Xm;t.pooled=!0,t.maskObject=e,i=t}const s=0!==this.maskStack.length?this.maskStack[this.maskStack.length-1]:null;if(i.copyCountersOrReset(s),i._colorMask=s?s._colorMask:15,i.autoDetect&&this.detect(i),i._target=t,i.type!==Sh.SPRITE&&this.maskStack.push(i),i.enabled)switch(i.type){case Sh.SCISSOR:this.renderer.scissor.push(i);break;case Sh.STENCIL:this.renderer.stencil.push(i);break;case Sh.SPRITE:i.copyCountersOrReset(null),this.pushSpriteMask(i);break;case Sh.COLOR:this.pushColorMask(i)}i.type===Sh.SPRITE&&this.maskStack.push(i)}pop(t){const e=this.maskStack.pop();if(e&&e._target===t){if(e.enabled)switch(e.type){case Sh.SCISSOR:this.renderer.scissor.pop(e);break;case Sh.STENCIL:this.renderer.stencil.pop(e.maskObject);break;case Sh.SPRITE:this.popSpriteMask(e);break;case Sh.COLOR:this.popColorMask(e)}if(e.reset(),e.pooled&&this.maskDataPool.push(e),0!==this.maskStack.length){const t=this.maskStack[this.maskStack.length-1];t.type===Sh.SPRITE&&t._filters&&(t._filters[0].maskSprite=t.maskObject)}}}detect(t){const e=t.maskObject;e?e.isSprite?t.type=Sh.SPRITE:this.enableScissor&&this.renderer.scissor.testScissor(t)?t.type=Sh.SCISSOR:t.type=Sh.STENCIL:t.type=Sh.COLOR}pushSpriteMask(t){const{maskObject:e}=t,i=t._target;let s=t._filters;s||(s=this.alphaMaskPool[this.alphaMaskIndex],s||(s=this.alphaMaskPool[this.alphaMaskIndex]=[new Gm])),s[0].resolution=t.resolution,s[0].multisample=t.multisample,s[0].maskSprite=e;const r=i.filterArea;i.filterArea=e.getBounds(!0),this.renderer.filter.push(i,s),i.filterArea=r,t._filters||this.alphaMaskIndex++}popSpriteMask(t){this.renderer.filter.pop(),t._filters?t._filters[0].maskSprite=null:(this.alphaMaskIndex--,this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite=null)}pushColorMask(t){const e=t._colorMask,i=t._colorMask=e&t.colorMask;i!==e&&this.renderer.gl.colorMask(!!(1&i),!!(2&i),!!(4&i),!!(8&i))}popColorMask(t){const e=t._colorMask,i=this.maskStack.length>0?this.maskStack[this.maskStack.length-1]._colorMask:15;i!==e&&this.renderer.gl.colorMask(!!(1&i),!!(2&i),!!(4&i),!!(8&i))}destroy(){this.renderer=null}}Wm.extension={type:Up.RendererSystem,name:"mask"},Wp.add(Wm);class Ym{constructor(t){this.renderer=t,this.maskStack=[],this.glConst=0}getStackLength(){return this.maskStack.length}setMaskStack(t){const{gl:e}=this.renderer,i=this.getStackLength();this.maskStack=t;const s=this.getStackLength();s!==i&&(0===s?e.disable(this.glConst):(e.enable(this.glConst),this._useCurrent()))}_useCurrent(){}destroy(){this.renderer=null,this.maskStack=null}}const Hm=new Pf,$m=[],jm=class t extends Ym{constructor(t){super(t),this.glConst=Oh.ADAPTER.getWebGLRenderingContext().SCISSOR_TEST}getStackLength(){const t=this.maskStack[this.maskStack.length-1];return t?t._scissorCounter:0}calcScissorRect(t){if(t._scissorRectLocal)return;const e=t._scissorRect,{maskObject:i}=t,{renderer:s}=this,r=s.renderTexture,n=i.getBounds(!0,$m.pop()??new vf);this.roundFrameToPixels(n,r.current?r.current.resolution:s.resolution,r.sourceFrame,r.destinationFrame,s.projection.transform),e&&n.fit(e),t._scissorRectLocal=n}static isMatrixRotated(t){if(!t)return!1;const{a:e,b:i,c:s,d:r}=t;return(Math.abs(i)>1e-4||Math.abs(s)>1e-4)&&(Math.abs(e)>1e-4||Math.abs(r)>1e-4)}testScissor(e){const{maskObject:i}=e;if(!i.isFastRect||!i.isFastRect()||t.isMatrixRotated(i.worldTransform)||t.isMatrixRotated(this.renderer.projection.transform))return!1;this.calcScissorRect(e);const s=e._scissorRectLocal;return s.width>0&&s.height>0}roundFrameToPixels(e,i,s,r,n){t.isMatrixRotated(n)||((n=n?Hm.copyFrom(n):Hm.identity()).translate(-s.x,-s.y).scale(r.width/s.width,r.height/s.height).translate(r.x,r.y),this.renderer.filter.transformAABB(n,e),e.fit(r),e.x=Math.round(e.x*i),e.y=Math.round(e.y*i),e.width=Math.round(e.width*i),e.height=Math.round(e.height*i))}push(t){t._scissorRectLocal||this.calcScissorRect(t);const{gl:e}=this.renderer;t._scissorRect||e.enable(e.SCISSOR_TEST),t._scissorCounter++,t._scissorRect=t._scissorRectLocal,this._useCurrent()}pop(t){const{gl:e}=this.renderer;t&&$m.push(t._scissorRectLocal),this.getStackLength()>0?this._useCurrent():e.disable(e.SCISSOR_TEST)}_useCurrent(){const t=this.maskStack[this.maskStack.length-1]._scissorRect;let e;e=this.renderer.renderTexture.current?t.y:this.renderer.height-t.height-t.y,this.renderer.gl.scissor(t.x,e,t.width,t.height)}};jm.extension={type:Up.RendererSystem,name:"scissor"};let zm=jm;Wp.add(zm);class Vm extends Ym{constructor(t){super(t),this.glConst=Oh.ADAPTER.getWebGLRenderingContext().STENCIL_TEST}getStackLength(){const t=this.maskStack[this.maskStack.length-1];return t?t._stencilCounter:0}push(t){const e=t.maskObject,{gl:i}=this.renderer,s=t._stencilCounter;0===s&&(this.renderer.framebuffer.forceStencil(),i.clearStencil(0),i.clear(i.STENCIL_BUFFER_BIT),i.enable(i.STENCIL_TEST)),t._stencilCounter++;const r=t._colorMask;0!==r&&(t._colorMask=0,i.colorMask(!1,!1,!1,!1)),i.stencilFunc(i.EQUAL,s,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.INCR),e.renderable=!0,e.render(this.renderer),this.renderer.batch.flush(),e.renderable=!1,0!==r&&(t._colorMask=r,i.colorMask(!!(1&r),!!(2&r),!!(4&r),!!(8&r))),this._useCurrent()}pop(t){const e=this.renderer.gl;if(0===this.getStackLength())e.disable(e.STENCIL_TEST);else{const i=0!==this.maskStack.length?this.maskStack[this.maskStack.length-1]:null,s=i?i._colorMask:15;0!==s&&(i._colorMask=0,e.colorMask(!1,!1,!1,!1)),e.stencilOp(e.KEEP,e.KEEP,e.DECR),t.renderable=!0,t.render(this.renderer),this.renderer.batch.flush(),t.renderable=!1,0!==s&&(i._colorMask=s,e.colorMask(!!(1&s),!!(2&s),!!(4&s),!!(8&s))),this._useCurrent()}}_useCurrent(){const t=this.renderer.gl;t.stencilFunc(t.EQUAL,this.getStackLength(),4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP)}}Vm.extension={type:Up.RendererSystem,name:"stencil"},Wp.add(Vm);class qm{constructor(t){this.renderer=t,this.plugins={},Object.defineProperties(this.plugins,{extract:{enumerable:!1,get:()=>(Md("7.0.0","renderer.plugins.extract has moved to renderer.extract"),t.extract)},prepare:{enumerable:!1,get:()=>(Md("7.0.0","renderer.plugins.prepare has moved to renderer.prepare"),t.prepare)},interaction:{enumerable:!1,get:()=>(Md("7.0.0","renderer.plugins.interaction has been deprecated, use renderer.events"),t.events)}})}init(){const t=this.rendererPlugins;for(const e in t)this.plugins[e]=new t[e](this.renderer)}destroy(){for(const t in this.plugins)this.plugins[t].destroy(),this.plugins[t]=null}}qm.extension={type:[Up.RendererSystem,Up.CanvasRendererSystem],name:"_plugin"},Wp.add(qm);class Jm{constructor(t){this.renderer=t,this.destinationFrame=null,this.sourceFrame=null,this.defaultFrame=null,this.projectionMatrix=new Pf,this.transform=null}update(t,e,i,s){this.destinationFrame=t||this.destinationFrame||this.defaultFrame,this.sourceFrame=e||this.sourceFrame||t,this.calculateProjection(this.destinationFrame,this.sourceFrame,i,s),this.transform&&this.projectionMatrix.append(this.transform);const r=this.renderer;r.globalUniforms.uniforms.projectionMatrix=this.projectionMatrix,r.globalUniforms.update(),r.shader.shader&&r.shader.syncUniformGroup(r.shader.shader.uniforms.globals)}calculateProjection(t,e,i,s){const r=this.projectionMatrix,n=s?-1:1;r.identity(),r.a=1/e.width*2,r.d=n*(1/e.height*2),r.tx=-1-e.x*r.a,r.ty=-n-e.y*r.d}setTransform(t){}destroy(){this.renderer=null}}Jm.extension={type:Up.RendererSystem,name:"projection"},Wp.add(Jm);const Km=new Rf,Zm=new vf;class Qm{constructor(t){this.renderer=t,this._tempMatrix=new Pf}generateTexture(t,e){const{region:i,...s}=e||{},r=i?.copyTo(Zm)||t.getLocalBounds(Zm,!0),n=s.resolution||this.renderer.resolution;r.width=Math.max(r.width,1/n),r.height=Math.max(r.height,1/n),s.width=r.width,s.height=r.height,s.resolution=n,s.multisample??(s.multisample=this.renderer.multisample);const o=Tm.create(s);this._tempMatrix.tx=-r.x,this._tempMatrix.ty=-r.y;const a=t.transform;return t.transform=Km,this.renderer.render(t,{renderTexture:o,transform:this._tempMatrix,skipUpdateTransform:!!t.parent,blit:!0}),t.transform=a,o}destroy(){}}Qm.extension={type:[Up.RendererSystem,Up.CanvasRendererSystem],name:"textureGenerator"},Wp.add(Qm);const tg=new vf,eg=new vf;class ig{constructor(t){this.renderer=t,this.defaultMaskStack=[],this.current=null,this.sourceFrame=new vf,this.destinationFrame=new vf,this.viewportFrame=new vf}contextChange(){const t=this.renderer?.gl.getContextAttributes();this._rendererPremultipliedAlpha=!!(t&&t.alpha&&t.premultipliedAlpha)}bind(t=null,e,i){const s=this.renderer;let r,n,o;this.current=t,t?(r=t.baseTexture,o=r.resolution,e||(tg.width=t.frame.width,tg.height=t.frame.height,e=tg),i||(eg.x=t.frame.x,eg.y=t.frame.y,eg.width=e.width,eg.height=e.height,i=eg),n=r.framebuffer):(o=s.resolution,e||(tg.width=s._view.screen.width,tg.height=s._view.screen.height,e=tg),i||((i=tg).width=e.width,i.height=e.height));const a=this.viewportFrame;a.x=i.x*o,a.y=i.y*o,a.width=i.width*o,a.height=i.height*o,t||(a.y=s.view.height-(a.y+a.height)),a.ceil(),this.renderer.framebuffer.bind(n,a),this.renderer.projection.update(i,e,o,!n),t?this.renderer.mask.setMaskStack(r.maskStack):this.renderer.mask.setMaskStack(this.defaultMaskStack),this.sourceFrame.copyFrom(e),this.destinationFrame.copyFrom(i)}clear(t,e){const i=this.current?this.current.baseTexture.clear:this.renderer.background.backgroundColor,s=pp.shared.setValue(t||i);(this.current&&this.current.baseTexture.alphaMode>0||!this.current&&this._rendererPremultipliedAlpha)&&s.premultiply(s.alpha);const r=this.destinationFrame,n=this.current?this.current.baseTexture:this.renderer._view.screen,o=r.width!==n.width||r.height!==n.height;if(o){let{x:t,y:e,width:i,height:s}=this.viewportFrame;t=Math.round(t),e=Math.round(e),i=Math.round(i),s=Math.round(s),this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST),this.renderer.gl.scissor(t,e,i,s)}this.renderer.framebuffer.clear(s.red,s.green,s.blue,s.alpha,e),o&&this.renderer.scissor.pop()}resize(){this.bind(null)}reset(){this.bind(null)}destroy(){this.renderer=null}}ig.extension={type:Up.RendererSystem,name:"renderTexture"},Wp.add(ig);class sg{constructor(t,e){this.program=t,this.uniformData=e,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBufferBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBufferBindings=null,this.program=null}}function rg(t,e){const i=Bf(t,t.VERTEX_SHADER,e.vertexSrc),s=Bf(t,t.FRAGMENT_SHADER,e.fragmentSrc),r=t.createProgram();t.attachShader(r,i),t.attachShader(r,s);const n=e.extra?.transformFeedbackVaryings;if(n&&("function"!=typeof t.transformFeedbackVaryings?console.warn("TransformFeedback is not supported but TransformFeedbackVaryings are given."):t.transformFeedbackVaryings(r,n.names,"separate"===n.bufferMode?t.SEPARATE_ATTRIBS:t.INTERLEAVED_ATTRIBS)),t.linkProgram(r),t.getProgramParameter(r,t.LINK_STATUS)||function(t,e,i,s){t.getProgramParameter(e,t.LINK_STATUS)||(t.getShaderParameter(i,t.COMPILE_STATUS)||$f(t,i),t.getShaderParameter(s,t.COMPILE_STATUS)||$f(t,s),console.error("PixiJS Error: Could not initialize shader."),""!==t.getProgramInfoLog(e)&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",t.getProgramInfoLog(e)))}(t,r,i,s),e.attributeData=function(t,e){const i={},s=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<s;r++){const s=e.getActiveAttrib(t,r);if(s.name.startsWith("gl_"))continue;const n=Jf(e,s.type),o={type:n,name:s.name,size:zf(n),location:e.getAttribLocation(t,s.name)};i[s.name]=o}return i}(r,t),e.uniformData=function(t,e){const i={},s=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<s;r++){const s=e.getActiveUniform(t,r),n=s.name.replace(/\[.*?\]$/,""),o=!!s.name.match(/\[.*?\]$/),a=Jf(e,s.type);i[n]={name:n,index:r,type:a,size:s.size,isArray:o,value:Ff(a,s.size)}}return i}(r,t),!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertexSrc)){const i=Object.keys(e.attributeData);i.sort((t,e)=>t>e?1:-1);for(let s=0;s<i.length;s++)e.attributeData[i[s]].location=s,t.bindAttribLocation(r,s,i[s]);t.linkProgram(r)}t.deleteShader(i),t.deleteShader(s);const o={};for(const a in e.uniformData){const i=e.uniformData[a];o[a]={location:t.getUniformLocation(r,a),value:Ff(i.type,i.size)}}return new sg(r,o)}function ng(t,e,i,s,r){i.buffer.update(r)}const og={float:"\n data[offset] = v;\n ",vec2:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n ",vec3:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n ",vec4:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n data[offset+3] = v[3];\n ",mat2:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n\n data[offset+4] = v[2];\n data[offset+5] = v[3];\n ",mat3:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n data[offset + 4] = v[3];\n data[offset + 5] = v[4];\n data[offset + 6] = v[5];\n\n data[offset + 8] = v[6];\n data[offset + 9] = v[7];\n data[offset + 10] = v[8];\n ",mat4:"\n for(var i = 0; i < 16; i++)\n {\n data[offset + i] = v[i];\n }\n "},ag={float:4,vec2:8,vec3:12,vec4:16,int:4,ivec2:8,ivec3:12,ivec4:16,uint:4,uvec2:8,uvec3:12,uvec4:16,bool:4,bvec2:8,bvec3:12,bvec4:16,mat2:32,mat3:48,mat4:64};function lg(t,e){if(!t.autoManage)return{size:0,syncFunc:ng};const i=function(t,e){const i=[];for(const s in t)e[s]&&i.push(e[s]);return i.sort((t,e)=>t.index-e.index),i}(t.uniforms,e),{uboElements:s,size:r}=function(t){const e=t.map(t=>({data:t,offset:0,dataLen:0,dirty:0}));let i=0,s=0,r=0;for(let n=0;n<e.length;n++){const t=e[n];if(i=ag[t.data.type],t.data.size>1&&(i=Math.max(i,16)*t.data.size),t.dataLen=i,s%i!==0&&s<16){const t=s%i%16;s+=t,r+=t}s+i>16?(r=16*Math.ceil(r/16),t.offset=r,r+=i,s=i):(t.offset=r,s+=i,r+=i)}return r=16*Math.ceil(r/16),{uboElements:e,size:r}}(i),n=["\n var v = null;\n var v2 = null;\n var cv = null;\n var t = 0;\n var gl = renderer.gl\n var index = 0;\n var data = buffer.data;\n "];for(let o=0;o<s.length;o++){const e=s[o],i=t.uniforms[e.data.name],r=e.data.name;let a=!1;for(let t=0;t<Df.length;t++){const s=Df[t];if(s.codeUbo&&s.test(e.data,i)){n.push(`offset = ${e.offset/4};`,Df[t].codeUbo(e.data.name,i)),a=!0;break}}if(!a)if(e.data.size>1){const t=zf(e.data.type),i=Math.max(ag[e.data.type]/16,1),s=t/i,o=(4-s%4)%4;n.push(`\n cv = ud.${r}.value;\n v = uv.${r};\n offset = ${e.offset/4};\n\n t = 0;\n\n for(var i=0; i < ${e.data.size*i}; i++)\n {\n for(var j = 0; j < ${s}; j++)\n {\n data[offset++] = v[t++];\n }\n offset += ${o};\n }\n\n `)}else{const t=og[e.data.type];n.push(`\n cv = ud.${r}.value;\n v = uv.${r};\n offset = ${e.offset/4};\n ${t};\n `)}}return n.push("\n renderer.buffer.update(buffer);\n "),{size:r,syncFunc:new Function("ud","uv","renderer","syncData","buffer",n.join("\n"))}}let hg=0;const ug={textureCount:0,uboCount:0};class cg{constructor(t){this.destroyed=!1,this.renderer=t,this.systemCheck(),this.gl=null,this.shader=null,this.program=null,this.cache={},this._uboCache={},this.id=hg++}systemCheck(){if(!function(){if("boolean"==typeof Zf)return Zf;try{Zf=!0===new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")}catch{Zf=!1}return Zf}())throw new Error("Current environment does not allow unsafe-eval, please use @pixi/unsafe-eval module to enable support.")}contextChange(t){this.gl=t,this.reset()}bind(t,e){t.disposeRunner.add(this),t.uniforms.globals=this.renderer.globalUniforms;const i=t.program,s=i.glPrograms[this.renderer.CONTEXT_UID]||this.generateProgram(t);return this.shader=t,this.program!==i&&(this.program=i,this.gl.useProgram(s.program)),e||(ug.textureCount=0,ug.uboCount=0,this.syncUniformGroup(t.uniformGroup,ug)),s}setUniforms(t){const e=this.shader.program,i=e.glPrograms[this.renderer.CONTEXT_UID];e.syncUniforms(i.uniformData,t,this.renderer)}syncUniformGroup(t,e){const i=this.getGlProgram();(!t.static||t.dirtyId!==i.uniformDirtyGroups[t.id])&&(i.uniformDirtyGroups[t.id]=t.dirtyId,this.syncUniforms(t,i,e))}syncUniforms(t,e,i){(t.syncUniforms[this.shader.program.id]||this.createSyncGroups(t))(e.uniformData,t.uniforms,this.renderer,i)}createSyncGroups(t){const e=this.getSignature(t,this.shader.program.uniformData,"u");return this.cache[e]||(this.cache[e]=function(t,e){const i=["\n var v = null;\n var cv = null;\n var cu = null;\n var t = 0;\n var gl = renderer.gl;\n "];for(const s in t.uniforms){const r=e[s];if(!r){!0===t.uniforms[s]?.group&&(t.uniforms[s].ubo?i.push(`\n renderer.shader.syncUniformBufferGroup(uv.${s}, '${s}');\n `):i.push(`\n renderer.shader.syncUniformGroup(uv.${s}, syncData);\n `));continue}const n=t.uniforms[s];let o=!1;for(let t=0;t<Df.length;t++)if(Df[t].test(r,n)){i.push(Df[t].code(s,n)),o=!0;break}if(!o){const t=(1!==r.size||r.isArray?Gf:Uf)[r.type].replace("location",`ud["${s}"].location`);i.push(`\n cu = ud["${s}"];\n cv = cu.value;\n v = uv["${s}"];\n ${t};`)}}return new Function("ud","uv","renderer","syncData",i.join("\n"))}(t,this.shader.program.uniformData)),t.syncUniforms[this.shader.program.id]=this.cache[e],t.syncUniforms[this.shader.program.id]}syncUniformBufferGroup(t,e){const i=this.getGlProgram();if(!t.static||0!==t.dirtyId||!i.uniformGroups[t.id]){t.dirtyId=0;const s=i.uniformGroups[t.id]||this.createSyncBufferGroup(t,i,e);t.buffer.update(),s(i.uniformData,t.uniforms,this.renderer,ug,t.buffer)}this.renderer.buffer.bindBufferBase(t.buffer,i.uniformBufferBindings[e])}createSyncBufferGroup(t,e,i){const{gl:s}=this.renderer;this.renderer.buffer.bind(t.buffer);const r=this.gl.getUniformBlockIndex(e.program,i);e.uniformBufferBindings[i]=this.shader.uniformBindCount,s.uniformBlockBinding(e.program,r,this.shader.uniformBindCount),this.shader.uniformBindCount++;const n=this.getSignature(t,this.shader.program.uniformData,"ubo");let o=this._uboCache[n];if(o||(o=this._uboCache[n]=lg(t,this.shader.program.uniformData)),t.autoManage){const e=new Float32Array(o.size/4);t.buffer.update(e)}return e.uniformGroups[t.id]=o.syncFunc,e.uniformGroups[t.id]}getSignature(t,e,i){const s=t.uniforms,r=[`${i}-`];for(const n in s)r.push(n),e[n]&&r.push(e[n].type);return r.join("-")}getGlProgram(){return this.shader?this.shader.program.glPrograms[this.renderer.CONTEXT_UID]:null}generateProgram(t){const e=this.gl,i=t.program,s=rg(e,i);return i.glPrograms[this.renderer.CONTEXT_UID]=s,s}reset(){this.program=null,this.shader=null}disposeShader(t){this.shader===t&&(this.shader=null)}destroy(){this.renderer=null,this.destroyed=!0}}cg.extension={type:Up.RendererSystem,name:"shader"},Wp.add(cg);class dg{constructor(t){this.renderer=t}run(t){const{renderer:e}=this;e.runners.init.emit(e.options),t.hello&&console.log(`PixiJS 7.4.2 - ${e.rendererLogId} - https://pixijs.com`),e.resize(e.screen.width,e.screen.height)}destroy(){}}dg.defaultOptions={hello:!1},dg.extension={type:[Up.RendererSystem,Up.CanvasRendererSystem],name:"startup"},Wp.add(dg);const pg=class t{constructor(){this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode=mh.NONE,this._blendEq=!1,this.map=[],this.map[0]=this.setBlend,this.map[1]=this.setOffset,this.map[2]=this.setCullFace,this.map[3]=this.setDepthTest,this.map[4]=this.setFrontFace,this.map[5]=this.setDepthMask,this.checks=[],this.defaultState=new jp,this.defaultState.blend=!0}contextChange(t){this.gl=t,this.blendModes=function(t,e=[]){return e[mh.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.ADD]=[t.ONE,t.ONE],e[mh.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.NONE]=[0,0],e[mh.NORMAL_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.ADD_NPM]=[t.SRC_ALPHA,t.ONE,t.ONE,t.ONE],e[mh.SCREEN_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.SRC_IN]=[t.DST_ALPHA,t.ZERO],e[mh.SRC_OUT]=[t.ONE_MINUS_DST_ALPHA,t.ZERO],e[mh.SRC_ATOP]=[t.DST_ALPHA,t.ONE_MINUS_SRC_ALPHA],e[mh.DST_OVER]=[t.ONE_MINUS_DST_ALPHA,t.ONE],e[mh.DST_IN]=[t.ZERO,t.SRC_ALPHA],e[mh.DST_OUT]=[t.ZERO,t.ONE_MINUS_SRC_ALPHA],e[mh.DST_ATOP]=[t.ONE_MINUS_DST_ALPHA,t.SRC_ALPHA],e[mh.XOR]=[t.ONE_MINUS_DST_ALPHA,t.ONE_MINUS_SRC_ALPHA],e[mh.SUBTRACT]=[t.ONE,t.ONE,t.ONE,t.ONE,t.FUNC_REVERSE_SUBTRACT,t.FUNC_ADD],e}(t),this.set(this.defaultState),this.reset()}set(t){if(t=t||this.defaultState,this.stateId!==t.data){let e=this.stateId^t.data,i=0;for(;e;)1&e&&this.map[i].call(this,!!(t.data&1<<i)),e>>=1,i++;this.stateId=t.data}for(let e=0;e<this.checks.length;e++)this.checks[e](this,t)}forceState(t){t=t||this.defaultState;for(let e=0;e<this.map.length;e++)this.map[e].call(this,!!(t.data&1<<e));for(let e=0;e<this.checks.length;e++)this.checks[e](this,t);this.stateId=t.data}setBlend(e){this.updateCheck(t.checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this.updateCheck(t.checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(t){this.gl[t?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(t){this.gl.depthMask(t)}setCullFace(t){this.gl[t?"enable":"disable"](this.gl.CULL_FACE)}setFrontFace(t){this.gl.frontFace(this.gl[t?"CW":"CCW"])}setBlendMode(t){if(t===this.blendMode)return;this.blendMode=t;const e=this.blendModes[t],i=this.gl;2===e.length?i.blendFunc(e[0],e[1]):i.blendFuncSeparate(e[0],e[1],e[2],e[3]),6===e.length?(this._blendEq=!0,i.blendEquationSeparate(e[4],e[5])):this._blendEq&&(this._blendEq=!1,i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD))}setPolygonOffset(t,e){this.gl.polygonOffset(t,e)}reset(){this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode=-1,this.setBlendMode(0)}updateCheck(t,e){const i=this.checks.indexOf(t);e&&-1===i?this.checks.push(t):!e&&-1!==i&&this.checks.splice(i,1)}static checkBlendMode(t,e){t.setBlendMode(e.blendMode)}static checkPolygonOffset(t,e){t.setPolygonOffset(1,e.polygonOffset)}destroy(){this.gl=null}};pg.extension={type:Up.RendererSystem,name:"state"};let fg=pg;Wp.add(fg);class mg extends Qh{constructor(){super(...arguments),this.runners={},this._systemsHash={}}setup(t){this.addRunners(...t.runners);const e=(t.priority??[]).filter(e=>t.systems[e]),i=[...e,...Object.keys(t.systems).filter(t=>!e.includes(t))];for(const s of i)this.addSystem(t.systems[s],s)}addRunners(...t){t.forEach(t=>{this.runners[t]=new qp(t)})}addSystem(t,e){const i=new t(this);if(this[e])throw new Error(`Whoops! The name "${e}" is already in use`);this[e]=i,this._systemsHash[e]=i;for(const s in this.runners)this.runners[s].add(i);return this}emitWithCustomOptions(t,e){const i=Object.keys(this._systemsHash);t.items.forEach(s=>{const r=i.find(t=>this._systemsHash[t]===s);s[t.name](e[r])})}destroy(){Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash={}}}const gg=class t{constructor(e){this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=t.defaultMaxIdle,this.checkCountMax=t.defaultCheckCountMax,this.mode=t.defaultMode}postrender(){this.renderer.objectRenderer.renderingToScreen&&(this.count++,this.mode!==Ah.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())))}run(){const t=this.renderer.texture,e=t.managedTextures;let i=!1;for(let s=0;s<e.length;s++){const r=e[s];r.resource&&this.count-r.touched>this.maxIdle&&(t.destroyTexture(r,!0),e[s]=null,i=!0)}if(i){let t=0;for(let i=0;i<e.length;i++)null!==e[i]&&(e[t++]=e[i]);e.length=t}}unload(t){const e=this.renderer.texture,i=t._texture;i&&!i.framebuffer&&e.destroyTexture(i);for(let s=t.children.length-1;s>=0;s--)this.unload(t.children[s])}destroy(){this.renderer=null}};gg.defaultMode=Ah.AUTO,gg.defaultMaxIdle=3600,gg.defaultCheckCountMax=600,gg.extension={type:Up.RendererSystem,name:"textureGC"};let yg=gg;Wp.add(yg);class vg{constructor(t){this.texture=t,this.width=-1,this.height=-1,this.dirtyId=-1,this.dirtyStyleId=-1,this.mipmap=!1,this.wrapMode=33071,this.type=xh.UNSIGNED_BYTE,this.internalFormat=yh.RGBA,this.samplerType=0}}class xg{constructor(t){this.renderer=t,this.boundTextures=[],this.currentLocation=-1,this.managedTextures=[],this._unknownBoundTextures=!1,this.unknownTexture=new tf,this.hasIntegerTextures=!1}contextChange(){const t=this.gl=this.renderer.gl;this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.webGLVersion=this.renderer.context.webGLVersion,this.internalFormats=function(t){let e;return e="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext?{[xh.UNSIGNED_BYTE]:{[yh.RGBA]:t.RGBA8,[yh.RGB]:t.RGB8,[yh.RG]:t.RG8,[yh.RED]:t.R8,[yh.RGBA_INTEGER]:t.RGBA8UI,[yh.RGB_INTEGER]:t.RGB8UI,[yh.RG_INTEGER]:t.RG8UI,[yh.RED_INTEGER]:t.R8UI,[yh.ALPHA]:t.ALPHA,[yh.LUMINANCE]:t.LUMINANCE,[yh.LUMINANCE_ALPHA]:t.LUMINANCE_ALPHA},[xh.BYTE]:{[yh.RGBA]:t.RGBA8_SNORM,[yh.RGB]:t.RGB8_SNORM,[yh.RG]:t.RG8_SNORM,[yh.RED]:t.R8_SNORM,[yh.RGBA_INTEGER]:t.RGBA8I,[yh.RGB_INTEGER]:t.RGB8I,[yh.RG_INTEGER]:t.RG8I,[yh.RED_INTEGER]:t.R8I},[xh.UNSIGNED_SHORT]:{[yh.RGBA_INTEGER]:t.RGBA16UI,[yh.RGB_INTEGER]:t.RGB16UI,[yh.RG_INTEGER]:t.RG16UI,[yh.RED_INTEGER]:t.R16UI,[yh.DEPTH_COMPONENT]:t.DEPTH_COMPONENT16},[xh.SHORT]:{[yh.RGBA_INTEGER]:t.RGBA16I,[yh.RGB_INTEGER]:t.RGB16I,[yh.RG_INTEGER]:t.RG16I,[yh.RED_INTEGER]:t.R16I},[xh.UNSIGNED_INT]:{[yh.RGBA_INTEGER]:t.RGBA32UI,[yh.RGB_INTEGER]:t.RGB32UI,[yh.RG_INTEGER]:t.RG32UI,[yh.RED_INTEGER]:t.R32UI,[yh.DEPTH_COMPONENT]:t.DEPTH_COMPONENT24},[xh.INT]:{[yh.RGBA_INTEGER]:t.RGBA32I,[yh.RGB_INTEGER]:t.RGB32I,[yh.RG_INTEGER]:t.RG32I,[yh.RED_INTEGER]:t.R32I},[xh.FLOAT]:{[yh.RGBA]:t.RGBA32F,[yh.RGB]:t.RGB32F,[yh.RG]:t.RG32F,[yh.RED]:t.R32F,[yh.DEPTH_COMPONENT]:t.DEPTH_COMPONENT32F},[xh.HALF_FLOAT]:{[yh.RGBA]:t.RGBA16F,[yh.RGB]:t.RGB16F,[yh.RG]:t.RG16F,[yh.RED]:t.R16F},[xh.UNSIGNED_SHORT_5_6_5]:{[yh.RGB]:t.RGB565},[xh.UNSIGNED_SHORT_4_4_4_4]:{[yh.RGBA]:t.RGBA4},[xh.UNSIGNED_SHORT_5_5_5_1]:{[yh.RGBA]:t.RGB5_A1},[xh.UNSIGNED_INT_2_10_10_10_REV]:{[yh.RGBA]:t.RGB10_A2,[yh.RGBA_INTEGER]:t.RGB10_A2UI},[xh.UNSIGNED_INT_10F_11F_11F_REV]:{[yh.RGB]:t.R11F_G11F_B10F},[xh.UNSIGNED_INT_5_9_9_9_REV]:{[yh.RGB]:t.RGB9_E5},[xh.UNSIGNED_INT_24_8]:{[yh.DEPTH_STENCIL]:t.DEPTH24_STENCIL8},[xh.FLOAT_32_UNSIGNED_INT_24_8_REV]:{[yh.DEPTH_STENCIL]:t.DEPTH32F_STENCIL8}}:{[xh.UNSIGNED_BYTE]:{[yh.RGBA]:t.RGBA,[yh.RGB]:t.RGB,[yh.ALPHA]:t.ALPHA,[yh.LUMINANCE]:t.LUMINANCE,[yh.LUMINANCE_ALPHA]:t.LUMINANCE_ALPHA},[xh.UNSIGNED_SHORT_5_6_5]:{[yh.RGB]:t.RGB},[xh.UNSIGNED_SHORT_4_4_4_4]:{[yh.RGBA]:t.RGBA},[xh.UNSIGNED_SHORT_5_5_5_1]:{[yh.RGBA]:t.RGBA}},e}(t),this.samplerTypes=function(t){let e;return e="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext?{[t.RGB]:bh.FLOAT,[t.RGBA]:bh.FLOAT,[t.ALPHA]:bh.FLOAT,[t.LUMINANCE]:bh.FLOAT,[t.LUMINANCE_ALPHA]:bh.FLOAT,[t.R8]:bh.FLOAT,[t.R8_SNORM]:bh.FLOAT,[t.RG8]:bh.FLOAT,[t.RG8_SNORM]:bh.FLOAT,[t.RGB8]:bh.FLOAT,[t.RGB8_SNORM]:bh.FLOAT,[t.RGB565]:bh.FLOAT,[t.RGBA4]:bh.FLOAT,[t.RGB5_A1]:bh.FLOAT,[t.RGBA8]:bh.FLOAT,[t.RGBA8_SNORM]:bh.FLOAT,[t.RGB10_A2]:bh.FLOAT,[t.RGB10_A2UI]:bh.FLOAT,[t.SRGB8]:bh.FLOAT,[t.SRGB8_ALPHA8]:bh.FLOAT,[t.R16F]:bh.FLOAT,[t.RG16F]:bh.FLOAT,[t.RGB16F]:bh.FLOAT,[t.RGBA16F]:bh.FLOAT,[t.R32F]:bh.FLOAT,[t.RG32F]:bh.FLOAT,[t.RGB32F]:bh.FLOAT,[t.RGBA32F]:bh.FLOAT,[t.R11F_G11F_B10F]:bh.FLOAT,[t.RGB9_E5]:bh.FLOAT,[t.R8I]:bh.INT,[t.R8UI]:bh.UINT,[t.R16I]:bh.INT,[t.R16UI]:bh.UINT,[t.R32I]:bh.INT,[t.R32UI]:bh.UINT,[t.RG8I]:bh.INT,[t.RG8UI]:bh.UINT,[t.RG16I]:bh.INT,[t.RG16UI]:bh.UINT,[t.RG32I]:bh.INT,[t.RG32UI]:bh.UINT,[t.RGB8I]:bh.INT,[t.RGB8UI]:bh.UINT,[t.RGB16I]:bh.INT,[t.RGB16UI]:bh.UINT,[t.RGB32I]:bh.INT,[t.RGB32UI]:bh.UINT,[t.RGBA8I]:bh.INT,[t.RGBA8UI]:bh.UINT,[t.RGBA16I]:bh.INT,[t.RGBA16UI]:bh.UINT,[t.RGBA32I]:bh.INT,[t.RGBA32UI]:bh.UINT,[t.DEPTH_COMPONENT16]:bh.FLOAT,[t.DEPTH_COMPONENT24]:bh.FLOAT,[t.DEPTH_COMPONENT32F]:bh.FLOAT,[t.DEPTH_STENCIL]:bh.FLOAT,[t.DEPTH24_STENCIL8]:bh.FLOAT,[t.DEPTH32F_STENCIL8]:bh.FLOAT}:{[t.RGB]:bh.FLOAT,[t.RGBA]:bh.FLOAT,[t.ALPHA]:bh.FLOAT,[t.LUMINANCE]:bh.FLOAT,[t.LUMINANCE_ALPHA]:bh.FLOAT,[t.DEPTH_STENCIL]:bh.FLOAT},e}(t);const e=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);this.boundTextures.length=e;for(let s=0;s<e;s++)this.boundTextures[s]=null;this.emptyTextures={};const i=new vg(t.createTexture());t.bindTexture(t.TEXTURE_2D,i.texture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array(4)),this.emptyTextures[t.TEXTURE_2D]=i,this.emptyTextures[t.TEXTURE_CUBE_MAP]=new vg(t.createTexture()),t.bindTexture(t.TEXTURE_CUBE_MAP,this.emptyTextures[t.TEXTURE_CUBE_MAP].texture);for(let s=0;s<6;s++)t.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,null);t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MIN_FILTER,t.LINEAR);for(let s=0;s<this.boundTextures.length;s++)this.bind(null,s)}bind(t,e=0){const{gl:i}=this;if(t=t?.castToBaseTexture(),t?.valid&&!t.parentTextureArray){t.touched=this.renderer.textureGC.count;const s=t._glTextures[this.CONTEXT_UID]||this.initTexture(t);this.boundTextures[e]!==t&&(this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),i.bindTexture(t.target,s.texture)),s.dirtyId!==t.dirtyId?(this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),this.updateTexture(t)):s.dirtyStyleId!==t.dirtyStyleId&&this.updateTextureStyle(t),this.boundTextures[e]=t}else this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),i.bindTexture(i.TEXTURE_2D,this.emptyTextures[i.TEXTURE_2D].texture),this.boundTextures[e]=null}reset(){this._unknownBoundTextures=!0,this.hasIntegerTextures=!1,this.currentLocation=-1;for(let t=0;t<this.boundTextures.length;t++)this.boundTextures[t]=this.unknownTexture}unbind(t){const{gl:e,boundTextures:i}=this;if(this._unknownBoundTextures){this._unknownBoundTextures=!1;for(let t=0;t<i.length;t++)i[t]===this.unknownTexture&&this.bind(null,t)}for(let s=0;s<i.length;s++)i[s]===t&&(this.currentLocation!==s&&(e.activeTexture(e.TEXTURE0+s),this.currentLocation=s),e.bindTexture(t.target,this.emptyTextures[t.target].texture),i[s]=null)}ensureSamplerType(t){const{boundTextures:e,hasIntegerTextures:i,CONTEXT_UID:s}=this;if(i)for(let r=t-1;r>=0;--r){const t=e[r];t&&t._glTextures[s].samplerType!==bh.FLOAT&&this.renderer.texture.unbind(t)}}initTexture(t){const e=new vg(this.gl.createTexture());return e.dirtyId=-1,t._glTextures[this.CONTEXT_UID]=e,this.managedTextures.push(t),t.on("dispose",this.destroyTexture,this),e}initTextureType(t,e){e.internalFormat=this.internalFormats[t.type]?.[t.format]??t.format,e.samplerType=this.samplerTypes[e.internalFormat]??bh.FLOAT,2===this.webGLVersion&&t.type===xh.HALF_FLOAT?e.type=this.gl.HALF_FLOAT:e.type=t.type}updateTexture(t){const e=t._glTextures[this.CONTEXT_UID];if(!e)return;const i=this.renderer;if(this.initTextureType(t,e),t.resource?.upload(i,t,e))e.samplerType!==bh.FLOAT&&(this.hasIntegerTextures=!0);else{const s=t.realWidth,r=t.realHeight,n=i.gl;(e.width!==s||e.height!==r||e.dirtyId<0)&&(e.width=s,e.height=r,n.texImage2D(t.target,0,e.internalFormat,s,r,0,t.format,e.type,null))}t.dirtyStyleId!==e.dirtyStyleId&&this.updateTextureStyle(t),e.dirtyId=t.dirtyId}destroyTexture(t,e){const{gl:i}=this;if((t=t.castToBaseTexture())._glTextures[this.CONTEXT_UID]&&(this.unbind(t),i.deleteTexture(t._glTextures[this.CONTEXT_UID].texture),t.off("dispose",this.destroyTexture,this),delete t._glTextures[this.CONTEXT_UID],!e)){const e=this.managedTextures.indexOf(t);-1!==e&&wp(this.managedTextures,e,1)}}updateTextureStyle(t){const e=t._glTextures[this.CONTEXT_UID];e&&(t.mipmap!==Ph.POW2&&2===this.webGLVersion||t.isPowerOfTwo?e.mipmap=t.mipmap>=1:e.mipmap=!1,2===this.webGLVersion||t.isPowerOfTwo?e.wrapMode=t.wrapMode:e.wrapMode=_h.CLAMP,t.resource?.style(this.renderer,t,e)||this.setStyle(t,e),e.dirtyStyleId=t.dirtyStyleId)}setStyle(t,e){const i=this.gl;if(e.mipmap&&t.mipmap!==Ph.ON_MANUAL&&i.generateMipmap(t.target),i.texParameteri(t.target,i.TEXTURE_WRAP_S,e.wrapMode),i.texParameteri(t.target,i.TEXTURE_WRAP_T,e.wrapMode),e.mipmap){i.texParameteri(t.target,i.TEXTURE_MIN_FILTER,t.scaleMode===wh.LINEAR?i.LINEAR_MIPMAP_LINEAR:i.NEAREST_MIPMAP_NEAREST);const e=this.renderer.context.extensions.anisotropicFiltering;if(e&&t.anisotropicLevel>0&&t.scaleMode===wh.LINEAR){const s=Math.min(t.anisotropicLevel,i.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY_EXT));i.texParameterf(t.target,e.TEXTURE_MAX_ANISOTROPY_EXT,s)}}else i.texParameteri(t.target,i.TEXTURE_MIN_FILTER,t.scaleMode===wh.LINEAR?i.LINEAR:i.NEAREST);i.texParameteri(t.target,i.TEXTURE_MAG_FILTER,t.scaleMode===wh.LINEAR?i.LINEAR:i.NEAREST)}destroy(){this.renderer=null}}xg.extension={type:Up.RendererSystem,name:"texture"},Wp.add(xg);class bg{constructor(t){this.renderer=t}contextChange(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID}bind(t){const{gl:e,CONTEXT_UID:i}=this,s=t._glTransformFeedbacks[i]||this.createGLTransformFeedback(t);e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,s)}unbind(){const{gl:t}=this;t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null)}beginTransformFeedback(t,e){const{gl:i,renderer:s}=this;e&&s.shader.bind(e),i.beginTransformFeedback(t)}endTransformFeedback(){const{gl:t}=this;t.endTransformFeedback()}createGLTransformFeedback(t){const{gl:e,renderer:i,CONTEXT_UID:s}=this,r=e.createTransformFeedback();t._glTransformFeedbacks[s]=r,e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,r);for(let n=0;n<t.buffers.length;n++){const r=t.buffers[n];r&&(i.buffer.update(r),r._glBuffers[s].refCount++,e.bindBufferBase(e.TRANSFORM_FEEDBACK_BUFFER,n,r._glBuffers[s].buffer||null))}return e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,null),t.disposeRunner.add(this),r}disposeTransformFeedback(t,e){const i=t._glTransformFeedbacks[this.CONTEXT_UID],s=this.gl;t.disposeRunner.remove(this);const r=this.renderer.buffer;if(r)for(let n=0;n<t.buffers.length;n++){const i=t.buffers[n];if(!i)continue;const s=i._glBuffers[this.CONTEXT_UID];s&&(s.refCount--,0===s.refCount&&!e&&r.dispose(i,e))}i&&(e||s.deleteTransformFeedback(i),delete t._glTransformFeedbacks[this.CONTEXT_UID])}destroy(){this.renderer=null}}bg.extension={type:Up.RendererSystem,name:"transformFeedback"},Wp.add(bg);class wg{constructor(t){this.renderer=t}init(t){this.screen=new vf(0,0,t.width,t.height),this.element=t.view||Oh.ADAPTER.createCanvas(),this.resolution=t.resolution||Oh.RESOLUTION,this.autoDensity=!!t.autoDensity}resizeView(t,e){this.element.width=Math.round(t*this.resolution),this.element.height=Math.round(e*this.resolution);const i=this.element.width/this.resolution,s=this.element.height/this.resolution;this.screen.width=i,this.screen.height=s,this.autoDensity&&(this.element.style.width=`${i}px`,this.element.style.height=`${s}px`),this.renderer.emit("resize",i,s),this.renderer.runners.resize.emit(this.screen.width,this.screen.height)}destroy(t){t&&this.element.parentNode?.removeChild(this.element),this.renderer=null,this.element=null,this.screen=null}}wg.defaultOptions={width:800,height:600,resolution:void 0,autoDensity:!1},wg.extension={type:[Up.RendererSystem,Up.CanvasRendererSystem],name:"_view"},Wp.add(wg),Oh.PREFER_ENV=dh.WEBGL2,Oh.STRICT_TEXTURE_CACHE=!1,Oh.RENDER_OPTIONS={...gm.defaultOptions,...pm.defaultOptions,...wg.defaultOptions,...dg.defaultOptions},Object.defineProperties(Oh,{WRAP_MODE:{get:()=>tf.defaultOptions.wrapMode,set(t){Md("7.1.0","settings.WRAP_MODE is deprecated, use BaseTexture.defaultOptions.wrapMode"),tf.defaultOptions.wrapMode=t}},SCALE_MODE:{get:()=>tf.defaultOptions.scaleMode,set(t){Md("7.1.0","settings.SCALE_MODE is deprecated, use BaseTexture.defaultOptions.scaleMode"),tf.defaultOptions.scaleMode=t}},MIPMAP_TEXTURES:{get:()=>tf.defaultOptions.mipmap,set(t){Md("7.1.0","settings.MIPMAP_TEXTURES is deprecated, use BaseTexture.defaultOptions.mipmap"),tf.defaultOptions.mipmap=t}},ANISOTROPIC_LEVEL:{get:()=>tf.defaultOptions.anisotropicLevel,set(t){Md("7.1.0","settings.ANISOTROPIC_LEVEL is deprecated, use BaseTexture.defaultOptions.anisotropicLevel"),tf.defaultOptions.anisotropicLevel=t}},FILTER_RESOLUTION:{get:()=>(Md("7.1.0","settings.FILTER_RESOLUTION is deprecated, use Filter.defaultResolution"),dm.defaultResolution),set(t){dm.defaultResolution=t}},FILTER_MULTISAMPLE:{get:()=>(Md("7.1.0","settings.FILTER_MULTISAMPLE is deprecated, use Filter.defaultMultisample"),dm.defaultMultisample),set(t){dm.defaultMultisample=t}},SPRITE_MAX_TEXTURES:{get:()=>um.defaultMaxTextures,set(t){Md("7.1.0","settings.SPRITE_MAX_TEXTURES is deprecated, use BatchRenderer.defaultMaxTextures"),um.defaultMaxTextures=t}},SPRITE_BATCH_SIZE:{get:()=>um.defaultBatchSize,set(t){Md("7.1.0","settings.SPRITE_BATCH_SIZE is deprecated, use BatchRenderer.defaultBatchSize"),um.defaultBatchSize=t}},CAN_UPLOAD_SAME_BUFFER:{get:()=>um.canUploadSameBuffer,set(t){Md("7.1.0","settings.CAN_UPLOAD_SAME_BUFFER is deprecated, use BatchRenderer.canUploadSameBuffer"),um.canUploadSameBuffer=t}},GC_MODE:{get:()=>yg.defaultMode,set(t){Md("7.1.0","settings.GC_MODE is deprecated, use TextureGCSystem.defaultMode"),yg.defaultMode=t}},GC_MAX_IDLE:{get:()=>yg.defaultMaxIdle,set(t){Md("7.1.0","settings.GC_MAX_IDLE is deprecated, use TextureGCSystem.defaultMaxIdle"),yg.defaultMaxIdle=t}},GC_MAX_CHECK_COUNT:{get:()=>yg.defaultCheckCountMax,set(t){Md("7.1.0","settings.GC_MAX_CHECK_COUNT is deprecated, use TextureGCSystem.defaultCheckCountMax"),yg.defaultCheckCountMax=t}},PRECISION_VERTEX:{get:()=>im.defaultVertexPrecision,set(t){Md("7.1.0","settings.PRECISION_VERTEX is deprecated, use Program.defaultVertexPrecision"),im.defaultVertexPrecision=t}},PRECISION_FRAGMENT:{get:()=>im.defaultFragmentPrecision,set(t){Md("7.1.0","settings.PRECISION_FRAGMENT is deprecated, use Program.defaultFragmentPrecision"),im.defaultFragmentPrecision=t}}});var _g=/* @__PURE__ */(t=>(t[t.INTERACTION=50]="INTERACTION",t[t.HIGH=25]="HIGH",t[t.NORMAL=0]="NORMAL",t[t.LOW=-25]="LOW",t[t.UTILITY=-50]="UTILITY",t))(_g||{});class Pg{constructor(t,e=null,i=0,s=!1){this.next=null,this.previous=null,this._destroyed=!1,this.fn=t,this.context=e,this.priority=i,this.once=s}match(t,e=null){return this.fn===t&&this.context===e}emit(t){this.fn&&(this.context?this.fn.call(this.context,t):this.fn(t));const e=this.next;return this.once&&this.destroy(!0),this._destroyed&&(this.next=null),e}connect(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this}destroy(t=!1){this._destroyed=!0,this.fn=null,this.context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const e=this.next;return this.next=t?null:e,this.previous=null,e}}const Eg=class t{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new Pg(null,null,1/0),this.deltaMS=1/t.targetFPMS,this.elapsedMS=1/t.targetFPMS,this._tick=t=>{this._requestId=null,this.started&&(this.update(t),this.started&&null===this._requestId&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){null===this._requestId&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){null!==this._requestId&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(t,e,i=_g.NORMAL){return this._addListener(new Pg(t,e,i))}addOnce(t,e,i=_g.NORMAL){return this._addListener(new Pg(t,e,i,!0))}_addListener(t){let e=this._head.next,i=this._head;if(e){for(;e;){if(t.priority>e.priority){t.connect(i);break}i=e,e=e.next}t.previous||t.connect(i)}else t.connect(i);return this._startIfPossible(),this}remove(t,e){let i=this._head.next;for(;i;)i=i.match(t,e)?i.destroy():i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let t=0,e=this._head;for(;e=e.next;)t++;return t}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let t=this._head.next;for(;t;)t=t.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let i;if(e>this.lastTime){if(i=this.elapsedMS=e-this.lastTime,i>this._maxElapsedMS&&(i=this._maxElapsedMS),i*=this.speed,this._minElapsedMS){const t=e-this._lastFrame|0;if(t<this._minElapsedMS)return;this._lastFrame=e-t%this._minElapsedMS}this.deltaMS=i,this.deltaTime=this.deltaMS*t.targetFPMS;const s=this._head;let r=s.next;for(;r;)r=r.emit(this.deltaTime);s.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const i=Math.min(this.maxFPS,e),s=Math.min(Math.max(0,i)/1e3,t.targetFPMS);this._maxElapsedMS=1/s}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(t){if(0===t)this._minElapsedMS=0;else{const e=Math.max(this.minFPS,t);this._minElapsedMS=1/(e/1e3)}}static get shared(){if(!t._shared){const e=t._shared=new t;e.autoStart=!0,e._protected=!0}return t._shared}static get system(){if(!t._system){const e=t._system=new t;e.autoStart=!0,e._protected=!0}return t._system}};Eg.targetFPMS=.06;let Tg=Eg;Object.defineProperties(Oh,{TARGET_FPMS:{get:()=>Tg.targetFPMS,set(t){Md("7.1.0","settings.TARGET_FPMS is deprecated, use Ticker.targetFPMS"),Tg.targetFPMS=t}}});class Ag{static init(t){t=Object.assign({autoStart:!0,sharedTicker:!1},t),Object.defineProperty(this,"ticker",{set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,_g.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=t.sharedTicker?Tg.shared:new Tg,t.autoStart&&this.start()}static destroy(){if(this._ticker){const t=this._ticker;this.ticker=null,t.destroy()}}}Ag.extension=Up.Application,Wp.add(Ag);const Ig=[];Wp.handleByList(Up.Renderer,Ig);class Sg{constructor(t){this.renderer=t}contextChange(t){let e;if(1===this.renderer.context.webGLVersion){const i=t.getParameter(t.FRAMEBUFFER_BINDING);t.bindFramebuffer(t.FRAMEBUFFER,null),e=t.getParameter(t.SAMPLES),t.bindFramebuffer(t.FRAMEBUFFER,i)}else{const i=t.getParameter(t.DRAW_FRAMEBUFFER_BINDING);t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),e=t.getParameter(t.SAMPLES),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,i)}e>=Ch.HIGH?this.multisample=Ch.HIGH:e>=Ch.MEDIUM?this.multisample=Ch.MEDIUM:e>=Ch.LOW?this.multisample=Ch.LOW:this.multisample=Ch.NONE}destroy(){}}Sg.extension={type:Up.RendererSystem,name:"_multisample"},Wp.add(Sg);class Cg{constructor(t){this.buffer=t||null,this.updateID=-1,this.byteLength=-1,this.refCount=0}}class Mg{constructor(t){this.renderer=t,this.managedBuffers={},this.boundBufferBases={}}destroy(){this.renderer=null}contextChange(){this.disposeAll(!0),this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID}bind(t){const{gl:e,CONTEXT_UID:i}=this,s=t._glBuffers[i]||this.createGLBuffer(t);e.bindBuffer(t.type,s.buffer)}unbind(t){const{gl:e}=this;e.bindBuffer(t,null)}bindBufferBase(t,e){const{gl:i,CONTEXT_UID:s}=this;if(this.boundBufferBases[e]!==t){const r=t._glBuffers[s]||this.createGLBuffer(t);this.boundBufferBases[e]=t,i.bindBufferBase(i.UNIFORM_BUFFER,e,r.buffer)}}bindBufferRange(t,e,i){const{gl:s,CONTEXT_UID:r}=this;i=i||0;const n=t._glBuffers[r]||this.createGLBuffer(t);s.bindBufferRange(s.UNIFORM_BUFFER,e||0,n.buffer,256*i,256)}update(t){const{gl:e,CONTEXT_UID:i}=this,s=t._glBuffers[i]||this.createGLBuffer(t);if(t._updateID!==s.updateID)if(s.updateID=t._updateID,e.bindBuffer(t.type,s.buffer),s.byteLength>=t.data.byteLength)e.bufferSubData(t.type,0,t.data);else{const i=t.static?e.STATIC_DRAW:e.DYNAMIC_DRAW;s.byteLength=t.data.byteLength,e.bufferData(t.type,t.data,i)}}dispose(t,e){if(!this.managedBuffers[t.id])return;delete this.managedBuffers[t.id];const i=t._glBuffers[this.CONTEXT_UID],s=this.gl;t.disposeRunner.remove(this),i&&(e||s.deleteBuffer(i.buffer),delete t._glBuffers[this.CONTEXT_UID])}disposeAll(t){const e=Object.keys(this.managedBuffers);for(let i=0;i<e.length;i++)this.dispose(this.managedBuffers[e[i]],t)}createGLBuffer(t){const{CONTEXT_UID:e,gl:i}=this;return t._glBuffers[e]=new Cg(i.createBuffer()),this.managedBuffers[t.id]=t,t.disposeRunner.add(this),t._glBuffers[e]}}Mg.extension={type:Up.RendererSystem,name:"buffer"},Wp.add(Mg);class Og{constructor(t){this.renderer=t}render(t,e){const i=this.renderer;let s,r,n,o;if(e&&(s=e.renderTexture,r=e.clear,n=e.transform,o=e.skipUpdateTransform),this.renderingToScreen=!s,i.runners.prerender.emit(),i.emit("prerender"),i.projection.transform=n,!i.context.isLost){if(s||(this.lastObjectRendered=t),!o){const e=t.enableTempParent();t.updateTransform(),t.disableTempParent(e)}i.renderTexture.bind(s),i.batch.currentRenderer.start(),(r??i.background.clearBeforeRender)&&i.renderTexture.clear(),t.render(i),i.batch.currentRenderer.flush(),s&&(e.blit&&i.framebuffer.blit(),s.baseTexture.update()),i.runners.postrender.emit(),i.projection.transform=null,i.emit("postrender")}}destroy(){this.renderer=null,this.lastObjectRendered=null}}Og.extension={type:Up.RendererSystem,name:"objectRenderer"},Wp.add(Og);const Ng=class t extends mg{constructor(e){super(),this.type=ph.WEBGL,e=Object.assign({},Oh.RENDER_OPTIONS,e),this.gl=null,this.CONTEXT_UID=0,this.globalUniforms=new rm({projectionMatrix:new Pf},!0);const i={runners:["init","destroy","contextChange","resolutionChange","reset","update","postrender","prerender","resize"],systems:t.__systems,priority:["_view","textureGenerator","background","_plugin","startup","context","state","texture","buffer","geometry","framebuffer","transformFeedback","mask","scissor","stencil","projection","textureGC","filter","renderTexture","batch","objectRenderer","_multisample"]};this.setup(i),"useContextAlpha"in e&&(Md("7.0.0","options.useContextAlpha is deprecated, use options.premultipliedAlpha and options.backgroundAlpha instead"),e.premultipliedAlpha=e.useContextAlpha&&"notMultiplied"!==e.useContextAlpha,e.backgroundAlpha=!1===e.useContextAlpha?1:e.backgroundAlpha),this._plugin.rendererPlugins=t.__plugins,this.options=e,this.startup.run(this.options)}static test(t){return!t?.forceCanvas&&Fd()}render(t,e){this.objectRenderer.render(t,e)}resize(t,e){this._view.resizeView(t,e)}reset(){return this.runners.reset.emit(),this}clear(){this.renderTexture.bind(),this.renderTexture.clear()}destroy(t=!1){this.runners.destroy.items.reverse(),this.emitWithCustomOptions(this.runners.destroy,{_view:t}),super.destroy()}get plugins(){return this._plugin.plugins}get multisample(){return this._multisample.multisample}get width(){return this._view.element.width}get height(){return this._view.element.height}get resolution(){return this._view.resolution}set resolution(t){this._view.resolution=t,this.runners.resolutionChange.emit(t)}get autoDensity(){return this._view.autoDensity}get view(){return this._view.element}get screen(){return this._view.screen}get lastObjectRendered(){return this.objectRenderer.lastObjectRendered}get renderingToScreen(){return this.objectRenderer.renderingToScreen}get rendererLogId(){return`WebGL ${this.context.webGLVersion}`}get clearBeforeRender(){return Md("7.0.0","renderer.clearBeforeRender has been deprecated, please use renderer.background.clearBeforeRender instead."),this.background.clearBeforeRender}get useContextAlpha(){return Md("7.0.0","renderer.useContextAlpha has been deprecated, please use renderer.context.premultipliedAlpha instead."),this.context.useContextAlpha}get preserveDrawingBuffer(){return Md("7.0.0","renderer.preserveDrawingBuffer has been deprecated, we cannot truly know this unless pixi created the context"),this.context.preserveDrawingBuffer}get backgroundColor(){return Md("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color}set backgroundColor(t){Md("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color=t}get backgroundAlpha(){return Md("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha}set backgroundAlpha(t){Md("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha=t}get powerPreference(){return Md("7.0.0","renderer.powerPreference has been deprecated, we can only know this if pixi creates the context"),this.context.powerPreference}generateTexture(t,e){return this.textureGenerator.generateTexture(t,e)}};Ng.extension={type:Up.Renderer,priority:1},Ng.__plugins={},Ng.__systems={};let Lg=Ng;Wp.handleByMap(Up.RendererPlugin,Lg.__plugins),Wp.handleByMap(Up.RendererSystem,Lg.__systems),Wp.add(Lg);class Rg extends Jp{constructor(t,e){const{width:i,height:s}=e||{};super(i,s),this.items=[],this.itemDirtyIds=[];for(let r=0;r<t;r++){const t=new tf;this.items.push(t),this.itemDirtyIds.push(-2)}this.length=t,this._load=null,this.baseTexture=null}initFromArray(t,e){for(let i=0;i<this.length;i++)t[i]&&(t[i].castToBaseTexture?this.addBaseTextureAt(t[i].castToBaseTexture(),i):t[i]instanceof Jp?this.addResourceAt(t[i],i):this.addResourceAt(Vp(t[i],e),i))}dispose(){for(let t=0,e=this.length;t<e;t++)this.items[t].destroy();this.items=null,this.itemDirtyIds=null,this._load=null}addResourceAt(t,e){if(!this.items[e])throw new Error(`Index ${e} is out of bounds`);return t.valid&&!this.valid&&this.resize(t.width,t.height),this.items[e].setResource(t),this}bind(t){if(null!==this.baseTexture)throw new Error("Only one base texture per TextureArray is allowed");super.bind(t);for(let e=0;e<this.length;e++)this.items[e].parentTextureArray=t,this.items[e].on("update",t.update,t)}unbind(t){super.unbind(t);for(let e=0;e<this.length;e++)this.items[e].parentTextureArray=null,this.items[e].off("update",t.update,t)}load(){if(this._load)return this._load;const t=this.items.map(t=>t.resource).filter(t=>t).map(t=>t.load());return this._load=Promise.all(t).then(()=>{const{realWidth:t,realHeight:e}=this.items[0];return this.resize(t,e),this.update(),Promise.resolve(this)}),this._load}}class Bg extends xm{constructor(t){super(t)}static test(t){const{OffscreenCanvas:e}=globalThis;return!!(e&&t instanceof e)||globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement}}const kg=class t extends Rg{constructor(e,i){const{width:s,height:r,autoLoad:n,linkBaseTexture:o}=i||{};if(e&&e.length!==t.SIDES)throw new Error(`Invalid length. Got ${e.length}, expected 6`);super(6,{width:s,height:r});for(let a=0;a<t.SIDES;a++)this.items[a].target=vh.TEXTURE_CUBE_MAP_POSITIVE_X+a;this.linkBaseTexture=!1!==o,e&&this.initFromArray(e,i),!1!==n&&this.load()}bind(t){super.bind(t),t.target=vh.TEXTURE_CUBE_MAP}addBaseTextureAt(t,e,i){if(void 0===i&&(i=this.linkBaseTexture),!this.items[e])throw new Error(`Index ${e} is out of bounds`);if(!this.linkBaseTexture||t.parentTextureArray||Object.keys(t._glTextures).length>0){if(!t.resource)throw new Error("CubeResource does not support copying of renderTexture.");this.addResourceAt(t.resource,e)}else t.target=vh.TEXTURE_CUBE_MAP_POSITIVE_X+e,t.parentTextureArray=this.baseTexture,this.items[e]=t;return t.valid&&!this.valid&&this.resize(t.realWidth,t.realHeight),this.items[e]=t,this}upload(e,i,s){const r=this.itemDirtyIds;for(let n=0;n<t.SIDES;n++){const t=this.items[n];(r[n]<t.dirtyId||s.dirtyId<i.dirtyId)&&(t.valid&&t.resource?(t.resource.upload(e,t,s),r[n]=t.dirtyId):r[n]<-1&&(e.gl.texImage2D(t.target,0,s.internalFormat,i.realWidth,i.realHeight,0,i.format,s.type,null),r[n]=-1))}return!0}static test(e){return Array.isArray(e)&&e.length===t.SIDES}};kg.SIDES=6;let Fg=kg;class Dg extends xm{constructor(t,e){let i,s,r;e=e||{},"string"==typeof t?(i=Dg.EMPTY,s=t,r=!0):(i=t,s=null,r=!1),super(i),this.url=s,this.crossOrigin=e.crossOrigin??!0,this.alphaMode="number"==typeof e.alphaMode?e.alphaMode:null,this.ownsImageBitmap=e.ownsImageBitmap??r,this._load=null,!1!==e.autoLoad&&this.load()}load(){return this._load||(this._load=new Promise(async(t,e)=>{if(null!==this.url)try{const e=await Oh.ADAPTER.fetch(this.url,{mode:this.crossOrigin?"cors":"no-cors"});if(this.destroyed)return;const i=await e.blob();if(this.destroyed)return;const s=await createImageBitmap(i,{premultiplyAlpha:null===this.alphaMode||this.alphaMode===Eh.UNPACK?"premultiply":"none"});if(this.destroyed)return void s.close();this.source=s,this.update(),t(this)}catch(i){if(this.destroyed)return;e(i),this.onError.emit(i)}else t(this)})),this._load}upload(t,e,i){return this.source instanceof ImageBitmap?("number"==typeof this.alphaMode&&(e.alphaMode=this.alphaMode),super.upload(t,e,i)):(this.load(),!1)}dispose(){this.ownsImageBitmap&&this.source instanceof ImageBitmap&&this.source.close(),super.dispose(),this._load=null}static test(t){return!!globalThis.createImageBitmap&&typeof ImageBitmap<"u"&&("string"==typeof t||t instanceof ImageBitmap)}static get EMPTY(){return Dg._EMPTY=Dg._EMPTY??Oh.ADAPTER.createCanvas(0,0),Dg._EMPTY}}const Ug=class t extends xm{constructor(t,e){e=e||{},super(Oh.ADAPTER.createCanvas()),this._width=0,this._height=0,this.svg=t,this.scale=e.scale||1,this._overrideWidth=e.width,this._overrideHeight=e.height,this._resolve=null,this._crossorigin=e.crossorigin,this._load=null,!1!==e.autoLoad&&this.load()}load(){return this._load||(this._load=new Promise(e=>{if(this._resolve=()=>{this.update(),e(this)},t.SVG_XML.test(this.svg.trim())){if(!btoa)throw new Error("Your browser doesn't support base64 conversions.");this.svg=`data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(this.svg)))}`}this._loadSvg()})),this._load}_loadSvg(){const t=new Image;xm.crossOrigin(t,this.svg,this._crossorigin),t.src=this.svg,t.onerror=e=>{this._resolve&&(t.onerror=null,this.onError.emit(e))},t.onload=()=>{if(!this._resolve)return;const e=t.width,i=t.height;if(!e||!i)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");let s=e*this.scale,r=i*this.scale;(this._overrideWidth||this._overrideHeight)&&(s=this._overrideWidth||this._overrideHeight/i*e,r=this._overrideHeight||this._overrideWidth/e*i),s=Math.round(s),r=Math.round(r);const n=this.source;n.width=s,n.height=r,n._pixiId=`canvas_${Ep()}`,n.getContext("2d").drawImage(t,0,0,e,i,0,0,s,r),this._resolve(),this._resolve=null}}static getSize(e){const i=t.SVG_SIZE.exec(e),s={};return i&&(s[i[1]]=Math.round(parseFloat(i[3])),s[i[5]]=Math.round(parseFloat(i[7]))),s}dispose(){super.dispose(),this._resolve=null,this._crossorigin=null}static test(e,i){return"svg"===i||"string"==typeof e&&e.startsWith("data:image/svg+xml")||"string"==typeof e&&t.SVG_XML.test(e)}};Ug.SVG_XML=/^(<\?xml[^?]+\?>)?\s*(<!--[^(-->)]*-->)?\s*\<svg/m,Ug.SVG_SIZE=/<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i;let Gg=Ug;const Xg=class t extends xm{constructor(e,i){if(i=i||{},!(e instanceof HTMLVideoElement)){const s=document.createElement("video");!1!==i.autoLoad&&s.setAttribute("preload","auto"),!1!==i.playsinline&&(s.setAttribute("webkit-playsinline",""),s.setAttribute("playsinline","")),!0===i.muted&&(s.setAttribute("muted",""),s.muted=!0),!0===i.loop&&s.setAttribute("loop",""),!1!==i.autoPlay&&s.setAttribute("autoplay",""),"string"==typeof e&&(e=[e]);const r=e[0].src||e[0];xm.crossOrigin(s,r,i.crossorigin);for(let i=0;i<e.length;++i){const r=document.createElement("source");let{src:n,mime:o}=e[i];if(n=n||e[i],n.startsWith("data:"))o=n.slice(5,n.indexOf(";"));else if(!n.startsWith("blob:")){const e=n.split("?").shift().toLowerCase(),i=e.slice(e.lastIndexOf(".")+1);o=o||t.MIME_TYPES[i]||`video/${i}`}r.src=n,o&&(r.type=o),s.appendChild(r)}e=s}super(e),this.noSubImage=!0,this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=i.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=!1!==i.autoPlay,this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),!1!==i.autoLoad&&this.load()}update(t=0){if(!this.destroyed){if(this._updateFPS){const t=Tg.shared.elapsedMS*this.source.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-t)}(!this._updateFPS||this._msToNextUpdate<=0)&&(super.update(),this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0)}}_videoFrameRequestCallback(){this.update(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.source.requestVideoFrameCallback(this._videoFrameRequestCallback)}load(){if(this._load)return this._load;const t=this.source;return(t.readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),t.addEventListener("play",this._onPlayStart),t.addEventListener("pause",this._onPlayStop),t.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._onCanPlay():(t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlay),t.addEventListener("error",this._onError,!0)),this._load=new Promise((e,i)=>{this.valid?e(this):(this._resolve=e,this._reject=i,t.load())}),this._load}_onError(t){this.source.removeEventListener("error",this._onError,!0),this.onError.emit(t),this._reject&&(this._reject(t),this._reject=null,this._resolve=null)}_isSourcePlaying(){const t=this.source;return!t.paused&&!t.ended}_isSourceReady(){return this.source.readyState>2}_onPlayStart(){this.valid||this._onCanPlay(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.update(),this._msToNextUpdate=0)}_onCanPlay(){const t=this.source;t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlay);const e=this.valid;this._msToNextUpdate=0,this.update(),this._msToNextUpdate=0,!e&&this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&t.play()}dispose(){this._configureAutoUpdate();const t=this.source;t&&(t.removeEventListener("play",this._onPlayStart),t.removeEventListener("pause",this._onPlayStop),t.removeEventListener("seeked",this._onSeeked),t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlay),t.removeEventListener("error",this._onError,!0),t.pause(),t.src="",t.load()),super.dispose()}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){t!==this._autoUpdate&&(this._autoUpdate=t,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(t){t!==this._updateFPS&&(this._updateFPS=t,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.source.requestVideoFrameCallback?(this._isConnectedToTicker&&(Tg.shared.remove(this.update,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),null===this._videoFrameRequestCallbackHandle&&(this._videoFrameRequestCallbackHandle=this.source.requestVideoFrameCallback(this._videoFrameRequestCallback))):(null!==this._videoFrameRequestCallbackHandle&&(this.source.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(Tg.shared.add(this.update,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(null!==this._videoFrameRequestCallbackHandle&&(this.source.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(Tg.shared.remove(this.update,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e,i){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement||t.TYPES.includes(i)}};Xg.TYPES=["mp4","m4v","webm","ogg","ogv","h264","avi","mov"],Xg.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Wg=Xg;zp.push(Dg,bm,Bg,Wg,class extends xm{constructor(t){super(t)}static test(t){return!!globalThis.VideoFrame&&t instanceof globalThis.VideoFrame}},Gg,Kp,Fg,class extends Rg{constructor(t,e){const{width:i,height:s}=e||{};let r,n;Array.isArray(t)?(r=t,n=t.length):n=t,super(n,{width:i,height:s}),r&&this.initFromArray(r,e)}addBaseTextureAt(t,e){if(!t.resource)throw new Error("ArrayResource does not support RenderTexture");return this.addResourceAt(t.resource,e),this}bind(t){super.bind(t),t.target=vh.TEXTURE_2D_ARRAY}upload(t,e,i){const{length:s,itemDirtyIds:r,items:n}=this,{gl:o}=t;i.dirtyId<0&&o.texImage3D(o.TEXTURE_2D_ARRAY,0,i.internalFormat,this._width,this._height,s,0,e.format,i.type,null);for(let a=0;a<s;a++){const t=n[a];r[a]<t.dirtyId&&(r[a]=t.dirtyId,t.valid&&o.texSubImage3D(o.TEXTURE_2D_ARRAY,0,0,0,a,t.resource.width,t.resource.height,1,e.format,i.type,t.resource.source))}return!0}});class Yg{constructor(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.rect=null,this.updateID=-1}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}clear(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0}getRectangle(t){return this.minX>this.maxX||this.minY>this.maxY?vf.EMPTY:((t=t||new vf(0,0,1,1)).x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)}addPoint(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)}addPointMatrix(t,e){const{a:i,b:s,c:r,d:n,tx:o,ty:a}=t,l=i*e.x+r*e.y+o,h=s*e.x+n*e.y+a;this.minX=Math.min(this.minX,l),this.maxX=Math.max(this.maxX,l),this.minY=Math.min(this.minY,h),this.maxY=Math.max(this.maxY,h)}addQuad(t){let e=this.minX,i=this.minY,s=this.maxX,r=this.maxY,n=t[0],o=t[1];e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,n=t[2],o=t[3],e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,n=t[4],o=t[5],e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,n=t[6],o=t[7],e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,this.minX=e,this.minY=i,this.maxX=s,this.maxY=r}addFrame(t,e,i,s,r){this.addFrameMatrix(t.worldTransform,e,i,s,r)}addFrameMatrix(t,e,i,s,r){const n=t.a,o=t.b,a=t.c,l=t.d,h=t.tx,u=t.ty;let c=this.minX,d=this.minY,p=this.maxX,f=this.maxY,m=n*e+a*i+h,g=o*e+l*i+u;c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*s+a*i+h,g=o*s+l*i+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*e+a*r+h,g=o*e+l*r+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*s+a*r+h,g=o*s+l*r+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,this.minX=c,this.minY=d,this.maxX=p,this.maxY=f}addVertexData(t,e,i){let s=this.minX,r=this.minY,n=this.maxX,o=this.maxY;for(let a=e;a<i;a+=2){const e=t[a],i=t[a+1];s=e<s?e:s,r=i<r?i:r,n=e>n?e:n,o=i>o?i:o}this.minX=s,this.minY=r,this.maxX=n,this.maxY=o}addVertices(t,e,i,s){this.addVerticesMatrix(t.worldTransform,e,i,s)}addVerticesMatrix(t,e,i,s,r=0,n=r){const o=t.a,a=t.b,l=t.c,h=t.d,u=t.tx,c=t.ty;let d=this.minX,p=this.minY,f=this.maxX,m=this.maxY;for(let g=i;g<s;g+=2){const t=e[g],i=e[g+1],s=o*t+l*i+u,y=h*i+a*t+c;d=Math.min(d,s-r),f=Math.max(f,s+r),p=Math.min(p,y-n),m=Math.max(m,y+n)}this.minX=d,this.minY=p,this.maxX=f,this.maxY=m}addBounds(t){const e=this.minX,i=this.minY,s=this.maxX,r=this.maxY;this.minX=t.minX<e?t.minX:e,this.minY=t.minY<i?t.minY:i,this.maxX=t.maxX>s?t.maxX:s,this.maxY=t.maxY>r?t.maxY:r}addBoundsMask(t,e){const i=t.minX>e.minX?t.minX:e.minX,s=t.minY>e.minY?t.minY:e.minY,r=t.maxX<e.maxX?t.maxX:e.maxX,n=t.maxY<e.maxY?t.maxY:e.maxY;if(i<=r&&s<=n){const t=this.minX,e=this.minY,o=this.maxX,a=this.maxY;this.minX=i<t?i:t,this.minY=s<e?s:e,this.maxX=r>o?r:o,this.maxY=n>a?n:a}}addBoundsMatrix(t,e){this.addFrameMatrix(e,t.minX,t.minY,t.maxX,t.maxY)}addBoundsArea(t,e){const i=t.minX>e.x?t.minX:e.x,s=t.minY>e.y?t.minY:e.y,r=t.maxX<e.x+e.width?t.maxX:e.x+e.width,n=t.maxY<e.y+e.height?t.maxY:e.y+e.height;if(i<=r&&s<=n){const t=this.minX,e=this.minY,o=this.maxX,a=this.maxY;this.minX=i<t?i:t,this.minY=s<e?s:e,this.maxX=r>o?r:o,this.maxY=n>a?n:a}}pad(t=0,e=t){this.isEmpty()||(this.minX-=t,this.maxX+=t,this.minY-=e,this.maxY+=e)}addFramePad(t,e,i,s,r,n){t-=r,e-=n,i+=r,s+=n,this.minX=this.minX<t?this.minX:t,this.maxX=this.maxX>i?this.maxX:i,this.minY=this.minY<e?this.minY:e,this.maxY=this.maxY>s?this.maxY:s}}class Hg extends Qh{constructor(){super(),this.tempDisplayObjectParent=null,this.transform=new Rf,this.alpha=1,this.visible=!0,this.renderable=!0,this.cullable=!1,this.cullArea=null,this.parent=null,this.worldAlpha=1,this._lastSortedIndex=0,this._zIndex=0,this.filterArea=null,this.filters=null,this._enabledFilters=null,this._bounds=new Yg,this._localBounds=null,this._boundsID=0,this._boundsRect=null,this._localBoundsRect=null,this._mask=null,this._maskRefCount=0,this._destroyed=!1,this.isSprite=!1,this.isMask=!1}static mixin(t){const e=Object.keys(t);for(let i=0;i<e.length;++i){const s=e[i];Object.defineProperty(Hg.prototype,s,Object.getOwnPropertyDescriptor(t,s))}}get destroyed(){return this._destroyed}_recursivePostUpdateTransform(){this.parent?(this.parent._recursivePostUpdateTransform(),this.transform.updateTransform(this.parent.transform)):this.transform.updateTransform(this._tempDisplayObjectParent.transform)}updateTransform(){this._boundsID++,this.transform.updateTransform(this.parent.transform),this.worldAlpha=this.alpha*this.parent.worldAlpha}getBounds(t,e){return t||(this.parent?(this._recursivePostUpdateTransform(),this.updateTransform()):(this.parent=this._tempDisplayObjectParent,this.updateTransform(),this.parent=null)),this._bounds.updateID!==this._boundsID&&(this.calculateBounds(),this._bounds.updateID=this._boundsID),e||(this._boundsRect||(this._boundsRect=new vf),e=this._boundsRect),this._bounds.getRectangle(e)}getLocalBounds(t){t||(this._localBoundsRect||(this._localBoundsRect=new vf),t=this._localBoundsRect),this._localBounds||(this._localBounds=new Yg);const e=this.transform,i=this.parent;this.parent=null,this._tempDisplayObjectParent.worldAlpha=i?.worldAlpha??1,this.transform=this._tempDisplayObjectParent.transform;const s=this._bounds,r=this._boundsID;this._bounds=this._localBounds;const n=this.getBounds(!1,t);return this.parent=i,this.transform=e,this._bounds=s,this._bounds.updateID+=this._boundsID-r,n}toGlobal(t,e,i=!1){return i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)}toLocal(t,e,i,s){return e&&(t=e.toGlobal(t,i,s)),s||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,i)}setParent(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t}removeFromParent(){this.parent?.removeChild(this)}setTransform(t=0,e=0,i=1,s=1,r=0,n=0,o=0,a=0,l=0){return this.position.x=t,this.position.y=e,this.scale.x=i||1,this.scale.y=s||1,this.rotation=r,this.skew.x=n,this.skew.y=o,this.pivot.x=a,this.pivot.y=l,this}destroy(t){this.removeFromParent(),this._destroyed=!0,this.transform=null,this.parent=null,this._bounds=null,this.mask=null,this.cullArea=null,this.filters=null,this.filterArea=null,this.hitArea=null,this.eventMode="auto",this.interactiveChildren=!1,this.emit("destroyed"),this.removeAllListeners()}get _tempDisplayObjectParent(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new $g),this.tempDisplayObjectParent}enableTempParent(){const t=this.parent;return this.parent=this._tempDisplayObjectParent,t}disableTempParent(t){this.parent=t}get x(){return this.position.x}set x(t){this.transform.position.x=t}get y(){return this.position.y}set y(t){this.transform.position.y=t}get worldTransform(){return this.transform.worldTransform}get localTransform(){return this.transform.localTransform}get position(){return this.transform.position}set position(t){this.transform.position.copyFrom(t)}get scale(){return this.transform.scale}set scale(t){this.transform.scale.copyFrom(t)}get pivot(){return this.transform.pivot}set pivot(t){this.transform.pivot.copyFrom(t)}get skew(){return this.transform.skew}set skew(t){this.transform.skew.copyFrom(t)}get rotation(){return this.transform.rotation}set rotation(t){this.transform.rotation=t}get angle(){return this.transform.rotation*pf}set angle(t){this.transform.rotation=t*ff}get zIndex(){return this._zIndex}set zIndex(t){this._zIndex!==t&&(this._zIndex=t,this.parent&&(this.parent.sortDirty=!0))}get worldVisible(){let t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}get mask(){return this._mask}set mask(t){if(this._mask!==t){if(this._mask){const t=this._mask.isMaskData?this._mask.maskObject:this._mask;t&&(t._maskRefCount--,0===t._maskRefCount&&(t.renderable=!0,t.isMask=!1))}if(this._mask=t,this._mask){const t=this._mask.isMaskData?this._mask.maskObject:this._mask;t&&(0===t._maskRefCount&&(t.renderable=!1,t.isMask=!0),t._maskRefCount++)}}}}class $g extends Hg{constructor(){super(...arguments),this.sortDirty=null}}Hg.prototype.displayObjectUpdateTransform=Hg.prototype.updateTransform;const jg=new Pf;function zg(t,e){return t.zIndex===e.zIndex?t._lastSortedIndex-e._lastSortedIndex:t.zIndex-e.zIndex}const Vg=class t extends Hg{constructor(){super(),this.children=[],this.sortableChildren=t.defaultSortableChildren,this.sortDirty=!1}onChildrenChange(t){}addChild(...t){if(t.length>1)for(let e=0;e<t.length;e++)this.addChild(t[e]);else{const e=t[0];e.parent&&e.parent.removeChild(e),e.parent=this,this.sortDirty=!0,e.transform._parentID=-1,this.children.push(e),this._boundsID++,this.onChildrenChange(this.children.length-1),this.emit("childAdded",e,this,this.children.length-1),e.emit("added",this)}return t[0]}addChildAt(t,e){if(e<0||e>this.children.length)throw new Error(`${t}addChildAt: The index ${e} supplied is out of bounds ${this.children.length}`);return t.parent&&t.parent.removeChild(t),t.parent=this,this.sortDirty=!0,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),this.emit("childAdded",t,this,e),t}swapChildren(t,e){if(t===e)return;const i=this.getChildIndex(t),s=this.getChildIndex(e);this.children[i]=e,this.children[s]=t,this.onChildrenChange(i<s?i:s)}getChildIndex(t){const e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e}setChildIndex(t,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);const i=this.getChildIndex(t);wp(this.children,i,1),this.children.splice(e,0,t),this.onChildrenChange(e)}getChildAt(t){if(t<0||t>=this.children.length)throw new Error(`getChildAt: Index (${t}) does not exist.`);return this.children[t]}removeChild(...t){if(t.length>1)for(let e=0;e<t.length;e++)this.removeChild(t[e]);else{const e=t[0],i=this.children.indexOf(e);if(-1===i)return null;e.parent=null,e.transform._parentID=-1,wp(this.children,i,1),this._boundsID++,this.onChildrenChange(i),e.emit("removed",this),this.emit("childRemoved",e,this,i)}return t[0]}removeChildAt(t){const e=this.getChildAt(t);return e.parent=null,e.transform._parentID=-1,wp(this.children,t,1),this._boundsID++,this.onChildrenChange(t),e.emit("removed",this),this.emit("childRemoved",e,this,t),e}removeChildren(t=0,e=this.children.length){const i=t,s=e-i;let r;if(s>0&&s<=e){r=this.children.splice(i,s);for(let t=0;t<r.length;++t)r[t].parent=null,r[t].transform&&(r[t].transform._parentID=-1);this._boundsID++,this.onChildrenChange(t);for(let t=0;t<r.length;++t)r[t].emit("removed",this),this.emit("childRemoved",r[t],this,t);return r}if(0===s&&0===this.children.length)return[];throw new RangeError("removeChildren: numeric values are outside the acceptable range.")}sortChildren(){let t=!1;for(let e=0,i=this.children.length;e<i;++e){const i=this.children[e];i._lastSortedIndex=e,!t&&0!==i.zIndex&&(t=!0)}t&&this.children.length>1&&this.children.sort(zg),this.sortDirty=!1}updateTransform(){this.sortableChildren&&this.sortDirty&&this.sortChildren(),this._boundsID++,this.transform.updateTransform(this.parent.transform),this.worldAlpha=this.alpha*this.parent.worldAlpha;for(let t=0,e=this.children.length;t<e;++t){const e=this.children[t];e.visible&&e.updateTransform()}}calculateBounds(){this._bounds.clear(),this._calculateBounds();for(let t=0;t<this.children.length;t++){const e=this.children[t];if(e.visible&&e.renderable)if(e.calculateBounds(),e._mask){const t=e._mask.isMaskData?e._mask.maskObject:e._mask;t?(t.calculateBounds(),this._bounds.addBoundsMask(e._bounds,t._bounds)):this._bounds.addBounds(e._bounds)}else e.filterArea?this._bounds.addBoundsArea(e._bounds,e.filterArea):this._bounds.addBounds(e._bounds)}this._bounds.updateID=this._boundsID}getLocalBounds(t,e=!1){const i=super.getLocalBounds(t);if(!e)for(let s=0,r=this.children.length;s<r;++s){const t=this.children[s];t.visible&&t.updateTransform()}return i}_calculateBounds(){}_renderWithCulling(e){const i=e.renderTexture.sourceFrame;if(!(i.width>0&&i.height>0))return;let s,r;this.cullArea?(s=this.cullArea,r=this.worldTransform):this._render!==t.prototype._render&&(s=this.getBounds(!0));const n=e.projection.transform;if(n&&(r?(r=jg.copyFrom(r),r.prepend(n)):r=n),s&&i.intersects(s,r))this._render(e);else if(this.cullArea)return;for(let t=0,o=this.children.length;t<o;++t){const i=this.children[t],s=i.cullable;i.cullable=s||!this.cullArea,i.render(e),i.cullable=s}}render(t){if(this.visible&&!(this.worldAlpha<=0)&&this.renderable)if(this._mask||this.filters?.length)this.renderAdvanced(t);else if(this.cullable)this._renderWithCulling(t);else{this._render(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].render(t)}}renderAdvanced(t){const e=this.filters,i=this._mask;if(e){this._enabledFilters||(this._enabledFilters=[]),this._enabledFilters.length=0;for(let t=0;t<e.length;t++)e[t].enabled&&this._enabledFilters.push(e[t])}const s=e&&this._enabledFilters?.length||i&&(!i.isMaskData||i.enabled&&(i.autoDetect||i.type!==Sh.NONE));if(s&&t.batch.flush(),e&&this._enabledFilters?.length&&t.filter.push(this,this._enabledFilters),i&&t.mask.push(this,this._mask),this.cullable)this._renderWithCulling(t);else{this._render(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].render(t)}s&&t.batch.flush(),i&&t.mask.pop(this),e&&this._enabledFilters?.length&&t.filter.pop()}_render(t){}destroy(t){super.destroy(),this.sortDirty=!1;const e="boolean"==typeof t?t:t?.children,i=this.removeChildren(0,this.children.length);if(e)for(let s=0;s<i.length;++s)i[s].destroy(t)}get width(){return this.scale.x*this.getLocalBounds().width}set width(t){const e=this.getLocalBounds().width;this.scale.x=0!==e?t/e:1,this._width=t}get height(){return this.scale.y*this.getLocalBounds().height}set height(t){const e=this.getLocalBounds().height;this.scale.y=0!==e?t/e:1,this._height=t}};Vg.defaultSortableChildren=!1;let qg=Vg;qg.prototype.containerUpdateTransform=qg.prototype.updateTransform,Object.defineProperties(Oh,{SORTABLE_CHILDREN:{get:()=>qg.defaultSortableChildren,set(t){Md("7.1.0","settings.SORTABLE_CHILDREN is deprecated, use Container.defaultSortableChildren"),qg.defaultSortableChildren=t}}});const Jg=new gf,Kg=new Uint16Array([0,1,2,0,2,3]);class Zg extends qg{constructor(t){super(),this._anchor=new Nf(this._onAnchorUpdate,this,t?t.defaultAnchor.x:0,t?t.defaultAnchor.y:0),this._texture=null,this._width=0,this._height=0,this._tintColor=new pp(16777215),this._tintRGB=null,this.tint=16777215,this.blendMode=mh.NORMAL,this._cachedTint=16777215,this.uvs=null,this.texture=t||Em.EMPTY,this.vertexData=new Float32Array(8),this.vertexTrimmedData=null,this._transformID=-1,this._textureID=-1,this._transformTrimmedID=-1,this._textureTrimmedID=-1,this.indices=Kg,this.pluginName="batch",this.isSprite=!0,this._roundPixels=Oh.ROUND_PIXELS}_onTextureUpdate(){this._textureID=-1,this._textureTrimmedID=-1,this._cachedTint=16777215,this._width&&(this.scale.x=_p(this.scale.x)*this._width/this._texture.orig.width),this._height&&(this.scale.y=_p(this.scale.y)*this._height/this._texture.orig.height)}_onAnchorUpdate(){this._transformID=-1,this._transformTrimmedID=-1}calculateVertices(){const t=this._texture;if(this._transformID===this.transform._worldID&&this._textureID===t._updateID)return;this._textureID!==t._updateID&&(this.uvs=this._texture._uvs.uvsFloat32),this._transformID=this.transform._worldID,this._textureID=t._updateID;const e=this.transform.worldTransform,i=e.a,s=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty,l=this.vertexData,h=t.trim,u=t.orig,c=this._anchor;let d=0,p=0,f=0,m=0;if(h?(p=h.x-c._x*u.width,d=p+h.width,m=h.y-c._y*u.height,f=m+h.height):(p=-c._x*u.width,d=p+u.width,m=-c._y*u.height,f=m+u.height),l[0]=i*p+r*m+o,l[1]=n*m+s*p+a,l[2]=i*d+r*m+o,l[3]=n*m+s*d+a,l[4]=i*d+r*f+o,l[5]=n*f+s*d+a,l[6]=i*p+r*f+o,l[7]=n*f+s*p+a,this._roundPixels){const t=Oh.RESOLUTION;for(let e=0;e<l.length;++e)l[e]=Math.round(l[e]*t)/t}}calculateTrimmedVertices(){if(this.vertexTrimmedData){if(this._transformTrimmedID===this.transform._worldID&&this._textureTrimmedID===this._texture._updateID)return}else this.vertexTrimmedData=new Float32Array(8);this._transformTrimmedID=this.transform._worldID,this._textureTrimmedID=this._texture._updateID;const t=this._texture,e=this.vertexTrimmedData,i=t.orig,s=this._anchor,r=this.transform.worldTransform,n=r.a,o=r.b,a=r.c,l=r.d,h=r.tx,u=r.ty,c=-s._x*i.width,d=c+i.width,p=-s._y*i.height,f=p+i.height;if(e[0]=n*c+a*p+h,e[1]=l*p+o*c+u,e[2]=n*d+a*p+h,e[3]=l*p+o*d+u,e[4]=n*d+a*f+h,e[5]=l*f+o*d+u,e[6]=n*c+a*f+h,e[7]=l*f+o*c+u,this._roundPixels){const t=Oh.RESOLUTION;for(let i=0;i<e.length;++i)e[i]=Math.round(e[i]*t)/t}}_render(t){this.calculateVertices(),t.batch.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this)}_calculateBounds(){const t=this._texture.trim,e=this._texture.orig;!t||t.width===e.width&&t.height===e.height?(this.calculateVertices(),this._bounds.addQuad(this.vertexData)):(this.calculateTrimmedVertices(),this._bounds.addQuad(this.vertexTrimmedData))}getLocalBounds(t){return 0===this.children.length?(this._localBounds||(this._localBounds=new Yg),this._localBounds.minX=this._texture.orig.width*-this._anchor._x,this._localBounds.minY=this._texture.orig.height*-this._anchor._y,this._localBounds.maxX=this._texture.orig.width*(1-this._anchor._x),this._localBounds.maxY=this._texture.orig.height*(1-this._anchor._y),t||(this._localBoundsRect||(this._localBoundsRect=new vf),t=this._localBoundsRect),this._localBounds.getRectangle(t)):super.getLocalBounds.call(this,t)}containsPoint(t){this.worldTransform.applyInverse(t,Jg);const e=this._texture.orig.width,i=this._texture.orig.height,s=-e*this.anchor.x;let r=0;return Jg.x>=s&&Jg.x<s+e&&(r=-i*this.anchor.y,Jg.y>=r&&Jg.y<r+i)}destroy(t){if(super.destroy(t),this._texture.off("update",this._onTextureUpdate,this),this._anchor=null,"boolean"==typeof t?t:t?.texture){const e="boolean"==typeof t?t:t?.baseTexture;this._texture.destroy(!!e)}this._texture=null}static from(t,e){const i=t instanceof Em?t:Em.from(t,e);return new Zg(i)}set roundPixels(t){this._roundPixels!==t&&(this._transformID=-1,this._transformTrimmedID=-1),this._roundPixels=t}get roundPixels(){return this._roundPixels}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(t){const e=_p(this.scale.x)||1;this.scale.x=e*t/this._texture.orig.width,this._width=t}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(t){const e=_p(this.scale.y)||1;this.scale.y=e*t/this._texture.orig.height,this._height=t}get anchor(){return this._anchor}set anchor(t){this._anchor.copyFrom(t)}get tint(){return this._tintColor.value}set tint(t){this._tintColor.setValue(t),this._tintRGB=this._tintColor.toLittleEndianNumber()}get tintValue(){return this._tintColor.toNumber()}get texture(){return this._texture}set texture(t){this._texture!==t&&(this._texture&&this._texture.off("update",this._onTextureUpdate,this),this._texture=t||Em.EMPTY,this._cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.valid?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}const Qg={build(t){const e=t.points;let i,s,r,n,o,a;if(t.type===mf.CIRC){const e=t.shape;i=e.x,s=e.y,o=a=e.radius,r=n=0}else if(t.type===mf.ELIP){const e=t.shape;i=e.x,s=e.y,o=e.width,a=e.height,r=n=0}else{const e=t.shape,l=e.width/2,h=e.height/2;i=e.x+l,s=e.y+h,o=a=Math.max(0,Math.min(e.radius,Math.min(l,h))),r=l-o,n=h-a}if(!(o>=0&&a>=0&&r>=0&&n>=0))return void(e.length=0);const l=Math.ceil(2.3*Math.sqrt(o+a)),h=8*l+(r?4:0)+(n?4:0);if(e.length=h,0===h)return;if(0===l)return e.length=8,e[0]=e[6]=i+r,e[1]=e[3]=s+n,e[2]=e[4]=i-r,void(e[5]=e[7]=s-n);let u=0,c=4*l+(r?2:0)+2,d=c,p=h;{const t=r+o,a=n,l=i+t,h=i-t,f=s+a;if(e[u++]=l,e[u++]=f,e[--c]=f,e[--c]=h,n){const t=s-a;e[d++]=h,e[d++]=t,e[--p]=t,e[--p]=l}}for(let f=1;f<l;f++){const t=Math.PI/2*(f/l),h=r+Math.cos(t)*o,m=n+Math.sin(t)*a,g=i+h,y=i-h,v=s+m,x=s-m;e[u++]=g,e[u++]=v,e[--c]=v,e[--c]=y,e[d++]=y,e[d++]=x,e[--p]=x,e[--p]=g}{const t=n+a,o=i+r,l=i-r,h=s+t,c=s-t;e[u++]=o,e[u++]=h,e[--p]=c,e[--p]=o,r&&(e[u++]=l,e[u++]=h,e[--p]=c,e[--p]=l)}},triangulate(t,e){const i=t.points,s=e.points,r=e.indices;if(0===i.length)return;let n=s.length/2;const o=n;let a,l;if(t.type!==mf.RREC){const e=t.shape;a=e.x,l=e.y}else{const e=t.shape;a=e.x+e.width/2,l=e.y+e.height/2}const h=t.matrix;s.push(t.matrix?h.a*a+h.c*l+h.tx:a,t.matrix?h.b*a+h.d*l+h.ty:l),n++,s.push(i[0],i[1]);for(let u=2;u<i.length;u+=2)s.push(i[u],i[u+1]),r.push(n++,o,n);r.push(o+1,o,n)}};function ty(t,e=!1){const i=t.length;if(i<6)return;let s=0;for(let r=0,n=t[i-2],o=t[i-1];r<i;r+=2){const e=t[r],i=t[r+1];s+=(e-n)*(i+o),n=e,o=i}if(!e&&s>0||e&&s<=0){const e=i/2;for(let s=e+e%2;s<i;s+=2){const e=i-s-2,r=i-s-1,n=s,o=s+1;[t[e],t[n]]=[t[n],t[e]],[t[r],t[o]]=[t[o],t[r]]}}}const ey={build(t){t.points=t.shape.points.slice()},triangulate(t,e){let i=t.points;const s=t.holes,r=e.points,n=e.indices;if(i.length>=6){ty(i,!1);const t=[];for(let r=0;r<s.length;r++){const e=s[r];ty(e.points,!0),t.push(i.length/2),i=i.concat(e.points)}const e=Nt(i,t,2);if(!e)return;const o=r.length/2;for(let i=0;i<e.length;i+=3)n.push(e[i]+o),n.push(e[i+1]+o),n.push(e[i+2]+o);for(let s=0;s<i.length;s++)r.push(i[s])}}},iy={build(t){const e=t.shape,i=e.x,s=e.y,r=e.width,n=e.height,o=t.points;o.length=0,r>=0&&n>=0&&o.push(i,s,i+r,s,i+r,s+n,i,s+n)},triangulate(t,e){const i=t.points,s=e.points;if(0===i.length)return;const r=s.length/2;s.push(i[0],i[1],i[2],i[3],i[6],i[7],i[4],i[5]),e.indices.push(r,r+1,r+2,r+1,r+2,r+3)}},sy={build(t){Qg.build(t)},triangulate(t,e){Qg.triangulate(t,e)}};var ry=/* @__PURE__ */(t=>(t.MITER="miter",t.BEVEL="bevel",t.ROUND="round",t))(ry||{}),ny=/* @__PURE__ */(t=>(t.BUTT="butt",t.ROUND="round",t.SQUARE="square",t))(ny||{});const oy={adaptive:!0,maxLength:10,minSegments:8,maxSegments:2048,epsilon:1e-4,_segmentsCount(t,e=20){if(!this.adaptive||!t||isNaN(t))return e;let i=Math.ceil(t/this.maxLength);return i<this.minSegments?i=this.minSegments:i>this.maxSegments&&(i=this.maxSegments),i}};class ay{static curveTo(t,e,i,s,r,n){const o=n[n.length-2],a=n[n.length-1]-e,l=o-t,h=s-e,u=i-t,c=Math.abs(a*u-l*h);if(c<1e-8||0===r)return(n[n.length-2]!==t||n[n.length-1]!==e)&&n.push(t,e),null;const d=a*a+l*l,p=h*h+u*u,f=a*h+l*u,m=r*Math.sqrt(d)/c,g=r*Math.sqrt(p)/c,y=m*f/d,v=g*f/p,x=m*u+g*l,b=m*h+g*a,w=l*(g+y),_=a*(g+y),P=u*(m+v),E=h*(m+v);return{cx:x+t,cy:b+e,radius:r,startAngle:Math.atan2(_-b,w-x),endAngle:Math.atan2(E-b,P-x),anticlockwise:l*h>u*a}}static arc(t,e,i,s,r,n,o,a,l){const h=o-n,u=oy._segmentsCount(Math.abs(h)*r,40*Math.ceil(Math.abs(h)/df)),c=h/(2*u),d=2*c,p=Math.cos(c),f=Math.sin(c),m=u-1,g=m%1/m;for(let y=0;y<=m;++y){const t=c+n+d*(y+g*y),e=Math.cos(t),o=-Math.sin(t);l.push((p*e+f*o)*r+i,(p*-o+f*e)*r+s)}}}class ly{constructor(){this.reset()}begin(t,e,i){this.reset(),this.style=t,this.start=e,this.attribStart=i}end(t,e){this.attribSize=e-this.attribStart,this.size=t-this.start}reset(){this.style=null,this.size=0,this.start=0,this.attribStart=0,this.attribSize=0}}class hy{static curveLength(t,e,i,s,r,n,o,a){let l=0,h=0,u=0,c=0,d=0,p=0,f=0,m=0,g=0,y=0,v=0,x=t,b=e;for(let w=1;w<=10;++w)h=w/10,u=h*h,c=u*h,d=1-h,p=d*d,f=p*d,m=f*t+3*p*h*i+3*d*u*r+c*o,g=f*e+3*p*h*s+3*d*u*n+c*a,y=x-m,v=b-g,x=m,b=g,l+=Math.sqrt(y*y+v*v);return l}static curveTo(t,e,i,s,r,n,o){const a=o[o.length-2],l=o[o.length-1];o.length-=2;const h=oy._segmentsCount(hy.curveLength(a,l,t,e,i,s,r,n));let u=0,c=0,d=0,p=0,f=0;o.push(a,l);for(let m=1,g=0;m<=h;++m)g=m/h,u=1-g,c=u*u,d=c*u,p=g*g,f=p*g,o.push(d*a+3*c*g*t+3*u*p*i+f*r,d*l+3*c*g*e+3*u*p*s+f*n)}}function uy(t,e,i,s,r,n,o,a){let l,h;o?(l=s,h=-i):(l=-s,h=i);const u=t-i*r+l,c=e-s*r+h,d=t+i*n+l,p=e+s*n+h;return a.push(u,c,d,p),2}function cy(t,e,i,s,r,n,o,a){const l=i-t,h=s-e;let u=Math.atan2(l,h),c=Math.atan2(r-t,n-e);a&&u<c?u+=2*Math.PI:!a&&u>c&&(c+=2*Math.PI);let d=u;const p=c-u,f=Math.abs(p),m=Math.sqrt(l*l+h*h),g=1+(15*f*Math.sqrt(m)/Math.PI|0),y=p/g;if(d+=y,a){o.push(t,e,i,s);for(let i=1,s=d;i<g;i++,s+=y)o.push(t,e,t+Math.sin(s)*m,e+Math.cos(s)*m);o.push(t,e,r,n)}else{o.push(i,s,t,e);for(let i=1,s=d;i<g;i++,s+=y)o.push(t+Math.sin(s)*m,e+Math.cos(s)*m,t,e);o.push(r,n,t,e)}return 2*g}function dy(t,e){t.lineStyle.native?function(t,e){let i=0;const s=t.shape,r=t.points||s.points,n=s.type!==mf.POLY||s.closeStroke;if(0===r.length)return;const o=e.points,a=e.indices,l=r.length/2,h=o.length/2;let u=h;for(o.push(r[0],r[1]),i=1;i<l;i++)o.push(r[2*i],r[2*i+1]),a.push(u,u+1),u++;n&&a.push(u,h)}(t,e):function(t,e){const i=t.shape;let s=t.points||i.points.slice();const r=e.closePointEps;if(0===s.length)return;const n=t.lineStyle,o=new gf(s[0],s[1]),a=new gf(s[s.length-2],s[s.length-1]),l=i.type!==mf.POLY||i.closeStroke,h=Math.abs(o.x-a.x)<r&&Math.abs(o.y-a.y)<r;if(l){s=s.slice(),h&&(s.pop(),s.pop(),a.set(s[s.length-2],s[s.length-1]));const t=.5*(o.x+a.x),e=.5*(a.y+o.y);s.unshift(t,e),s.push(t,e)}const u=e.points,c=s.length/2;let d=s.length;const p=u.length/2,f=n.width/2,m=f*f,g=n.miterLimit*n.miterLimit;let y=s[0],v=s[1],x=s[2],b=s[3],w=0,_=0,P=-(v-b),E=y-x,T=0,A=0,I=Math.sqrt(P*P+E*E);P/=I,E/=I,P*=f,E*=f;const S=n.alignment,C=2*(1-S),M=2*S;l||(n.cap===ny.ROUND?d+=cy(y-P*(C-M)*.5,v-E*(C-M)*.5,y-P*C,v-E*C,y+P*M,v+E*M,u,!0)+2:n.cap===ny.SQUARE&&(d+=uy(y,v,P,E,C,M,!0,u))),u.push(y-P*C,v-E*C,y+P*M,v+E*M);for(let L=1;L<c-1;++L){y=s[2*(L-1)],v=s[2*(L-1)+1],x=s[2*L],b=s[2*L+1],w=s[2*(L+1)],_=s[2*(L+1)+1],P=-(v-b),E=y-x,I=Math.sqrt(P*P+E*E),P/=I,E/=I,P*=f,E*=f,T=-(b-_),A=x-w,I=Math.sqrt(T*T+A*A),T/=I,A/=I,T*=f,A*=f;const t=x-y,e=v-b,i=x-w,r=_-b,o=t*i+e*r,a=e*i-r*t,l=a<0;if(Math.abs(a)<.001*Math.abs(o)){u.push(x-P*C,b-E*C,x+P*M,b+E*M),o>=0&&(n.join===ry.ROUND?d+=cy(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+4:d+=2,u.push(x-T*M,b-A*M,x+T*C,b+A*C));continue}const h=(-P+y)*(-E+b)-(-P+x)*(-E+v),c=(-T+w)*(-A+b)-(-T+x)*(-A+_),p=(t*c-i*h)/a,S=(r*h-e*c)/a,O=(p-x)*(p-x)+(S-b)*(S-b),N=x+(p-x)*C,R=b+(S-b)*C,B=x-(p-x)*M,k=b-(S-b)*M,F=l?C:M,D=O<=Math.min(t*t+e*e,i*i+r*r)+F*F*m;let U=n.join;if(U===ry.MITER&&O/m>g&&(U=ry.BEVEL),D)switch(U){case ry.MITER:u.push(N,R,B,k);break;case ry.BEVEL:l?u.push(N,R,x+P*M,b+E*M,N,R,x+T*M,b+A*M):u.push(x-P*C,b-E*C,B,k,x-T*C,b-A*C,B,k),d+=2;break;case ry.ROUND:l?(u.push(N,R,x+P*M,b+E*M),d+=cy(x,b,x+P*M,b+E*M,x+T*M,b+A*M,u,!0)+4,u.push(N,R,x+T*M,b+A*M)):(u.push(x-P*C,b-E*C,B,k),d+=cy(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+4,u.push(x-T*C,b-A*C,B,k))}else{switch(u.push(x-P*C,b-E*C,x+P*M,b+E*M),U){case ry.MITER:l?u.push(B,k,B,k):u.push(N,R,N,R),d+=2;break;case ry.ROUND:d+=l?cy(x,b,x+P*M,b+E*M,x+T*M,b+A*M,u,!0)+2:cy(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+2}u.push(x-T*C,b-A*C,x+T*M,b+A*M),d+=2}}y=s[2*(c-2)],v=s[2*(c-2)+1],x=s[2*(c-1)],b=s[2*(c-1)+1],P=-(v-b),E=y-x,I=Math.sqrt(P*P+E*E),P/=I,E/=I,P*=f,E*=f,u.push(x-P*C,b-E*C,x+P*M,b+E*M),l||(n.cap===ny.ROUND?d+=cy(x-P*(C-M)*.5,b-E*(C-M)*.5,x-P*C,b-E*C,x+P*M,b+E*M,u,!1)+2:n.cap===ny.SQUARE&&(d+=uy(x,b,P,E,C,M,!1,u)));const O=e.indices,N=oy.epsilon*oy.epsilon;for(let L=p;L<d+p-2;++L)y=u[2*L],v=u[2*L+1],x=u[2*(L+1)],b=u[2*(L+1)+1],w=u[2*(L+2)],_=u[2*(L+2)+1],!(Math.abs(y*(b-_)+x*(_-v)+w*(v-b))<N)&&O.push(L,L+1,L+2)}(t,e)}class py{static curveLength(t,e,i,s,r,n){const o=t-2*i+r,a=e-2*s+n,l=2*i-2*t,h=2*s-2*e,u=4*(o*o+a*a),c=4*(o*l+a*h),d=l*l+h*h,p=2*Math.sqrt(u+c+d),f=Math.sqrt(u),m=2*u*f,g=2*Math.sqrt(d),y=c/f;return(m*p+f*c*(p-g)+(4*d*u-c*c)*Math.log((2*f+y+p)/(y+g)))/(4*m)}static curveTo(t,e,i,s,r){const n=r[r.length-2],o=r[r.length-1],a=oy._segmentsCount(py.curveLength(n,o,t,e,i,s));let l=0,h=0;for(let u=1;u<=a;++u){const c=u/a;l=n+(t-n)*c,h=o+(e-o)*c,r.push(l+(t+(i-t)*c-l)*c,h+(e+(s-e)*c-h)*c)}}}const fy={[mf.POLY]:ey,[mf.CIRC]:Qg,[mf.ELIP]:Qg,[mf.RECT]:iy,[mf.RREC]:sy},my=[],gy=[];class yy{constructor(t,e=null,i=null,s=null){this.points=[],this.holes=[],this.shape=t,this.lineStyle=i,this.fillStyle=e,this.matrix=s,this.type=t.type}clone(){return new yy(this.shape,this.fillStyle,this.lineStyle,this.matrix)}destroy(){this.shape=null,this.holes.length=0,this.holes=null,this.points.length=0,this.points=null,this.lineStyle=null,this.fillStyle=null}}const vy=new gf,xy=class t extends cf{constructor(){super(),this.closePointEps=1e-4,this.boundsPadding=0,this.uvsFloat32=null,this.indicesUint16=null,this.batchable=!1,this.points=[],this.colors=[],this.uvs=[],this.indices=[],this.textureIds=[],this.graphicsData=[],this.drawCalls=[],this.batchDirty=-1,this.batches=[],this.dirty=0,this.cacheDirty=-1,this.clearDirty=0,this.shapeIndex=0,this._bounds=new Yg,this.boundsDirty=-1}get bounds(){return this.updateBatches(),this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.calculateBounds()),this._bounds}invalidate(){this.boundsDirty=-1,this.dirty++,this.batchDirty++,this.shapeIndex=0,this.points.length=0,this.colors.length=0,this.uvs.length=0,this.indices.length=0,this.textureIds.length=0;for(let t=0;t<this.drawCalls.length;t++)this.drawCalls[t].texArray.clear(),gy.push(this.drawCalls[t]);this.drawCalls.length=0;for(let t=0;t<this.batches.length;t++){const e=this.batches[t];e.reset(),my.push(e)}this.batches.length=0}clear(){return this.graphicsData.length>0&&(this.invalidate(),this.clearDirty++,this.graphicsData.length=0),this}drawShape(t,e=null,i=null,s=null){const r=new yy(t,e,i,s);return this.graphicsData.push(r),this.dirty++,this}drawHole(t,e=null){if(!this.graphicsData.length)return null;const i=new yy(t,null,null,e),s=this.graphicsData[this.graphicsData.length-1];return i.lineStyle=s.lineStyle,s.holes.push(i),this.dirty++,this}destroy(){super.destroy();for(let t=0;t<this.graphicsData.length;++t)this.graphicsData[t].destroy();this.points.length=0,this.points=null,this.colors.length=0,this.colors=null,this.uvs.length=0,this.uvs=null,this.indices.length=0,this.indices=null,this.indexBuffer.destroy(),this.indexBuffer=null,this.graphicsData.length=0,this.graphicsData=null,this.drawCalls.length=0,this.drawCalls=null,this.batches.length=0,this.batches=null,this._bounds=null}containsPoint(t){const e=this.graphicsData;for(let i=0;i<e.length;++i){const s=e[i];if(s.fillStyle.visible&&s.shape&&(s.matrix?s.matrix.applyInverse(t,vy):vy.copyFrom(t),s.shape.contains(vy.x,vy.y))){let t=!1;if(s.holes)for(let e=0;e<s.holes.length;e++)if(s.holes[e].shape.contains(vy.x,vy.y)){t=!0;break}if(!t)return!0}}return!1}updateBatches(){if(!this.graphicsData.length)return void(this.batchable=!0);if(!this.validateBatching())return;this.cacheDirty=this.dirty;const t=this.uvs,e=this.graphicsData;let i=null,s=null;this.batches.length>0&&(i=this.batches[this.batches.length-1],s=i.style);for(let a=this.shapeIndex;a<e.length;a++){this.shapeIndex++;const r=e[a],n=r.fillStyle,o=r.lineStyle;fy[r.type].build(r),r.matrix&&this.transformPoints(r.points,r.matrix),(n.visible||o.visible)&&this.processHoles(r.holes);for(let e=0;e<2;e++){const a=0===e?n:o;if(!a.visible)continue;const l=a.texture.baseTexture,h=this.indices.length,u=this.points.length/2;l.wrapMode=_h.REPEAT,0===e?this.processFill(r):this.processLine(r);const c=this.points.length/2-u;0!==c&&(i&&!this._compareStyles(s,a)&&(i.end(h,u),i=null),i||(i=my.pop()||new ly,i.begin(a,h,u),this.batches.push(i),s=a),this.addUvs(this.points,t,a.texture,u,c,a.matrix))}}const r=this.indices.length,n=this.points.length/2;if(i&&i.end(r,n),0===this.batches.length)return void(this.batchable=!0);const o=n>65535;this.indicesUint16&&this.indices.length===this.indicesUint16.length&&o===this.indicesUint16.BYTES_PER_ELEMENT>2?this.indicesUint16.set(this.indices):this.indicesUint16=o?new Uint32Array(this.indices):new Uint16Array(this.indices),this.batchable=this.isBatchable(),this.batchable?this.packBatches():this.buildDrawCalls()}_compareStyles(t,e){return!(!t||!e||t.texture.baseTexture!==e.texture.baseTexture||t.color+t.alpha!==e.color+e.alpha||!!t.native!=!!e.native)}validateBatching(){if(this.dirty===this.cacheDirty||!this.graphicsData.length)return!1;for(let t=0,e=this.graphicsData.length;t<e;t++){const e=this.graphicsData[t],i=e.fillStyle,s=e.lineStyle;if(i&&!i.texture.baseTexture.valid||s&&!s.texture.baseTexture.valid)return!1}return!0}packBatches(){this.batchDirty++,this.uvsFloat32=new Float32Array(this.uvs);const t=this.batches;for(let e=0,i=t.length;e<i;e++){const i=t[e];for(let t=0;t<i.size;t++){const e=i.start+t;this.indicesUint16[e]=this.indicesUint16[e]-i.attribStart}}}isBatchable(){if(this.points.length>131070)return!1;const e=this.batches;for(let t=0;t<e.length;t++)if(e[t].style.native)return!1;return this.points.length<2*t.BATCHABLE_SIZE}buildDrawCalls(){let t=++tf._globalBatch;for(let u=0;u<this.drawCalls.length;u++)this.drawCalls[u].texArray.clear(),gy.push(this.drawCalls[u]);this.drawCalls.length=0;const e=this.colors,i=this.textureIds;let s=gy.pop();s||(s=new ef,s.texArray=new am),s.texArray.count=0,s.start=0,s.size=0,s.type=gh.TRIANGLES;let r=0,n=null,o=0,a=!1,l=gh.TRIANGLES,h=0;this.drawCalls.push(s);for(let u=0;u<this.batches.length;u++){const c=this.batches[u],d=8,p=c.style,f=p.texture.baseTexture;a!==!!p.native&&(a=!!p.native,l=a?gh.LINES:gh.TRIANGLES,n=null,r=d,t++),n!==f&&(n=f,f._batchEnabled!==t&&(r===d&&(t++,r=0,s.size>0&&(s=gy.pop(),s||(s=new ef,s.texArray=new am),this.drawCalls.push(s)),s.start=h,s.size=0,s.texArray.count=0,s.type=l),f.touched=1,f._batchEnabled=t,f._batchLocation=r,f.wrapMode=_h.REPEAT,s.texArray.elements[s.texArray.count++]=f,r++)),s.size+=c.size,h+=c.size,o=f._batchLocation,this.addColors(e,p.color,p.alpha,c.attribSize,c.attribStart),this.addTextureIds(i,o,c.attribSize,c.attribStart)}tf._globalBatch=t,this.packAttributes()}packAttributes(){const t=this.points,e=this.uvs,i=this.colors,s=this.textureIds,r=new ArrayBuffer(3*t.length*4),n=new Float32Array(r),o=new Uint32Array(r);let a=0;for(let l=0;l<t.length/2;l++)n[a++]=t[2*l],n[a++]=t[2*l+1],n[a++]=e[2*l],n[a++]=e[2*l+1],o[a++]=i[l],n[a++]=s[l];this._buffer.update(r),this._indexBuffer.update(this.indicesUint16)}processFill(t){t.holes.length?ey.triangulate(t,this):fy[t.type].triangulate(t,this)}processLine(t){dy(t,this);for(let e=0;e<t.holes.length;e++)dy(t.holes[e],this)}processHoles(t){for(let e=0;e<t.length;e++){const i=t[e];fy[i.type].build(i),i.matrix&&this.transformPoints(i.points,i.matrix)}}calculateBounds(){const t=this._bounds;t.clear(),t.addVertexData(this.points,0,this.points.length),t.pad(this.boundsPadding,this.boundsPadding)}transformPoints(t,e){for(let i=0;i<t.length/2;i++){const s=t[2*i],r=t[2*i+1];t[2*i]=e.a*s+e.c*r+e.tx,t[2*i+1]=e.b*s+e.d*r+e.ty}}addColors(t,e,i,s,r=0){const n=pp.shared.setValue(e).toLittleEndianNumber(),o=pp.shared.setValue(n).toPremultiplied(i);t.length=Math.max(t.length,r+s);for(let a=0;a<s;a++)t[r+a]=o}addTextureIds(t,e,i,s=0){t.length=Math.max(t.length,s+i);for(let r=0;r<i;r++)t[s+r]=e}addUvs(t,e,i,s,r,n=null){let o=0;const a=e.length,l=i.frame;for(;o<r;){let i=t[2*(s+o)],r=t[2*(s+o)+1];if(n){const t=n.a*i+n.c*r+n.tx;r=n.b*i+n.d*r+n.ty,i=t}o++,e.push(i/l.width,r/l.height)}const h=i.baseTexture;(l.width<h.width||l.height<h.height)&&this.adjustUvs(e,i,a,r)}adjustUvs(t,e,i,s){const r=e.baseTexture,n=1e-6,o=i+2*s,a=e.frame,l=a.width/r.width,h=a.height/r.height;let u=a.x/a.width,c=a.y/a.height,d=Math.floor(t[i]+n),p=Math.floor(t[i+1]+n);for(let f=i+2;f<o;f+=2)d=Math.min(d,Math.floor(t[f]+n)),p=Math.min(p,Math.floor(t[f+1]+n));u-=d,c-=p;for(let f=i;f<o;f+=2)t[f]=(t[f]+u)*l,t[f+1]=(t[f+1]+c)*h}};xy.BATCHABLE_SIZE=100;let by=xy;class wy{constructor(){this.color=16777215,this.alpha=1,this.texture=Em.WHITE,this.matrix=null,this.visible=!1,this.reset()}clone(){const t=new wy;return t.color=this.color,t.alpha=this.alpha,t.texture=this.texture,t.matrix=this.matrix,t.visible=this.visible,t}reset(){this.color=16777215,this.alpha=1,this.texture=Em.WHITE,this.matrix=null,this.visible=!1}destroy(){this.texture=null,this.matrix=null}}class _y extends wy{constructor(){super(...arguments),this.width=0,this.alignment=.5,this.native=!1,this.cap=ny.BUTT,this.join=ry.MITER,this.miterLimit=10}clone(){const t=new _y;return t.color=this.color,t.alpha=this.alpha,t.texture=this.texture,t.matrix=this.matrix,t.visible=this.visible,t.width=this.width,t.alignment=this.alignment,t.native=this.native,t.cap=this.cap,t.join=this.join,t.miterLimit=this.miterLimit,t}reset(){super.reset(),this.color=0,this.alignment=.5,this.width=0,this.native=!1,this.cap=ny.BUTT,this.join=ry.MITER,this.miterLimit=10}}const Py={},Ey=class t extends qg{constructor(t=null){super(),this.shader=null,this.pluginName="batch",this.currentPath=null,this.batches=[],this.batchTint=-1,this.batchDirty=-1,this.vertexData=null,this._fillStyle=new wy,this._lineStyle=new _y,this._matrix=null,this._holeMode=!1,this.state=jp.for2d(),this._geometry=t||new by,this._geometry.refCount++,this._transformID=-1,this._tintColor=new pp(16777215),this.blendMode=mh.NORMAL}get geometry(){return this._geometry}clone(){return this.finishPoly(),new t(this._geometry)}set blendMode(t){this.state.blendMode=t}get blendMode(){return this.state.blendMode}get tint(){return this._tintColor.value}set tint(t){this._tintColor.setValue(t)}get fill(){return this._fillStyle}get line(){return this._lineStyle}lineStyle(t=null,e=0,i,s=.5,r=!1){return"number"==typeof t&&(t={width:t,color:e,alpha:i,alignment:s,native:r}),this.lineTextureStyle(t)}lineTextureStyle(t){const e={width:0,texture:Em.WHITE,color:t?.texture?16777215:0,matrix:null,alignment:.5,native:!1,cap:ny.BUTT,join:ry.MITER,miterLimit:10};t=Object.assign(e,t),this.normalizeColor(t),this.currentPath&&this.startPoly();const i=t.width>0&&t.alpha>0;return i?(t.matrix&&(t.matrix=t.matrix.clone(),t.matrix.invert()),Object.assign(this._lineStyle,{visible:i},t)):this._lineStyle.reset(),this}startPoly(){if(this.currentPath){const t=this.currentPath.points,e=this.currentPath.points.length;e>2&&(this.drawShape(this.currentPath),this.currentPath=new wf,this.currentPath.closeStroke=!1,this.currentPath.points.push(t[e-2],t[e-1]))}else this.currentPath=new wf,this.currentPath.closeStroke=!1}finishPoly(){this.currentPath&&(this.currentPath.points.length>2?(this.drawShape(this.currentPath),this.currentPath=null):this.currentPath.points.length=0)}moveTo(t,e){return this.startPoly(),this.currentPath.points[0]=t,this.currentPath.points[1]=e,this}lineTo(t,e){this.currentPath||this.moveTo(0,0);const i=this.currentPath.points,s=i[i.length-2],r=i[i.length-1];return(s!==t||r!==e)&&i.push(t,e),this}_initCurve(t=0,e=0){this.currentPath?0===this.currentPath.points.length&&(this.currentPath.points=[t,e]):this.moveTo(t,e)}quadraticCurveTo(t,e,i,s){this._initCurve();const r=this.currentPath.points;return 0===r.length&&this.moveTo(0,0),py.curveTo(t,e,i,s,r),this}bezierCurveTo(t,e,i,s,r,n){return this._initCurve(),hy.curveTo(t,e,i,s,r,n,this.currentPath.points),this}arcTo(t,e,i,s,r){this._initCurve(t,e);const n=this.currentPath.points,o=ay.curveTo(t,e,i,s,r,n);if(o){const{cx:t,cy:e,radius:i,startAngle:s,endAngle:r,anticlockwise:n}=o;this.arc(t,e,i,s,r,n)}return this}arc(t,e,i,s,r,n=!1){if(s===r)return this;if(!n&&r<=s?r+=df:n&&s<=r&&(s+=df),r-s===0)return this;const o=t+Math.cos(s)*i,a=e+Math.sin(s)*i,l=this._geometry.closePointEps;let h=this.currentPath?this.currentPath.points:null;if(h){const t=Math.abs(h[h.length-2]-o),e=Math.abs(h[h.length-1]-a);t<l&&e<l||h.push(o,a)}else this.moveTo(o,a),h=this.currentPath.points;return ay.arc(o,a,t,e,i,s,r,n,h),this}beginFill(t=0,e){return this.beginTextureFill({texture:Em.WHITE,color:t,alpha:e})}normalizeColor(t){const e=pp.shared.setValue(t.color??0);t.color=e.toNumber(),t.alpha??(t.alpha=e.alpha)}beginTextureFill(t){const e={texture:Em.WHITE,color:16777215,matrix:null};t=Object.assign(e,t),this.normalizeColor(t),this.currentPath&&this.startPoly();const i=t.alpha>0;return i?(t.matrix&&(t.matrix=t.matrix.clone(),t.matrix.invert()),Object.assign(this._fillStyle,{visible:i},t)):this._fillStyle.reset(),this}endFill(){return this.finishPoly(),this._fillStyle.reset(),this}drawRect(t,e,i,s){return this.drawShape(new vf(t,e,i,s))}drawRoundedRect(t,e,i,s,r){return this.drawShape(new _f(t,e,i,s,r))}drawCircle(t,e,i){return this.drawShape(new xf(t,e,i))}drawEllipse(t,e,i,s){return this.drawShape(new bf(t,e,i,s))}drawPolygon(...t){let e,i=!0;const s=t[0];s.points?(i=s.closeStroke,e=s.points):e=Array.isArray(t[0])?t[0]:t;const r=new wf(e);return r.closeStroke=i,this.drawShape(r),this}drawShape(t){return this._holeMode?this._geometry.drawHole(t,this._matrix):this._geometry.drawShape(t,this._fillStyle.clone(),this._lineStyle.clone(),this._matrix),this}clear(){return this._geometry.clear(),this._lineStyle.reset(),this._fillStyle.reset(),this._boundsID++,this._matrix=null,this._holeMode=!1,this.currentPath=null,this}isFastRect(){const t=this._geometry.graphicsData;return!(1!==t.length||t[0].shape.type!==mf.RECT||t[0].matrix||t[0].holes.length||t[0].lineStyle.visible&&t[0].lineStyle.width)}_render(t){this.finishPoly();const e=this._geometry;e.updateBatches(),e.batchable?(this.batchDirty!==e.batchDirty&&this._populateBatches(),this._renderBatched(t)):(t.batch.flush(),this._renderDirect(t))}_populateBatches(){const t=this._geometry,e=this.blendMode,i=t.batches.length;this.batchTint=-1,this._transformID=-1,this.batchDirty=t.batchDirty,this.batches.length=i,this.vertexData=new Float32Array(t.points);for(let s=0;s<i;s++){const i=t.batches[s],r=i.style.color,n=new Float32Array(this.vertexData.buffer,4*i.attribStart*2,2*i.attribSize),o=new Float32Array(t.uvsFloat32.buffer,4*i.attribStart*2,2*i.attribSize),a={vertexData:n,blendMode:e,indices:new Uint16Array(t.indicesUint16.buffer,2*i.start,i.size),uvs:o,_batchRGB:pp.shared.setValue(r).toRgbArray(),_tintRGB:r,_texture:i.style.texture,alpha:i.style.alpha,worldAlpha:1};this.batches[s]=a}}_renderBatched(t){if(this.batches.length){t.batch.setObjectRenderer(t.plugins[this.pluginName]),this.calculateVertices(),this.calculateTints();for(let e=0,i=this.batches.length;e<i;e++){const i=this.batches[e];i.worldAlpha=this.worldAlpha*i.alpha,t.plugins[this.pluginName].render(i)}}}_renderDirect(t){const e=this._resolveDirectShader(t),i=this._geometry,s=this.worldAlpha,r=e.uniforms,n=i.drawCalls;r.translationMatrix=this.transform.worldTransform,pp.shared.setValue(this._tintColor).premultiply(s).toArray(r.tint),t.shader.bind(e),t.geometry.bind(i,e),t.state.set(this.state);for(let o=0,a=n.length;o<a;o++)this._renderDrawCallDirect(t,i.drawCalls[o])}_renderDrawCallDirect(t,e){const{texArray:i,type:s,size:r,start:n}=e,o=i.count;for(let a=0;a<o;a++)t.texture.bind(i.elements[a],a);t.geometry.draw(s,r,n)}_resolveDirectShader(t){let e=this.shader;const i=this.pluginName;if(!e){if(!Py[i]){const{maxTextures:e}=t.plugins[i],s=new Int32Array(e);for(let t=0;t<e;t++)s[t]=t;const r={tint:new Float32Array([1,1,1,1]),translationMatrix:new Pf,default:rm.from({uSamplers:s},!0)},n=t.plugins[i]._shader.program;Py[i]=new nm(n,r)}e=Py[i]}return e}_calculateBounds(){this.finishPoly();const t=this._geometry;if(!t.graphicsData.length)return;const{minX:e,minY:i,maxX:s,maxY:r}=t.bounds;this._bounds.addFrame(this.transform,e,i,s,r)}containsPoint(e){return this.worldTransform.applyInverse(e,t._TEMP_POINT),this._geometry.containsPoint(t._TEMP_POINT)}calculateTints(){if(this.batchTint!==this.tint){this.batchTint=this._tintColor.toNumber();for(let t=0;t<this.batches.length;t++){const e=this.batches[t];e._tintRGB=pp.shared.setValue(this._tintColor).multiply(e._batchRGB).toLittleEndianNumber()}}}calculateVertices(){const t=this.transform._worldID;if(this._transformID===t)return;this._transformID=t;const e=this.transform.worldTransform,i=e.a,s=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty,l=this._geometry.points,h=this.vertexData;let u=0;for(let c=0;c<l.length;c+=2){const t=l[c],e=l[c+1];h[u++]=i*t+r*e+o,h[u++]=n*e+s*t+a}}closePath(){const t=this.currentPath;return t&&(t.closeStroke=!0,this.finishPoly()),this}setMatrix(t){return this._matrix=t,this}beginHole(){return this.finishPoly(),this._holeMode=!0,this}endHole(){return this.finishPoly(),this._holeMode=!1,this}destroy(t){this._geometry.refCount--,0===this._geometry.refCount&&this._geometry.dispose(),this._matrix=null,this.currentPath=null,this._lineStyle.destroy(),this._lineStyle=null,this._fillStyle.destroy(),this._fillStyle=null,this._geometry=null,this.shader=null,this.vertexData=null,this.batches.length=0,this.batches=null,super.destroy(t)}};Ey.curves=oy,Ey._TEMP_POINT=new gf;let Ty=Ey;var Ay=/* @__PURE__ */(t=>(t[t.LINEAR_VERTICAL=0]="LINEAR_VERTICAL",t[t.LINEAR_HORIZONTAL=1]="LINEAR_HORIZONTAL",t))(Ay||{});const Iy={willReadFrequently:!0},Sy=class t{static get experimentalLetterSpacingSupported(){let e=t._experimentalLetterSpacingSupported;if(void 0!==e){const i=Oh.ADAPTER.getCanvasRenderingContext2D().prototype;e=t._experimentalLetterSpacingSupported="letterSpacing"in i||"textLetterSpacing"in i}return e}constructor(t,e,i,s,r,n,o,a,l){this.text=t,this.style=e,this.width=i,this.height=s,this.lines=r,this.lineWidths=n,this.lineHeight=o,this.maxLineWidth=a,this.fontProperties=l}static measureText(e,i,s,r=t._canvas){s=s??i.wordWrap;const n=i.toFontString(),o=t.measureFont(n);0===o.fontSize&&(o.fontSize=i.fontSize,o.ascent=i.fontSize);const a=r.getContext("2d",Iy);a.font=n;const l=(s?t.wordWrap(e,i,r):e).split(/(?:\r\n|\r|\n)/),h=new Array(l.length);let u=0;for(let f=0;f<l.length;f++){const e=t._measureText(l[f],i.letterSpacing,a);h[f]=e,u=Math.max(u,e)}let c=u+i.strokeThickness;i.dropShadow&&(c+=i.dropShadowDistance);const d=i.lineHeight||o.fontSize+i.strokeThickness;let p=Math.max(d,o.fontSize+2*i.strokeThickness)+i.leading+(l.length-1)*(d+i.leading);return i.dropShadow&&(p+=i.dropShadowDistance),new t(e,i,c,p,l,h,d+i.leading,u,o)}static _measureText(e,i,s){let r=!1;t.experimentalLetterSpacingSupported&&(t.experimentalLetterSpacing?(s.letterSpacing=`${i}px`,s.textLetterSpacing=`${i}px`,r=!0):(s.letterSpacing="0px",s.textLetterSpacing="0px"));let n=s.measureText(e).width;return n>0&&(r?n-=i:n+=(t.graphemeSegmenter(e).length-1)*i),n}static wordWrap(e,i,s=t._canvas){const r=s.getContext("2d",Iy);let n=0,o="",a="";const l=/* @__PURE__ */Object.create(null),{letterSpacing:h,whiteSpace:u}=i,c=t.collapseSpaces(u),d=t.collapseNewlines(u);let p=!c;const f=i.wordWrapWidth+h,m=t.tokenize(e);for(let g=0;g<m.length;g++){let e=m[g];if(t.isNewline(e)){if(!d){a+=t.addLine(o),p=!c,o="",n=0;continue}e=" "}if(c){const i=t.isBreakingSpace(e),s=t.isBreakingSpace(o[o.length-1]);if(i&&s)continue}const s=t.getFromCache(e,h,l,r);if(s>f)if(""!==o&&(a+=t.addLine(o),o="",n=0),t.canBreakWords(e,i.breakWords)){const s=t.wordWrapSplit(e);for(let u=0;u<s.length;u++){let c=s[u],d=c,m=1;for(;s[u+m];){const r=s[u+m];if(t.canBreakChars(d,r,e,u,i.breakWords))break;c+=r,d=r,m++}u+=m-1;const g=t.getFromCache(c,h,l,r);g+n>f&&(a+=t.addLine(o),p=!1,o="",n=0),o+=c,n+=g}}else{o.length>0&&(a+=t.addLine(o),o="",n=0);const i=g===m.length-1;a+=t.addLine(e,!i),p=!1,o="",n=0}else s+n>f&&(p=!1,a+=t.addLine(o),o="",n=0),(o.length>0||!t.isBreakingSpace(e)||p)&&(o+=e,n+=s)}return a+=t.addLine(o,!1),a}static addLine(e,i=!0){return e=t.trimRight(e),e=i?`${e}\n`:e}static getFromCache(e,i,s,r){let n=s[e];return"number"!=typeof n&&(n=t._measureText(e,i,r)+i,s[e]=n),n}static collapseSpaces(t){return"normal"===t||"pre-line"===t}static collapseNewlines(t){return"normal"===t}static trimRight(e){if("string"!=typeof e)return"";for(let i=e.length-1;i>=0;i--){const s=e[i];if(!t.isBreakingSpace(s))break;e=e.slice(0,-1)}return e}static isNewline(e){return"string"==typeof e&&t._newlines.includes(e.charCodeAt(0))}static isBreakingSpace(e,i){return"string"==typeof e&&t._breakingSpaces.includes(e.charCodeAt(0))}static tokenize(e){const i=[];let s="";if("string"!=typeof e)return i;for(let r=0;r<e.length;r++){const n=e[r],o=e[r+1];t.isBreakingSpace(n,o)||t.isNewline(n)?(""!==s&&(i.push(s),s=""),i.push(n)):s+=n}return""!==s&&i.push(s),i}static canBreakWords(t,e){return e}static canBreakChars(t,e,i,s,r){return!0}static wordWrapSplit(e){return t.graphemeSegmenter(e)}static measureFont(e){if(t._fonts[e])return t._fonts[e];const i={ascent:0,descent:0,fontSize:0},s=t._canvas,r=t._context;r.font=e;const n=t.METRICS_STRING+t.BASELINE_SYMBOL,o=Math.ceil(r.measureText(n).width);let a=Math.ceil(r.measureText(t.BASELINE_SYMBOL).width);const l=Math.ceil(t.HEIGHT_MULTIPLIER*a);if(a=a*t.BASELINE_MULTIPLIER|0,0===o||0===l)return t._fonts[e]=i,i;s.width=o,s.height=l,r.fillStyle="#f00",r.fillRect(0,0,o,l),r.font=e,r.textBaseline="alphabetic",r.fillStyle="#000",r.fillText(n,0,a);const h=r.getImageData(0,0,o,l).data,u=h.length,c=4*o;let d=0,p=0,f=!1;for(d=0;d<a;++d){for(let t=0;t<c;t+=4)if(255!==h[p+t]){f=!0;break}if(f)break;p+=c}for(i.ascent=a-d,p=u-c,f=!1,d=l;d>a;--d){for(let t=0;t<c;t+=4)if(255!==h[p+t]){f=!0;break}if(f)break;p-=c}return i.descent=d-a,i.fontSize=i.ascent+i.descent,t._fonts[e]=i,i}static clearMetrics(e=""){e?delete t._fonts[e]:t._fonts={}}static get _canvas(){if(!t.__canvas){let e;try{const i=new OffscreenCanvas(0,0);if(i.getContext("2d",Iy)?.measureText)return t.__canvas=i,i;e=Oh.ADAPTER.createCanvas()}catch{e=Oh.ADAPTER.createCanvas()}e.width=e.height=10,t.__canvas=e}return t.__canvas}static get _context(){return t.__context||(t.__context=t._canvas.getContext("2d",Iy)),t.__context}};Sy.METRICS_STRING="|ÉqÅ",Sy.BASELINE_SYMBOL="M",Sy.BASELINE_MULTIPLIER=1.4,Sy.HEIGHT_MULTIPLIER=2,Sy.graphemeSegmenter=(()=>{if("function"==typeof Intl?.Segmenter){const t=new Intl.Segmenter;return e=>[...t.segment(e)].map(t=>t.segment)}return t=>[...t]})(),Sy.experimentalLetterSpacing=!1,Sy._fonts={},Sy._newlines=[10,13],Sy._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288];let Cy=Sy;const My=["serif","sans-serif","monospace","cursive","fantasy","system-ui"],Oy=class t{constructor(t){this.styleID=0,this.reset(),Ry(this,t,t)}clone(){const e={};return Ry(e,this,t.defaultStyle),new t(e)}reset(){Ry(this,t.defaultStyle,t.defaultStyle)}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this.styleID++)}get breakWords(){return this._breakWords}set breakWords(t){this._breakWords!==t&&(this._breakWords=t,this.styleID++)}get dropShadow(){return this._dropShadow}set dropShadow(t){this._dropShadow!==t&&(this._dropShadow=t,this.styleID++)}get dropShadowAlpha(){return this._dropShadowAlpha}set dropShadowAlpha(t){this._dropShadowAlpha!==t&&(this._dropShadowAlpha=t,this.styleID++)}get dropShadowAngle(){return this._dropShadowAngle}set dropShadowAngle(t){this._dropShadowAngle!==t&&(this._dropShadowAngle=t,this.styleID++)}get dropShadowBlur(){return this._dropShadowBlur}set dropShadowBlur(t){this._dropShadowBlur!==t&&(this._dropShadowBlur=t,this.styleID++)}get dropShadowColor(){return this._dropShadowColor}set dropShadowColor(t){const e=Ly(t);this._dropShadowColor!==e&&(this._dropShadowColor=e,this.styleID++)}get dropShadowDistance(){return this._dropShadowDistance}set dropShadowDistance(t){this._dropShadowDistance!==t&&(this._dropShadowDistance=t,this.styleID++)}get fill(){return this._fill}set fill(t){const e=Ly(t);this._fill!==e&&(this._fill=e,this.styleID++)}get fillGradientType(){return this._fillGradientType}set fillGradientType(t){this._fillGradientType!==t&&(this._fillGradientType=t,this.styleID++)}get fillGradientStops(){return this._fillGradientStops}set fillGradientStops(t){(function(t,e){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;++i)if(t[i]!==e[i])return!1;return!0})(this._fillGradientStops,t)||(this._fillGradientStops=t,this.styleID++)}get fontFamily(){return this._fontFamily}set fontFamily(t){this.fontFamily!==t&&(this._fontFamily=t,this.styleID++)}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(this._fontSize=t,this.styleID++)}get fontStyle(){return this._fontStyle}set fontStyle(t){this._fontStyle!==t&&(this._fontStyle=t,this.styleID++)}get fontVariant(){return this._fontVariant}set fontVariant(t){this._fontVariant!==t&&(this._fontVariant=t,this.styleID++)}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.styleID++)}get letterSpacing(){return this._letterSpacing}set letterSpacing(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.styleID++)}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this.styleID++)}get leading(){return this._leading}set leading(t){this._leading!==t&&(this._leading=t,this.styleID++)}get lineJoin(){return this._lineJoin}set lineJoin(t){this._lineJoin!==t&&(this._lineJoin=t,this.styleID++)}get miterLimit(){return this._miterLimit}set miterLimit(t){this._miterLimit!==t&&(this._miterLimit=t,this.styleID++)}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this.styleID++)}get stroke(){return this._stroke}set stroke(t){const e=Ly(t);this._stroke!==e&&(this._stroke=e,this.styleID++)}get strokeThickness(){return this._strokeThickness}set strokeThickness(t){this._strokeThickness!==t&&(this._strokeThickness=t,this.styleID++)}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline!==t&&(this._textBaseline=t,this.styleID++)}get trim(){return this._trim}set trim(t){this._trim!==t&&(this._trim=t,this.styleID++)}get whiteSpace(){return this._whiteSpace}set whiteSpace(t){this._whiteSpace!==t&&(this._whiteSpace=t,this.styleID++)}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this.styleID++)}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.styleID++)}toFontString(){const t="number"==typeof this.fontSize?`${this.fontSize}px`:this.fontSize;let e=this.fontFamily;Array.isArray(this.fontFamily)||(e=this.fontFamily.split(","));for(let i=e.length-1;i>=0;i--){let t=e[i].trim();!/([\"\'])[^\'\"]+\1/.test(t)&&!My.includes(t)&&(t=`"${t}"`),e[i]=t}return`${this.fontStyle} ${this.fontVariant} ${this.fontWeight} ${t} ${e.join(",")}`}};Oy.defaultStyle={align:"left",breakWords:!1,dropShadow:!1,dropShadowAlpha:1,dropShadowAngle:Math.PI/6,dropShadowBlur:0,dropShadowColor:"black",dropShadowDistance:5,fill:"black",fillGradientType:Ay.LINEAR_VERTICAL,fillGradientStops:[],fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,lineJoin:"miter",miterLimit:10,padding:0,stroke:"black",strokeThickness:0,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let Ny=Oy;function Ly(t){const e=pp.shared,i=t=>{const i=e.setValue(t);return 1===i.alpha?i.toHex():i.toRgbaString()};return Array.isArray(t)?t.map(i):i(t)}function Ry(t,e,i){for(const s in i)Array.isArray(e[s])?t[s]=e[s].slice():t[s]=e[s]}const By={texture:!0,children:!1,baseTexture:!0},ky=class t extends Zg{constructor(e,i,s){let r=!1;s||(s=Oh.ADAPTER.createCanvas(),r=!0),s.width=3,s.height=3;const n=Em.from(s);n.orig=new vf,n.trim=new vf,super(n),this._ownCanvas=r,this.canvas=s,this.context=s.getContext("2d",{willReadFrequently:!0}),this._resolution=t.defaultResolution??Oh.RESOLUTION,this._autoResolution=t.defaultAutoResolution,this._text=null,this._style=null,this._styleListener=null,this._font="",this.text=e,this.style=i,this.localStyleID=-1}static get experimentalLetterSpacing(){return Cy.experimentalLetterSpacing}static set experimentalLetterSpacing(t){Md("7.1.0","Text.experimentalLetterSpacing is deprecated, use TextMetrics.experimentalLetterSpacing"),Cy.experimentalLetterSpacing=t}updateText(t){const e=this._style;if(this.localStyleID!==e.styleID&&(this.dirty=!0,this.localStyleID=e.styleID),!this.dirty&&t)return;this._font=this._style.toFontString();const i=this.context,s=Cy.measureText(this._text||" ",this._style,this._style.wordWrap,this.canvas),r=s.width,n=s.height,o=s.lines,a=s.lineHeight,l=s.lineWidths,h=s.maxLineWidth,u=s.fontProperties;let c,d;this.canvas.width=Math.ceil(Math.ceil(Math.max(1,r)+2*e.padding)*this._resolution),this.canvas.height=Math.ceil(Math.ceil(Math.max(1,n)+2*e.padding)*this._resolution),i.scale(this._resolution,this._resolution),i.clearRect(0,0,this.canvas.width,this.canvas.height),i.font=this._font,i.lineWidth=e.strokeThickness,i.textBaseline=e.textBaseline,i.lineJoin=e.lineJoin,i.miterLimit=e.miterLimit;const p=e.dropShadow?2:1;for(let f=0;f<p;++f){const t=e.dropShadow&&0===f,r=t?Math.ceil(Math.max(1,n)+2*e.padding):0,p=r*this._resolution;if(t){i.fillStyle="black",i.strokeStyle="black";const t=e.dropShadowColor,s=e.dropShadowBlur*this._resolution,r=e.dropShadowDistance*this._resolution;i.shadowColor=pp.shared.setValue(t).setAlpha(e.dropShadowAlpha).toRgbaString(),i.shadowBlur=s,i.shadowOffsetX=Math.cos(e.dropShadowAngle)*r,i.shadowOffsetY=Math.sin(e.dropShadowAngle)*r+p}else i.fillStyle=this._generateFillStyle(e,o,s),i.strokeStyle=e.stroke,i.shadowColor="black",i.shadowBlur=0,i.shadowOffsetX=0,i.shadowOffsetY=0;let m=(a-u.fontSize)/2;a-u.fontSize<0&&(m=0);for(let i=0;i<o.length;i++)c=e.strokeThickness/2,d=e.strokeThickness/2+i*a+u.ascent+m,"right"===e.align?c+=h-l[i]:"center"===e.align&&(c+=(h-l[i])/2),e.stroke&&e.strokeThickness&&this.drawLetterSpacing(o[i],c+e.padding,d+e.padding-r,!0),e.fill&&this.drawLetterSpacing(o[i],c+e.padding,d+e.padding-r)}this.updateTexture()}drawLetterSpacing(t,e,i,s=!1){const r=this._style.letterSpacing;let n=!1;if(Cy.experimentalLetterSpacingSupported&&(Cy.experimentalLetterSpacing?(this.context.letterSpacing=`${r}px`,this.context.textLetterSpacing=`${r}px`,n=!0):(this.context.letterSpacing="0px",this.context.textLetterSpacing="0px")),0===r||n)return void(s?this.context.strokeText(t,e,i):this.context.fillText(t,e,i));let o=e;const a=Cy.graphemeSegmenter(t);let l=this.context.measureText(t).width,h=0;for(let u=0;u<a.length;++u){const t=a[u];s?this.context.strokeText(t,o,i):this.context.fillText(t,o,i);let e="";for(let i=u+1;i<a.length;++i)e+=a[i];h=this.context.measureText(e).width,o+=l-h+r,l=h}}updateTexture(){const t=this.canvas;if(this._style.trim){const e=Bp(t);e.data&&(t.width=e.width,t.height=e.height,this.context.putImageData(e.data,0,0))}const e=this._texture,i=this._style,s=i.trim?0:i.padding,r=e.baseTexture;e.trim.width=e._frame.width=t.width/this._resolution,e.trim.height=e._frame.height=t.height/this._resolution,e.trim.x=-s,e.trim.y=-s,e.orig.width=e._frame.width-2*s,e.orig.height=e._frame.height-2*s,this._onTextureUpdate(),r.setRealSize(t.width,t.height,this._resolution),e.updateUvs(),this.dirty=!1}_render(t){this._autoResolution&&this._resolution!==t.resolution&&(this._resolution=t.resolution,this.dirty=!0),this.updateText(!0),super._render(t)}updateTransform(){this.updateText(!0),super.updateTransform()}getBounds(t,e){return this.updateText(!0),-1===this._textureID&&(t=!1),super.getBounds(t,e)}getLocalBounds(t){return this.updateText(!0),super.getLocalBounds.call(this,t)}_calculateBounds(){this.calculateVertices(),this._bounds.addQuad(this.vertexData)}_generateFillStyle(t,e,i){const s=t.fill;if(!Array.isArray(s))return s;if(1===s.length)return s[0];let r;const n=t.dropShadow?t.dropShadowDistance:0,o=t.padding||0,a=this.canvas.width/this._resolution-n-2*o,l=this.canvas.height/this._resolution-n-2*o,h=s.slice(),u=t.fillGradientStops.slice();if(!u.length){const t=h.length+1;for(let e=1;e<t;++e)u.push(e/t)}if(h.unshift(s[0]),u.unshift(0),h.push(s[s.length-1]),u.push(1),t.fillGradientType===Ay.LINEAR_VERTICAL){r=this.context.createLinearGradient(a/2,o,a/2,l+o);const s=i.fontProperties.fontSize+t.strokeThickness;for(let t=0;t<e.length;t++){const n=i.lineHeight*(t-1)+s,o=i.lineHeight*t;let a=o;t>0&&n>o&&(a=(o+n)/2);const c=o+s,d=i.lineHeight*(t+1);let p=c;t+1<e.length&&d<c&&(p=(c+d)/2);const f=(p-a)/l;for(let t=0;t<h.length;t++){let e=0;e="number"==typeof u[t]?u[t]:t/h.length;let i=Math.min(1,Math.max(0,a/l+e*f));i=Number(i.toFixed(5)),r.addColorStop(i,h[t])}}}else{r=this.context.createLinearGradient(o,l/2,a+o,l/2);const t=h.length+1;let e=1;for(let i=0;i<h.length;i++){let s;s="number"==typeof u[i]?u[i]:e/t,r.addColorStop(s,h[i]),e++}}return r}destroy(t){"boolean"==typeof t&&(t={children:t}),t=Object.assign({},By,t),super.destroy(t),this._ownCanvas&&(this.canvas.height=this.canvas.width=0),this.context=null,this.canvas=null,this._style=null}get width(){return this.updateText(!0),Math.abs(this.scale.x)*this._texture.orig.width}set width(t){this.updateText(!0);const e=_p(this.scale.x)||1;this.scale.x=e*t/this._texture.orig.width,this._width=t}get height(){return this.updateText(!0),Math.abs(this.scale.y)*this._texture.orig.height}set height(t){this.updateText(!0);const e=_p(this.scale.y)||1;this.scale.y=e*t/this._texture.orig.height,this._height=t}get style(){return this._style}set style(t){t=t||{},this._style=t instanceof Ny?t:new Ny(t),this.localStyleID=-1,this.dirty=!0}get text(){return this._text}set text(t){t=String(t??""),this._text!==t&&(this._text=t,this.dirty=!0)}get resolution(){return this._resolution}set resolution(t){this._autoResolution=!1,this._resolution!==t&&(this._resolution=t,this.dirty=!0)}};ky.defaultAutoResolution=!0;let Fy=ky;class Dy extends dm{constructor(){super("attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n",{m:new Float32Array([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]),uAlpha:1}),this.alpha=1}_loadMatrix(t,e=!1){let i=t;e&&(this._multiply(i,this.uniforms.m,t),i=this._colorMatrix(i)),this.uniforms.m=i}_multiply(t,e,i){return t[0]=e[0]*i[0]+e[1]*i[5]+e[2]*i[10]+e[3]*i[15],t[1]=e[0]*i[1]+e[1]*i[6]+e[2]*i[11]+e[3]*i[16],t[2]=e[0]*i[2]+e[1]*i[7]+e[2]*i[12]+e[3]*i[17],t[3]=e[0]*i[3]+e[1]*i[8]+e[2]*i[13]+e[3]*i[18],t[4]=e[0]*i[4]+e[1]*i[9]+e[2]*i[14]+e[3]*i[19]+e[4],t[5]=e[5]*i[0]+e[6]*i[5]+e[7]*i[10]+e[8]*i[15],t[6]=e[5]*i[1]+e[6]*i[6]+e[7]*i[11]+e[8]*i[16],t[7]=e[5]*i[2]+e[6]*i[7]+e[7]*i[12]+e[8]*i[17],t[8]=e[5]*i[3]+e[6]*i[8]+e[7]*i[13]+e[8]*i[18],t[9]=e[5]*i[4]+e[6]*i[9]+e[7]*i[14]+e[8]*i[19]+e[9],t[10]=e[10]*i[0]+e[11]*i[5]+e[12]*i[10]+e[13]*i[15],t[11]=e[10]*i[1]+e[11]*i[6]+e[12]*i[11]+e[13]*i[16],t[12]=e[10]*i[2]+e[11]*i[7]+e[12]*i[12]+e[13]*i[17],t[13]=e[10]*i[3]+e[11]*i[8]+e[12]*i[13]+e[13]*i[18],t[14]=e[10]*i[4]+e[11]*i[9]+e[12]*i[14]+e[13]*i[19]+e[14],t[15]=e[15]*i[0]+e[16]*i[5]+e[17]*i[10]+e[18]*i[15],t[16]=e[15]*i[1]+e[16]*i[6]+e[17]*i[11]+e[18]*i[16],t[17]=e[15]*i[2]+e[16]*i[7]+e[17]*i[12]+e[18]*i[17],t[18]=e[15]*i[3]+e[16]*i[8]+e[17]*i[13]+e[18]*i[18],t[19]=e[15]*i[4]+e[16]*i[9]+e[17]*i[14]+e[18]*i[19]+e[19],t}_colorMatrix(t){const e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e}brightness(t,e){const i=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}tint(t,e){const[i,s,r]=pp.shared.setValue(t).toArray(),n=[i,0,0,0,0,0,s,0,0,0,0,0,r,0,0,0,0,0,1,0];this._loadMatrix(n,e)}greyscale(t,e){const i=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}blackAndWhite(t){this._loadMatrix([.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0],t)}hue(t,e){t=(t||0)/180*Math.PI;const i=Math.cos(t),s=Math.sin(t),r=1/3,n=(0,Math.sqrt)(r),o=[i+(1-i)*r,r*(1-i)-n*s,r*(1-i)+n*s,0,0,r*(1-i)+n*s,i+r*(1-i),r*(1-i)-n*s,0,0,r*(1-i)-n*s,r*(1-i)+n*s,i+r*(1-i),0,0,0,0,0,1,0];this._loadMatrix(o,e)}contrast(t,e){const i=(t||0)+1,s=-.5*(i-1),r=[i,0,0,0,s,0,i,0,0,s,0,0,i,0,s,0,0,0,1,0];this._loadMatrix(r,e)}saturate(t=0,e){const i=2*t/3+1,s=-.5*(i-1),r=[i,s,s,0,0,s,i,s,0,0,s,s,i,0,0,0,0,0,1,0];this._loadMatrix(r,e)}desaturate(){this.saturate(-1)}negative(t){this._loadMatrix([-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0],t)}sepia(t){this._loadMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0],t)}technicolor(t){this._loadMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0],t)}polaroid(t){this._loadMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],t)}toBGR(t){this._loadMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0],t)}kodachrome(t){this._loadMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0],t)}browni(t){this._loadMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0],t)}vintage(t){this._loadMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0],t)}colorTone(t,e,i,s,r){t=t||.2,e=e||.15,i=i||16770432,s=s||3375104;const n=pp.shared,[o,a,l]=n.setValue(i).toArray(),[h,u,c]=n.setValue(s).toArray(),d=[.3,.59,.11,0,0,o,a,l,t,0,h,u,c,e,0,o-h,a-u,l-c,0,0];this._loadMatrix(d,r)}night(t,e){const i=[-2*(t=t||.1),-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}predator(t,e){const i=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(i,e)}lsd(t){this._loadMatrix([2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0],t)}reset(){this._loadMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],!1)}get matrix(){return this.uniforms.m}set matrix(t){this.uniforms.m=t}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}}Dy.prototype.grayscale=Dy.prototype.greyscale;var Uy,Gy={exports:{}},Xy=Gy.exports;var Wy=(Uy||(Uy=1,function(t){(function(){var e,i;i=e={linear:function(t,e,i,s){return i*t/s+e},easeInQuad:function(t,e,i,s){return i*(t/=s)*t+e},easeOutQuad:function(t,e,i,s){return-i*(t/=s)*(t-2)+e},easeInOutQuad:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,s){return i*(t/=s)*t*t+e},easeOutCubic:function(t,e,i,s){return i*((t=t/s-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,s){return i*(t/=s)*t*t*t+e},easeOutQuart:function(t,e,i,s){return-i*((t=t/s-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,s){return i*(t/=s)*t*t*t*t+e},easeOutQuint:function(t,e,i,s){return i*((t=t/s-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,s){return-i*Math.cos(t/s*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,s){return i*Math.sin(t/s*(Math.PI/2))+e},easeInOutSine:function(t,e,i,s){return-i/2*(Math.cos(Math.PI*t/s)-1)+e},easeInExpo:function(t,e,i,s){return 0===t?e:i*Math.pow(2,10*(t/s-1))+e},easeOutExpo:function(t,e,i,s){return t===s?e+i:i*(1-Math.pow(2,-10*t/s))+e},easeInOutExpo:function(t,e,i,s){return(t/=s/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,s){return-i*(Math.sqrt(1-(t/=s)*t)-1)+e},easeOutCirc:function(t,e,i,s){return i*Math.sqrt(1-(t=t/s-1)*t)+e},easeInOutCirc:function(t,e,i,s){return(t/=s/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),-r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)+e},easeOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),r*Math.pow(2,-10*t)*Math.sin((t*s-o)*(2*Math.PI)/n)+i+e},easeInOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s/2),(n=0)||(n=s*(.3*1.5)),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),t<1?r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*-.5+e:r*Math.pow(2,-10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*.5+i+e},easeInBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*(t/=s)*t*((r+1)*t-r)+e},easeOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*((t=t/s-1)*t*((r+1)*t+r)+1)+e},easeInOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),(t/=s/2)<1?i/2*(t*t*((1+(r*=1.525))*t-r))+e:i/2*((t-=2)*t*((1+(r*=1.525))*t+r)+2)+e},easeInBounce:function(t,i,s,r){return s-e.easeOutBounce(r-t,0,s,r)+i},easeOutBounce:function(t,e,i,s){return(t/=s)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e},easeInOutBounce:function(t,i,s,r){return t<r/2?.5*e.easeInBounce(2*t,0,s,r)+i:.5*e.easeOutBounce(2*t-r,0,s,r)+.5*s+i}},t.exports=i}).call(Xy)}(Gy)),Gy.exports);const Yy=/* @__PURE__ */It(Wy);qg.prototype._renderCanvas=function(t){},qg.prototype.renderCanvas=function(t){if(this.visible&&!(this.worldAlpha<=0)&&this.renderable){this._mask&&t.mask.pushMask(this._mask),this._renderCanvas(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].renderCanvas(t);this._mask&&t.mask.popMask(t)}},Hg.prototype.renderCanvas=function(t){},Fy.prototype._renderCanvas=function(t){this._autoResolution&&this._resolution!==t.resolution&&(this._resolution=t.resolution,this.dirty=!0),this.updateText(!0),Zg.prototype._renderCanvas.call(this,t)},Hg.prototype.name=null,qg.prototype.getChildByName=function(t,e){for(let i=0,s=this.children.length;i<s;i++)if(this.children[i].name===t)return this.children[i];if(e)for(let i=0,s=this.children.length;i<s;i++){const e=this.children[i];if(!e.getChildByName)continue;const s=e.getChildByName(t,!0);if(s)return s}return null};const Hy={vec3(t,e,i,s){(i[0]!==s[0]||i[1]!==s[1]||i[2]!==s[2])&&(i[0]=s[0],i[1]=s[1],i[2]=s[2],t.uniform3f(e,s[0],s[1],s[2]))},int(t,e,i,s){t.uniform1i(e,s)},ivec2(t,e,i,s){t.uniform2i(e,s[0],s[1])},ivec3(t,e,i,s){t.uniform3i(e,s[0],s[1],s[2])},ivec4(t,e,i,s){t.uniform4i(e,s[0],s[1],s[2],s[3])},uint(t,e,i,s){t.uniform1ui(e,s)},uvec2(t,e,i,s){t.uniform2ui(e,s[0],s[1])},uvec3(t,e,i,s){t.uniform3ui(e,s[0],s[1],s[2])},uvec4(t,e,i,s){t.uniform4ui(e,s[0],s[1],s[2],s[3])},bvec2(t,e,i,s){t.uniform2i(e,s[0],s[1])},bvec3(t,e,i,s){t.uniform3i(e,s[0],s[1],s[2])},bvec4(t,e,i,s){t.uniform4i(e,s[0],s[1],s[2],s[3])},mat2(t,e,i,s){t.uniformMatrix2fv(e,!1,s)},mat4(t,e,i,s){t.uniformMatrix4fv(e,!1,s)}},$y={float(t,e,i,s){t.uniform1fv(e,s)},vec2(t,e,i,s){t.uniform2fv(e,s)},vec3(t,e,i,s){t.uniform3fv(e,s)},vec4(t,e,i,s){t.uniform4fv(e,s)},int(t,e,i,s){t.uniform1iv(e,s)},ivec2(t,e,i,s){t.uniform2iv(e,s)},ivec3(t,e,i,s){t.uniform3iv(e,s)},ivec4(t,e,i,s){t.uniform4iv(e,s)},uint(t,e,i,s){t.uniform1uiv(e,s)},uvec2(t,e,i,s){t.uniform2uiv(e,s)},uvec3(t,e,i,s){t.uniform3uiv(e,s)},uvec4(t,e,i,s){t.uniform4uiv(e,s)},bool(t,e,i,s){t.uniform1iv(e,s)},bvec2(t,e,i,s){t.uniform2iv(e,s)},bvec3(t,e,i,s){t.uniform3iv(e,s)},bvec4(t,e,i,s){t.uniform4iv(e,s)},sampler2D(t,e,i,s){t.uniform1iv(e,s)},samplerCube(t,e,i,s){t.uniform1iv(e,s)},sampler2DArray(t,e,i,s){t.uniform1iv(e,s)}};Object.assign(cg.prototype,{systemCheck(){},syncUniforms(t,e){const{shader:i,renderer:s}=this;!function(t,e,i,s,r){let n=0,o=null,a=null;const l=r.gl;for(const h in t.uniforms){const u=e[h],c=s[h],d=i[h],p=t.uniforms[h];u?"float"!==u.type||1!==u.size||u.isArray?"bool"!==u.type||1!==u.size||u.isArray?"sampler2D"!==u.type&&"samplerCube"!==u.type&&"sampler2DArray"!==u.type||1!==u.size||u.isArray?"mat3"!==u.type||1!==u.size||u.isArray?"vec2"!==u.type||1!==u.size||u.isArray?"vec4"!==u.type||1!==u.size||u.isArray?(1!==u.size||u.isArray?$y:Hy)[u.type].call(null,l,d.location,d.value,c):void 0!==p.width?(a=d.value,o=c,(a[0]!==o.x||a[1]!==o.y||a[2]!==o.width||a[3]!==o.height)&&(a[0]=o.x,a[1]=o.y,a[2]=o.width,a[3]=o.height,l.uniform4f(d.location,o.x,o.y,o.width,o.height))):(a=d.value,o=c,(a[0]!==o[0]||a[1]!==o[1]||a[2]!==o[2]||a[3]!==o[3])&&(a[0]=o[0],a[1]=o[1],a[2]=o[2],a[3]=o[3],l.uniform4f(d.location,o[0],o[1],o[2],o[3]))):void 0!==p.x?(a=d.value,o=c,(a[0]!==o.x||a[1]!==o.y)&&(a[0]=o.x,a[1]=o.y,l.uniform2f(d.location,o.x,o.y))):(a=d.value,o=c,(a[0]!==o[0]||a[1]!==o[1])&&(a[0]=o[0],a[1]=o[1],l.uniform2f(d.location,o[0],o[1]))):void 0!==p.a?l.uniformMatrix3fv(d.location,!1,c.toArray(!0)):l.uniformMatrix3fv(d.location,!1,c):(r.texture.bind(c,n),d.value!==n&&(d.value=n,l.uniform1i(d.location,n)),n++):c!==d.value&&(d.value=c,l.uniform1i(d.location,Number(c))):c!==d.value&&(d.value=c,l.uniform1f(d.location,c)):!0===p.group&&r.shader.syncUniformGroup(c)}}(t,i.program.uniformData,e.uniformData,t.uniforms,s)}});const jy=new class{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this.tickerAdded=!1,this._pauseUpdate=!0}init(t){this.removeTickerListener(),this.events=t,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this.tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(t){this._pauseUpdate=t}addTickerListener(){this.tickerAdded||!this.domElement||(Tg.system.add(this.tickerUpdate,this,_g.INTERACTION),this.tickerAdded=!0)}removeTickerListener(){this.tickerAdded&&(Tg.system.remove(this.tickerUpdate,this),this.tickerAdded=!1)}pointerMoved(){this._didMove=!0}update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove)return void(this._didMove=!1);const t=this.events.rootPointerEvent;this.events.supportsTouchEvents&&"touch"===t.pointerType||globalThis.document.dispatchEvent(new PointerEvent("pointermove",{clientX:t.clientX,clientY:t.clientY}))}tickerUpdate(t){this._deltaTime+=t,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this.update())}};class zy{constructor(t){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=zy.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new gf,this.page=new gf,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=t}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(t,e,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(t,e,i,s,r){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}class Vy extends zy{constructor(){super(...arguments),this.client=new gf,this.movement=new gf,this.offset=new gf,this.global=new gf,this.screen=new gf}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(t,e,i){return t.worldTransform.applyInverse(i||this.global,e)}getModifierState(t){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(t)}initMouseEvent(t,e,i,s,r,n,o,a,l,h,u,c,d,p,f){throw new Error("Method not implemented.")}}class qy extends Vy{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return"pointermove"===this.type||"mousemove"===this.type||"touchmove"===this.type?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Jy extends Vy{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Jy.DOM_DELTA_PIXEL=0,Jy.DOM_DELTA_LINE=1,Jy.DOM_DELTA_PAGE=2;const Ky=new gf,Zy=new gf;class Qy{constructor(t){this.dispatch=new Qh,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=/* @__PURE__ */new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=t,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(t,e){this.mappingTable[t]||(this.mappingTable[t]=[]),this.mappingTable[t].push({fn:e,priority:0}),this.mappingTable[t].sort((t,e)=>t.priority-e.priority)}dispatchEvent(t,e){t.propagationStopped=!1,t.propagationImmediatelyStopped=!1,this.propagate(t,e),this.dispatch.emit(e||t.type,t)}mapEvent(t){if(!this.rootTarget)return;const e=this.mappingTable[t.type];if(e)for(let i=0,s=e.length;i<s;i++)e[i].fn(t);else console.warn(`[EventBoundary]: Event mapping not defined for ${t.type}`)}hitTest(t,e){jy.pauseUpdate=!0;const i=this[this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive"](this.rootTarget,this.rootTarget.eventMode,Ky.set(t,e),this.hitTestFn,this.hitPruneFn);return i&&i[0]}propagate(t,e){if(!t.target)return;const i=t.composedPath();t.eventPhase=t.CAPTURING_PHASE;for(let s=0,r=i.length-1;s<r;s++)if(t.currentTarget=i[s],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return;if(t.eventPhase=t.AT_TARGET,t.currentTarget=t.target,this.notifyTarget(t,e),!t.propagationStopped&&!t.propagationImmediatelyStopped){t.eventPhase=t.BUBBLING_PHASE;for(let s=i.length-2;s>=0;s--)if(t.currentTarget=i[s],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return}}all(t,e,i=this._allInteractiveElements){if(0===i.length)return;t.eventPhase=t.BUBBLING_PHASE;const s=Array.isArray(e)?e:[e];for(let r=i.length-1;r>=0;r--)s.forEach(e=>{t.currentTarget=i[r],this.notifyTarget(t,e)})}propagationPath(t){const e=[t];for(let i=0;i<2048&&t!==this.rootTarget;i++){if(!t.parent)throw new Error("Cannot find propagation path to disconnected target");e.push(t.parent),t=t.parent}return e.reverse(),e}hitTestMoveRecursive(t,e,i,s,r,n=!1){let o=!1;if(this._interactivePrune(t))return null;if(("dynamic"===t.eventMode||"dynamic"===e)&&(jy.pauseUpdate=!1),t.interactiveChildren&&t.children){const a=t.children;for(let l=a.length-1;l>=0;l--){const h=a[l],u=this.hitTestMoveRecursive(h,this._isInteractive(e)?e:h.eventMode,i,s,r,n||r(t,i));if(u){if(u.length>0&&!u[u.length-1].parent)continue;const e=t.isInteractive();(u.length>0||e)&&(e&&this._allInteractiveElements.push(t),u.push(t)),0===this._hitElements.length&&(this._hitElements=u),o=!0}}}const a=this._isInteractive(e),l=t.isInteractive();return a&&l&&this._allInteractiveElements.push(t),n||this._hitElements.length>0?null:o?this._hitElements:a&&!r(t,i)&&s(t,i)?l?[t]:[]:null}hitTestRecursive(t,e,i,s,r){if(this._interactivePrune(t)||r(t,i))return null;if(("dynamic"===t.eventMode||"dynamic"===e)&&(jy.pauseUpdate=!1),t.interactiveChildren&&t.children){const n=t.children;for(let o=n.length-1;o>=0;o--){const a=n[o],l=this.hitTestRecursive(a,this._isInteractive(e)?e:a.eventMode,i,s,r);if(l){if(l.length>0&&!l[l.length-1].parent)continue;const e=t.isInteractive();return(l.length>0||e)&&l.push(t),l}}}const n=this._isInteractive(e),o=t.isInteractive();return n&&s(t,i)?o?[t]:[]:null}_isInteractive(t){return"static"===t||"dynamic"===t}_interactivePrune(t){return!(t&&!t.isMask&&t.visible&&t.renderable&&"none"!==t.eventMode&&("passive"!==t.eventMode||t.interactiveChildren)&&!t.isMask)}hitPruneFn(t,e){if(t.hitArea&&(t.worldTransform.applyInverse(e,Zy),!t.hitArea.contains(Zy.x,Zy.y)))return!0;if(t._mask){const i=t._mask.isMaskData?t._mask.maskObject:t._mask;if(i&&!i.containsPoint?.(e))return!0}return!1}hitTestFn(t,e){return"passive"!==t.eventMode&&(!!t.hitArea||!!t.containsPoint&&t.containsPoint(e))}notifyTarget(t,e){const i=`on${e=e??t.type}`;t.currentTarget[i]?.(t);const s=t.eventPhase===t.CAPTURING_PHASE||t.eventPhase===t.AT_TARGET?`${e}capture`:e;this.notifyListeners(t,s),t.eventPhase===t.AT_TARGET&&this.notifyListeners(t,e)}mapPointerDown(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.createPointerEvent(t);if(this.dispatchEvent(e,"pointerdown"),"touch"===e.pointerType)this.dispatchEvent(e,"touchstart");else if("mouse"===e.pointerType||"pen"===e.pointerType){const t=2===e.button;this.dispatchEvent(e,t?"rightdown":"mousedown")}this.trackingData(t.pointerId).pressTargetsByButton[t.button]=e.composedPath(),this.freeEvent(e)}mapPointerMove(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const e=this.createPointerEvent(t);this._isPointerMoveEvent=!1;const i="mouse"===e.pointerType||"pen"===e.pointerType,s=this.trackingData(t.pointerId),r=this.findMountedTarget(s.overTargets);if(s.overTargets?.length>0&&r!==e.target){const s="mousemove"===t.type?"mouseout":"pointerout",n=this.createPointerEvent(t,s,r);if(this.dispatchEvent(n,"pointerout"),i&&this.dispatchEvent(n,"mouseout"),!e.composedPath().includes(r)){const s=this.createPointerEvent(t,"pointerleave",r);for(s.eventPhase=s.AT_TARGET;s.target&&!e.composedPath().includes(s.target);)s.currentTarget=s.target,this.notifyTarget(s),i&&this.notifyTarget(s,"mouseleave"),s.target=s.target.parent;this.freeEvent(s)}this.freeEvent(n)}if(r!==e.target){const s="mousemove"===t.type?"mouseover":"pointerover",n=this.clonePointerEvent(e,s);this.dispatchEvent(n,"pointerover"),i&&this.dispatchEvent(n,"mouseover");let o=r?.parent;for(;o&&o!==this.rootTarget.parent&&o!==e.target;)o=o.parent;if(!o||o===this.rootTarget.parent){const t=this.clonePointerEvent(e,"pointerenter");for(t.eventPhase=t.AT_TARGET;t.target&&t.target!==r&&t.target!==this.rootTarget.parent;)t.currentTarget=t.target,this.notifyTarget(t),i&&this.notifyTarget(t,"mouseenter"),t.target=t.target.parent;this.freeEvent(t)}this.freeEvent(n)}const n=[],o=this.enableGlobalMoveEvents??!0;this.moveOnAll?n.push("pointermove"):this.dispatchEvent(e,"pointermove"),o&&n.push("globalpointermove"),"touch"===e.pointerType&&(this.moveOnAll?n.splice(1,0,"touchmove"):this.dispatchEvent(e,"touchmove"),o&&n.push("globaltouchmove")),i&&(this.moveOnAll?n.splice(1,0,"mousemove"):this.dispatchEvent(e,"mousemove"),o&&n.push("globalmousemove"),this.cursor=e.target?.cursor),n.length>0&&this.all(e,n),this._allInteractiveElements.length=0,this._hitElements.length=0,s.overTargets=e.composedPath(),this.freeEvent(e)}mapPointerOver(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId),i=this.createPointerEvent(t),s="mouse"===i.pointerType||"pen"===i.pointerType;this.dispatchEvent(i,"pointerover"),s&&this.dispatchEvent(i,"mouseover"),"mouse"===i.pointerType&&(this.cursor=i.target?.cursor);const r=this.clonePointerEvent(i,"pointerenter");for(r.eventPhase=r.AT_TARGET;r.target&&r.target!==this.rootTarget.parent;)r.currentTarget=r.target,this.notifyTarget(r),s&&this.notifyTarget(r,"mouseenter"),r.target=r.target.parent;e.overTargets=i.composedPath(),this.freeEvent(i),this.freeEvent(r)}mapPointerOut(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId);if(e.overTargets){const i="mouse"===t.pointerType||"pen"===t.pointerType,s=this.findMountedTarget(e.overTargets),r=this.createPointerEvent(t,"pointerout",s);this.dispatchEvent(r),i&&this.dispatchEvent(r,"mouseout");const n=this.createPointerEvent(t,"pointerleave",s);for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),i&&this.notifyTarget(n,"mouseleave"),n.target=n.target.parent;e.overTargets=null,this.freeEvent(r),this.freeEvent(n)}this.cursor=null}mapPointerUp(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=performance.now(),i=this.createPointerEvent(t);if(this.dispatchEvent(i,"pointerup"),"touch"===i.pointerType)this.dispatchEvent(i,"touchend");else if("mouse"===i.pointerType||"pen"===i.pointerType){const t=2===i.button;this.dispatchEvent(i,t?"rightup":"mouseup")}const s=this.trackingData(t.pointerId),r=this.findMountedTarget(s.pressTargetsByButton[t.button]);let n=r;if(r&&!i.composedPath().includes(r)){let e=r;for(;e&&!i.composedPath().includes(e);){if(i.currentTarget=e,this.notifyTarget(i,"pointerupoutside"),"touch"===i.pointerType)this.notifyTarget(i,"touchendoutside");else if("mouse"===i.pointerType||"pen"===i.pointerType){const t=2===i.button;this.notifyTarget(i,t?"rightupoutside":"mouseupoutside")}e=e.parent}delete s.pressTargetsByButton[t.button],n=e}if(n){const r=this.clonePointerEvent(i,"click");r.target=n,r.path=null,s.clicksByButton[t.button]||(s.clicksByButton[t.button]={clickCount:0,target:r.target,timeStamp:e});const o=s.clicksByButton[t.button];if(o.target===r.target&&e-o.timeStamp<200?++o.clickCount:o.clickCount=1,o.target=r.target,o.timeStamp=e,r.detail=o.clickCount,"mouse"===r.pointerType){const t=2===r.button;this.dispatchEvent(r,t?"rightclick":"click")}else"touch"===r.pointerType&&this.dispatchEvent(r,"tap");this.dispatchEvent(r,"pointertap"),this.freeEvent(r)}this.freeEvent(i)}mapPointerUpOutside(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId),i=this.findMountedTarget(e.pressTargetsByButton[t.button]),s=this.createPointerEvent(t);if(i){let r=i;for(;r;)s.currentTarget=r,this.notifyTarget(s,"pointerupoutside"),"touch"===s.pointerType?this.notifyTarget(s,"touchendoutside"):("mouse"===s.pointerType||"pen"===s.pointerType)&&this.notifyTarget(s,2===s.button?"rightupoutside":"mouseupoutside"),r=r.parent;delete e.pressTargetsByButton[t.button]}this.freeEvent(s)}mapWheel(t){if(!(t instanceof Jy))return void console.warn("EventBoundary cannot map a non-wheel event as a wheel event");const e=this.createWheelEvent(t);this.dispatchEvent(e),this.freeEvent(e)}findMountedTarget(t){if(!t)return null;let e=t[0];for(let i=1;i<t.length&&t[i].parent===e;i++)e=t[i];return e}createPointerEvent(t,e,i){const s=this.allocateEvent(qy);return this.copyPointerData(t,s),this.copyMouseData(t,s),this.copyData(t,s),s.nativeEvent=t.nativeEvent,s.originalEvent=t,s.target=i??this.hitTest(s.global.x,s.global.y)??this._hitElements[0],"string"==typeof e&&(s.type=e),s}createWheelEvent(t){const e=this.allocateEvent(Jy);return this.copyWheelData(t,e),this.copyMouseData(t,e),this.copyData(t,e),e.nativeEvent=t.nativeEvent,e.originalEvent=t,e.target=this.hitTest(e.global.x,e.global.y),e}clonePointerEvent(t,e){const i=this.allocateEvent(qy);return i.nativeEvent=t.nativeEvent,i.originalEvent=t.originalEvent,this.copyPointerData(t,i),this.copyMouseData(t,i),this.copyData(t,i),i.target=t.target,i.path=t.composedPath().slice(),i.type=e??i.type,i}copyWheelData(t,e){e.deltaMode=t.deltaMode,e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ}copyPointerData(t,e){t instanceof qy&&e instanceof qy&&(e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist)}copyMouseData(t,e){t instanceof Vy&&e instanceof Vy&&(e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.copyFrom(t.client),e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.copyFrom(t.movement),e.screen.copyFrom(t.screen),e.shiftKey=t.shiftKey,e.global.copyFrom(t.global))}copyData(t,e){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.detail=t.detail,e.view=t.view,e.which=t.which,e.layer.copyFrom(t.layer),e.page.copyFrom(t.page)}trackingData(t){return this.mappingState.trackingData[t]||(this.mappingState.trackingData[t]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[t]}allocateEvent(t){this.eventPool.has(t)||this.eventPool.set(t,[]);const e=this.eventPool.get(t).pop()||new t(this);return e.eventPhase=e.NONE,e.currentTarget=null,e.path=null,e.target=null,e}freeEvent(t){if(t.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const e=t.constructor;this.eventPool.has(e)||this.eventPool.set(e,[]),this.eventPool.get(e).push(t)}notifyListeners(t,e){const i=t.currentTarget._events[e];if(i&&t.currentTarget.isInteractive())if("fn"in i)i.once&&t.currentTarget.removeListener(e,i.fn,void 0,!0),i.fn.call(i.context,t);else for(let s=0,r=i.length;s<r&&!t.propagationImmediatelyStopped;s++)i[s].once&&t.currentTarget.removeListener(e,i[s].fn,void 0,!0),i[s].fn.call(i[s].context,t)}}const tv={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},ev=class t{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new Qy(null),jy.init(this),this.autoPreventDefault=!0,this.eventsAdded=!1,this.rootPointerEvent=new qy(null),this.rootWheelEvent=new Jy(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...t.defaultEventFeatures},{set:(t,e,i)=>("globalMove"===e&&(this.rootBoundary.enableGlobalMoveEvents=i),t[e]=i,!0)}),this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.onPointerOverOut=this.onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{view:i,resolution:s}=this.renderer;this.setTargetElement(i),this.resolution=s,t._defaultEventMode=e.eventMode??"auto",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(t){this.resolution=t}destroy(){this.setTargetElement(null),this.renderer=null}setCursor(t){t=t||"default";let e=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(e=!1),this.currentCursor===t)return;this.currentCursor=t;const i=this.cursorStyles[t];if(i)switch(typeof i){case"string":e&&(this.domElement.style.cursor=i);break;case"function":i(t);break;case"object":e&&Object.assign(this.domElement.style,i)}else e&&"string"==typeof t&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,t)&&(this.domElement.style.cursor=t)}get pointer(){return this.rootPointerEvent}onPointerDown(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&(t.cancelable||!("cancelable"in t))&&t.preventDefault();for(let i=0,s=e.length;i<s;i++){const t=e[i],s=this.bootstrapEvent(this.rootPointerEvent,t);this.rootBoundary.mapEvent(s)}this.setCursor(this.rootBoundary.cursor)}onPointerMove(t){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,jy.pointerMoved();const e=this.normalizeToPointerData(t);for(let i=0,s=e.length;i<s;i++){const t=this.bootstrapEvent(this.rootPointerEvent,e[i]);this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onPointerUp(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let e=t.target;t.composedPath&&t.composedPath().length>0&&(e=t.composedPath()[0]);const i=e!==this.domElement?"outside":"",s=this.normalizeToPointerData(t);for(let r=0,n=s.length;r<n;r++){const t=this.bootstrapEvent(this.rootPointerEvent,s[r]);t.type+=i,this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onPointerOverOut(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this.normalizeToPointerData(t);for(let i=0,s=e.length;i<s;i++){const t=this.bootstrapEvent(this.rootPointerEvent,e[i]);this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onWheel(t){if(!this.features.wheel)return;const e=this.normalizeWheelEvent(t);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(e)}setTargetElement(t){this.removeEvents(),this.domElement=t,jy.domElement=t,this.addEvents()}addEvents(){if(this.eventsAdded||!this.domElement)return;jy.addTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="none",t.msTouchAction="none"):this.supportsPointerEvents&&(t.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this.onPointerMove,!0),this.domElement.addEventListener("pointerdown",this.onPointerDown,!0),this.domElement.addEventListener("pointerleave",this.onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this.onPointerOverOut,!0),globalThis.addEventListener("pointerup",this.onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this.onPointerMove,!0),this.domElement.addEventListener("mousedown",this.onPointerDown,!0),this.domElement.addEventListener("mouseout",this.onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this.onPointerOverOut,!0),globalThis.addEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this.onPointerDown,!0),this.domElement.addEventListener("touchend",this.onPointerUp,!0),this.domElement.addEventListener("touchmove",this.onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this.eventsAdded=!0}removeEvents(){if(!this.eventsAdded||!this.domElement)return;jy.removeTickerListener();const t=this.domElement.style;globalThis.navigator.msPointerEnabled?(t.msContentZooming="",t.msTouchAction=""):this.supportsPointerEvents&&(t.touchAction=""),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this.onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this.onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this.onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this.onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this.onPointerMove,!0),this.domElement.removeEventListener("mousedown",this.onPointerDown,!0),this.domElement.removeEventListener("mouseout",this.onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this.onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this.onPointerDown,!0),this.domElement.removeEventListener("touchend",this.onPointerUp,!0),this.domElement.removeEventListener("touchmove",this.onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this.eventsAdded=!1}mapPositionToPoint(t,e,i){const s=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},r=1/this.resolution;t.x=(e-s.left)*(this.domElement.width/s.width)*r,t.y=(i-s.top)*(this.domElement.height/s.height)*r}normalizeToPointerData(t){const e=[];if(this.supportsTouchEvents&&t instanceof TouchEvent)for(let i=0,s=t.changedTouches.length;i<s;i++){const s=t.changedTouches[i];typeof s.button>"u"&&(s.button=0),typeof s.buttons>"u"&&(s.buttons=1),typeof s.isPrimary>"u"&&(s.isPrimary=1===t.touches.length&&"touchstart"===t.type),typeof s.width>"u"&&(s.width=s.radiusX||1),typeof s.height>"u"&&(s.height=s.radiusY||1),typeof s.tiltX>"u"&&(s.tiltX=0),typeof s.tiltY>"u"&&(s.tiltY=0),typeof s.pointerType>"u"&&(s.pointerType="touch"),typeof s.pointerId>"u"&&(s.pointerId=s.identifier||0),typeof s.pressure>"u"&&(s.pressure=s.force||.5),typeof s.twist>"u"&&(s.twist=0),typeof s.tangentialPressure>"u"&&(s.tangentialPressure=0),typeof s.layerX>"u"&&(s.layerX=s.offsetX=s.clientX),typeof s.layerY>"u"&&(s.layerY=s.offsetY=s.clientY),s.isNormalized=!0,s.type=t.type,e.push(s)}else if(globalThis.MouseEvent&&(!(t instanceof MouseEvent)||this.supportsPointerEvents&&t instanceof globalThis.PointerEvent))e.push(t);else{const i=t;typeof i.isPrimary>"u"&&(i.isPrimary=!0),typeof i.width>"u"&&(i.width=1),typeof i.height>"u"&&(i.height=1),typeof i.tiltX>"u"&&(i.tiltX=0),typeof i.tiltY>"u"&&(i.tiltY=0),typeof i.pointerType>"u"&&(i.pointerType="mouse"),typeof i.pointerId>"u"&&(i.pointerId=1),typeof i.pressure>"u"&&(i.pressure=.5),typeof i.twist>"u"&&(i.twist=0),typeof i.tangentialPressure>"u"&&(i.tangentialPressure=0),i.isNormalized=!0,e.push(i)}return e}normalizeWheelEvent(t){const e=this.rootWheelEvent;return this.transferMouseData(e,t),e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ,e.deltaMode=t.deltaMode,this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.nativeEvent=t,e.type=t.type,e}bootstrapEvent(t,e){return t.originalEvent=null,t.nativeEvent=e,t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist,this.transferMouseData(t,e),this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.isTrusted=e.isTrusted,"pointerleave"===t.type&&(t.type="pointerout"),t.type.startsWith("mouse")&&(t.type=t.type.replace("mouse","pointer")),t.type.startsWith("touch")&&(t.type=tv[t.type]||t.type),t}transferMouseData(t,e){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.x=e.clientX,t.client.y=e.clientY,t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.x=e.movementX,t.movement.y=e.movementY,t.page.x=e.pageX,t.page.y=e.pageY,t.relatedTarget=null,t.shiftKey=e.shiftKey}};ev.extension={name:"events",type:[Up.RendererSystem,Up.CanvasRendererSystem]},ev.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let iv=ev;function sv(t){return"dynamic"===t||"static"===t}Wp.add(iv);const rv={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,_internalInteractive:void 0,get interactive(){return this._internalInteractive??sv(iv.defaultEventMode)},set interactive(t){Md("7.2.0","Setting interactive is deprecated, use eventMode = 'none'/'passive'/'auto'/'static'/'dynamic' instead."),this._internalInteractive=t,this.eventMode=t?"static":"auto"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??iv.defaultEventMode},set eventMode(t){this._internalInteractive=sv(t),this._internalEventMode=t},isInteractive(){return"static"===this.eventMode||"dynamic"===this.eventMode},interactiveChildren:!0,hitArea:null,addEventListener(t,e,i){const s="boolean"==typeof i&&i||"object"==typeof i&&i.capture,r="object"==typeof i?i.signal:void 0,n="object"==typeof i&&!0===i.once,o="function"==typeof e?void 0:e;t=s?`${t}capture`:t;const a="function"==typeof e?e:e.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(t,a,o)}),n?l.once(t,a,o):l.on(t,a,o)},removeEventListener(t,e,i){const s="function"==typeof e?void 0:e;t="boolean"==typeof i&&i||"object"==typeof i&&i.capture?`${t}capture`:t,e="function"==typeof e?e:e.handleEvent,this.off(t,e,s)},dispatchEvent(t){if(!(t instanceof zy))throw new Error("DisplayObject cannot propagate events outside of the Federated Events API");return t.defaultPrevented=!1,t.path=null,t.target=this,t.manager.dispatchEvent(t),!t.defaultPrevented}};Hg.mixin(rv);const nv=new vf;class ov{constructor(t){this.renderer=t}async image(t,e,i,s){const r=new Image;return r.src=await this.base64(t,e,i,s),r}async base64(t,e,i,s){const r=this.canvas(t,s);if(void 0!==r.toBlob)return new Promise((t,s)=>{r.toBlob(e=>{if(!e)return void s(new Error("ICanvas.toBlob failed!"));const i=new FileReader;i.onload=()=>t(i.result),i.onerror=s,i.readAsDataURL(e)},e,i)});if(void 0!==r.toDataURL)return r.toDataURL(e,i);if(void 0!==r.convertToBlob){const t=await r.convertToBlob({type:e,quality:i});return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsDataURL(t)})}throw new Error("CanvasExtract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(t,e){const i=this.renderer;if(!i)throw new Error("The CanvasExtract has already been destroyed");let s,r,n;t&&(t instanceof Tm?n=t:(n=i.generateTexture(t,{region:e,resolution:i.resolution}),e&&(nv.width=e.width,nv.height=e.height,e=nv))),n?(s=n.baseTexture._canvasRenderTarget.context,r=n.baseTexture._canvasRenderTarget.resolution,e=e??n.frame):(s=i.canvasContext.rootContext,r=i._view.resolution,e||((e=nv).width=i.width/r,e.height=i.height/r));const o=Math.round(e.x*r),a=Math.round(e.y*r),l=Math.max(Math.round(e.width*r),1),h=Math.max(Math.round(e.height*r),1),u=new Op(l,h,1),c=s.getImageData(o,a,l,h);return u.context.putImageData(c,0,0),u.canvas}pixels(t,e){const i=this.renderer;if(!i)throw new Error("The CanvasExtract has already been destroyed");let s,r,n;t&&(t instanceof Tm?n=t:(n=i.generateTexture(t,{region:e,resolution:i.resolution}),e&&(nv.width=e.width,nv.height=e.height,e=nv))),n?(s=n.baseTexture._canvasRenderTarget.context,r=n.baseTexture._canvasRenderTarget.resolution,e=e??n.frame):(s=i.canvasContext.rootContext,r=i.resolution,e||((e=nv).width=i.width/r,e.height=i.height/r));const o=Math.round(e.x*r),a=Math.round(e.y*r),l=Math.max(Math.round(e.width*r),1),h=Math.max(Math.round(e.height*r),1);return s.getImageData(o,a,l,h).data}destroy(){this.renderer=null}}let av;function lv(t){const e=Oh.ADAPTER.createCanvas(6,1),i=e.getContext("2d");return i.fillStyle=t,i.fillRect(0,0,6,1),e}function hv(){if(typeof document>"u")return!1;if(void 0!==av)return av;const t=lv("#ff00ff"),e=lv("#ffff00"),i=Oh.ADAPTER.createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(t,0,0),i.drawImage(e,2,0);const s=i.getImageData(2,0,1,1);if(s){const t=s.data;av=255===t[0]&&0===t[1]&&0===t[2]}else av=!1;return av}ov.extension={name:"extract",type:Up.CanvasRendererSystem},Wp.add(ov),tf.prototype.getDrawableSource=function(){const t=this.resource;return t?t.bitmap||t.source:null},vm.prototype._canvasRenderTarget=null,Em.prototype.patternCache=null,Em.prototype.tintCache=null;const uv=new Pf;class cv{constructor(t){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=function(t=[]){return hv()?(t[mh.NORMAL]="source-over",t[mh.ADD]="lighter",t[mh.MULTIPLY]="multiply",t[mh.SCREEN]="screen",t[mh.OVERLAY]="overlay",t[mh.DARKEN]="darken",t[mh.LIGHTEN]="lighten",t[mh.COLOR_DODGE]="color-dodge",t[mh.COLOR_BURN]="color-burn",t[mh.HARD_LIGHT]="hard-light",t[mh.SOFT_LIGHT]="soft-light",t[mh.DIFFERENCE]="difference",t[mh.EXCLUSION]="exclusion",t[mh.HUE]="hue",t[mh.SATURATION]="saturation",t[mh.COLOR]="color",t[mh.LUMINOSITY]="luminosity"):(t[mh.NORMAL]="source-over",t[mh.ADD]="lighter",t[mh.MULTIPLY]="source-over",t[mh.SCREEN]="source-over",t[mh.OVERLAY]="source-over",t[mh.DARKEN]="source-over",t[mh.LIGHTEN]="source-over",t[mh.COLOR_DODGE]="source-over",t[mh.COLOR_BURN]="source-over",t[mh.HARD_LIGHT]="source-over",t[mh.SOFT_LIGHT]="source-over",t[mh.DIFFERENCE]="source-over",t[mh.EXCLUSION]="source-over",t[mh.HUE]="source-over",t[mh.SATURATION]="source-over",t[mh.COLOR]="source-over",t[mh.LUMINOSITY]="source-over"),t[mh.NORMAL_NPM]=t[mh.NORMAL],t[mh.ADD_NPM]=t[mh.ADD],t[mh.SCREEN_NPM]=t[mh.SCREEN],t[mh.SRC_IN]="source-in",t[mh.SRC_OUT]="source-out",t[mh.SRC_ATOP]="source-atop",t[mh.DST_OVER]="destination-over",t[mh.DST_IN]="destination-in",t[mh.DST_OUT]="destination-out",t[mh.DST_ATOP]="destination-atop",t[mh.XOR]="xor",t[mh.SUBTRACT]="source-over",t}(),this._activeBlendMode=null,this._projTransform=null,this._outerBlend=!1,this.renderer=t}init(){const t=this.renderer.background.alpha<1;if(this.rootContext=this.renderer.view.getContext("2d",{alpha:t}),this.activeContext=this.rootContext,!this.rootContext.imageSmoothingEnabled){const t=this.rootContext;t.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":t.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":t.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":t.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(t,e,i){let s=t;const r=this._projTransform,n=this.activeResolution;i=i||n,r&&(s=uv,s.copyFrom(t),s.prepend(r)),e?this.activeContext.setTransform(s.a*i,s.b*i,s.c*i,s.d*i,s.tx*n|0,s.ty*n|0):this.activeContext.setTransform(s.a*i,s.b*i,s.c*i,s.d*i,s.tx*n,s.ty*n)}clear(t,e){const{activeContext:i,renderer:s}=this,r=t?pp.shared.setValue(t):this.renderer.background.backgroundColor;i.clearRect(0,0,s.width,s.height),t&&(i.globalAlpha=e??this.renderer.background.alpha,i.fillStyle=r.toHex(),i.fillRect(0,0,s.width,s.height),i.globalAlpha=1)}setBlendMode(t,e){const i=t===mh.SRC_IN||t===mh.SRC_OUT||t===mh.DST_IN||t===mh.DST_ATOP;!e&&i&&(t=mh.NORMAL),this._activeBlendMode!==t&&(this._activeBlendMode=t,this._outerBlend=i,this.activeContext.globalCompositeOperation=this.blendModes[t])}resize(){this.smoothProperty&&(this.rootContext[this.smoothProperty]=tf.defaultOptions.scaleMode===wh.LINEAR)}invalidateBlendMode(){this._activeBlendMode=this.blendModes.indexOf(this.activeContext.globalCompositeOperation)}destroy(){this.renderer=null,this.rootContext=null,this.activeContext=null,this.smoothProperty=null}}cv.extension={type:Up.CanvasRendererSystem,name:"canvasContext"},Wp.add(cv);class dv{constructor(t){this._foundShapes=[],this.renderer=t}pushMask(t){const e=this.renderer,i=t.maskObject||t;e.canvasContext.activeContext.save();const s=this._foundShapes;if(this.recursiveFindShapes(i,s),s.length>0){const t=e.canvasContext.activeContext;t.beginPath();for(let e=0;e<s.length;e++){const t=s[e],i=t.transform.worldTransform;this.renderer.canvasContext.setContextTransform(i),this.renderGraphicsShape(t)}s.length=0,t.clip()}}recursiveFindShapes(t,e){t.geometry&&t.geometry.graphicsData&&e.push(t);const{children:i}=t;if(i)for(let s=0;s<i.length;s++)this.recursiveFindShapes(i[s],e)}renderGraphicsShape(t){t.finishPoly();const e=this.renderer.canvasContext.activeContext,i=t.geometry.graphicsData,s=i.length;if(0!==s)for(let r=0;r<s;r++){const t=i[r],s=t.shape;if(s.type===mf.POLY){let i=s.points;const r=t.holes;let n,o,a,l;e.moveTo(i[0],i[1]);for(let t=1;t<i.length/2;t++)e.lineTo(i[2*t],i[2*t+1]);if(r.length>0){n=0,a=i[0],l=i[1];for(let t=2;t+2<i.length;t+=2)n+=(i[t]-a)*(i[t+3]-l)-(i[t+2]-a)*(i[t+1]-l);for(let t=0;t<r.length;t++)if(i=r[t].shape.points,i){o=0,a=i[0],l=i[1];for(let t=2;t+2<i.length;t+=2)o+=(i[t]-a)*(i[t+3]-l)-(i[t+2]-a)*(i[t+1]-l);if(o*n<0){e.moveTo(i[0],i[1]);for(let t=2;t<i.length;t+=2)e.lineTo(i[t],i[t+1])}else{e.moveTo(i[i.length-2],i[i.length-1]);for(let t=i.length-4;t>=0;t-=2)e.lineTo(i[t],i[t+1])}r[t].shape.closeStroke&&e.closePath()}}i[0]===i[i.length-2]&&i[1]===i[i.length-1]&&e.closePath()}else if(s.type===mf.RECT)e.rect(s.x,s.y,s.width,s.height),e.closePath();else if(s.type===mf.CIRC)e.arc(s.x,s.y,s.radius,0,2*Math.PI),e.closePath();else if(s.type===mf.ELIP){const t=2*s.width,i=2*s.height,r=s.x-t/2,n=s.y-i/2,o=.5522848,a=t/2*o,l=i/2*o,h=r+t,u=n+i,c=r+t/2,d=n+i/2;e.moveTo(r,d),e.bezierCurveTo(r,d-l,c-a,n,c,n),e.bezierCurveTo(c+a,n,h,d-l,h,d),e.bezierCurveTo(h,d+l,c+a,u,c,u),e.bezierCurveTo(c-a,u,r,d+l,r,d),e.closePath()}else if(s.type===mf.RREC){const t=s.x,i=s.y,r=s.width,n=s.height;let o=s.radius;const a=Math.min(r,n)/2;o=o>a?a:o,e.moveTo(t,i+o),e.lineTo(t,i+n-o),e.quadraticCurveTo(t,i+n,t+o,i+n),e.lineTo(t+r-o,i+n),e.quadraticCurveTo(t+r,i+n,t+r,i+n-o),e.lineTo(t+r,i+o),e.quadraticCurveTo(t+r,i,t+r-o,i),e.lineTo(t+o,i),e.quadraticCurveTo(t,i,t,i+o),e.closePath()}}}popMask(t){t.canvasContext.activeContext.restore(),t.canvasContext.invalidateBlendMode()}destroy(){}}dv.extension={type:Up.CanvasRendererSystem,name:"mask"},Wp.add(dv);class pv{constructor(t){this.renderer=t}render(t,e){const i=this.renderer;if(!i.view)return;const s=i.canvasContext;let r,n,o,a;e&&(r=e.renderTexture,n=e.clear,o=e.transform,a=e.skipUpdateTransform),this.renderingToScreen=!r,i.emit("prerender");const l=i.resolution;r?(r=r.castToBaseTexture(),r._canvasRenderTarget||(r._canvasRenderTarget=new Op(r.width,r.height,r.resolution),r.resource=new Bg(r._canvasRenderTarget.canvas),r.valid=!0),s.activeContext=r._canvasRenderTarget.context,i.canvasContext.activeResolution=r._canvasRenderTarget.resolution):(s.activeContext=s.rootContext,s.activeResolution=l);const h=s.activeContext;if(s._projTransform=o||null,r||(this.lastObjectRendered=t),!a){const e=t.enableTempParent();t.updateTransform(),t.disableTempParent(e)}if(h.save(),h.setTransform(1,0,0,1,0,0),h.globalAlpha=1,s._activeBlendMode=mh.NORMAL,s._outerBlend=!1,h.globalCompositeOperation=s.blendModes[mh.NORMAL],n??i.background.clearBeforeRender)if(this.renderingToScreen){h.clearRect(0,0,i.width,i.height);const t=i.background;t.alpha>0&&(h.globalAlpha=t.backgroundColor.alpha,h.fillStyle=t.backgroundColor.toHex(),h.fillRect(0,0,i.width,i.height),h.globalAlpha=1)}else r._canvasRenderTarget.clear(),r.clear.alpha>0&&(h.globalAlpha=r.clear.alpha,h.fillStyle=r.clear.toHex(),h.fillRect(0,0,r.realWidth,r.realHeight),h.globalAlpha=1);const u=s.activeContext;s.activeContext=h,t.renderCanvas(i),s.activeContext=u,h.restore(),s.activeResolution=l,s._projTransform=null,i.emit("postrender")}destroy(){this.lastObjectRendered=null,this.render=null}}pv.extension={type:Up.CanvasRendererSystem,name:"objectRenderer"},Wp.add(pv);const{deprecation:fv}=Dp,mv=class t extends mg{constructor(e){super(),this.type=ph.CANVAS,this.rendererLogId="Canvas",e=Object.assign({},Oh.RENDER_OPTIONS,e);const i={runners:["init","destroy","contextChange","resolutionChange","reset","update","postrender","prerender","resize"],systems:t.__systems,priority:["textureGenerator","background","_view","_plugin","startup","mask","canvasContext","objectRenderer"]};this.setup(i),"useContextAlpha"in e&&(fv("7.0.0","options.useContextAlpha is deprecated, use options.backgroundAlpha instead"),e.backgroundAlpha=!1===e.useContextAlpha?1:e.backgroundAlpha),this._plugin.rendererPlugins=t.__plugins,this.options=e,this.startup.run(this.options)}static test(){return!0}generateTexture(t,e){return this.textureGenerator.generateTexture(t,e)}reset(){}render(t,e){this.objectRenderer.render(t,e)}clear(){this.canvasContext.clear()}destroy(t){this.runners.destroy.items.reverse(),this.emitWithCustomOptions(this.runners.destroy,{_view:t}),super.destroy()}get plugins(){return this._plugin.plugins}resize(t,e){this._view.resizeView(t,e)}get width(){return this._view.element.width}get height(){return this._view.element.height}get resolution(){return this._view.resolution}set resolution(t){this._view.resolution=t,this.runners.resolutionChange.emit(t)}get autoDensity(){return this._view.autoDensity}get view(){return this._view.element}get screen(){return this._view.screen}get lastObjectRendered(){return this.objectRenderer.lastObjectRendered}get renderingToScreen(){return this.objectRenderer.renderingToScreen}get clearBeforeRender(){return this.background.clearBeforeRender}get blendModes(){return fv("7.0.0","renderer.blendModes has been deprecated, please use renderer.canvasContext.blendModes instead"),this.canvasContext.blendModes}get maskManager(){return fv("7.0.0","renderer.maskManager has been deprecated, please use renderer.mask instead"),this.mask}get refresh(){return fv("7.0.0","renderer.refresh has been deprecated"),!0}get rootContext(){return fv("7.0.0","renderer.rootContext has been deprecated, please use renderer.canvasContext.rootContext instead"),this.canvasContext.rootContext}get context(){return fv("7.0.0","renderer.context has been deprecated, please use renderer.canvasContext.activeContext instead"),this.canvasContext.activeContext}get smoothProperty(){return fv("7.0.0","renderer.smoothProperty has been deprecated, please use renderer.canvasContext.smoothProperty instead"),this.canvasContext.smoothProperty}setBlendMode(t,e){fv("7.0.0","renderer.setBlendMode has been deprecated, use renderer.canvasContext.setBlendMode instead"),this.canvasContext.setBlendMode(t,e)}invalidateBlendMode(){fv("7.0.0","renderer.invalidateBlendMode has been deprecated, use renderer.canvasContext.invalidateBlendMode instead"),this.canvasContext.invalidateBlendMode()}setContextTransform(t,e,i){fv("7.0.0","renderer.setContextTransform has been deprecated, use renderer.canvasContext.setContextTransform instead"),this.canvasContext.setContextTransform(t,e,i)}get backgroundColor(){return fv("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color}set backgroundColor(t){fv("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color=t}get backgroundAlpha(){return fv("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha}set backgroundAlpha(t){fv("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha=t}get preserveDrawingBuffer(){return fv("7.0.0","renderer.preserveDrawingBuffer has been deprecated"),!1}get useContextAlpha(){return fv("7.0.0","renderer.useContextAlpha has been deprecated"),!1}};mv.extension={type:Up.Renderer,priority:0},mv.__plugins={},mv.__systems={};let gv=mv;Wp.handleByMap(Up.CanvasRendererPlugin,gv.__plugins),Wp.handleByMap(Up.CanvasRendererSystem,gv.__systems),Wp.add(gv);const yv={canvas:null,getTintedCanvas:(t,e)=>{const i=t.texture,s=pp.shared.setValue(e).toHex();i.tintCache=i.tintCache||{};const r=i.tintCache[s];let n;if(r){if(r.tintId===i._updateID)return i.tintCache[s];n=i.tintCache[s]}else n=Oh.ADAPTER.createCanvas();if(yv.tintMethod(i,e,n),n.tintId=i._updateID,yv.convertTintToImage&&void 0!==n.toDataURL){const t=new Image;t.src=n.toDataURL(),i.tintCache[s]=t}else i.tintCache[s]=n;return n},getTintedPattern:(t,e)=>{const i=pp.shared.setValue(e).toHex();t.patternCache=t.patternCache||{};let s=t.patternCache[i];return s?.tintId===t._updateID||(yv.canvas||(yv.canvas=Oh.ADAPTER.createCanvas()),yv.tintMethod(t,e,yv.canvas),s=yv.canvas.getContext("2d").createPattern(yv.canvas,"repeat"),s.tintId=t._updateID,t.patternCache[i]=s),s},tintWithMultiply:(t,e,i)=>{const s=i.getContext("2d"),r=t._frame.clone(),n=t.baseTexture.resolution;r.x*=n,r.y*=n,r.width*=n,r.height*=n,i.width=Math.ceil(r.width),i.height=Math.ceil(r.height),s.save(),s.fillStyle=pp.shared.setValue(e).toHex(),s.fillRect(0,0,r.width,r.height),s.globalCompositeOperation="multiply";const o=t.baseTexture.getDrawableSource();s.drawImage(o,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.globalCompositeOperation="destination-atop",s.drawImage(o,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore()},tintWithOverlay:(t,e,i)=>{const s=i.getContext("2d"),r=t._frame.clone(),n=t.baseTexture.resolution;r.x*=n,r.y*=n,r.width*=n,r.height*=n,i.width=Math.ceil(r.width),i.height=Math.ceil(r.height),s.save(),s.globalCompositeOperation="copy",s.fillStyle=`#${`00000${(0|e).toString(16)}`.slice(-6)}`,s.fillRect(0,0,r.width,r.height),s.globalCompositeOperation="destination-atop",s.drawImage(t.baseTexture.getDrawableSource(),r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore()},tintWithPerPixel:(t,e,i)=>{const s=i.getContext("2d"),r=t._frame.clone(),n=t.baseTexture.resolution;r.x*=n,r.y*=n,r.width*=n,r.height*=n,i.width=Math.ceil(r.width),i.height=Math.ceil(r.height),s.save(),s.globalCompositeOperation="copy",s.drawImage(t.baseTexture.getDrawableSource(),r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore();const[o,a,l]=pp.shared.setValue(e).toArray(),h=s.getImageData(0,0,r.width,r.height),u=h.data;for(let c=0;c<u.length;c+=4)u[c+0]*=o,u[c+1]*=a,u[c+2]*=l;s.putImageData(h,0,0)},roundColor:t=>(Md("7.3.0","PIXI.canvasUtils.roundColor is deprecated"),pp.shared.setValue(t).round(yv.cacheStepsPerColorChannel).toNumber()),cacheStepsPerColorChannel:8,convertTintToImage:!1,canUseMultiply:hv(),tintMethod:null};let vv;yv.tintMethod=yv.canUseMultiply?yv.tintWithMultiply:yv.tintWithPerPixel;const xv=new Pf;Ty.prototype.generateCanvasTexture=function(t,e=1){const i=this.getLocalBounds(new vf);i.width=Math.max(i.width,1/e),i.height=Math.max(i.height,1/e);const s=Tm.create({width:i.width,height:i.height,scaleMode:t,resolution:e});vv||(vv=new gv),this.transform.updateLocalTransform(),this.transform.localTransform.copyTo(xv),xv.invert(),xv.tx-=i.x,xv.ty-=i.y,vv.render(this,{renderTexture:s,clear:!0,transform:xv});const r=Em.from(s.baseTexture._canvasRenderTarget.canvas,{scaleMode:t});return r.baseTexture.setResolution(e),r},Ty.prototype.cachedGraphicsData=[],Ty.prototype._renderCanvas=function(t){!0!==this.isMask&&(this.finishPoly(),t.plugins.graphics.render(this))};class bv{static offsetPolygon(t,e){const i=[],s=t.length;e=bv.isPolygonClockwise(t)?e:-1*e;for(let r=0;r<s;r+=2){let n=r-2;n<0&&(n+=s);const o=(r+2)%s;let a=t[r]-t[n],l=t[r+1]-t[n+1],h=Math.sqrt(a*a+l*l);a/=h,l/=h,a*=e,l*=e;const u=-l,c=a,d=[t[n]+u,t[n+1]+c],p=[t[r]+u,t[r+1]+c];let f=t[o]-t[r],m=t[o+1]-t[r+1];h=Math.sqrt(f*f+m*m),f/=h,m/=h,f*=e,m*=e;const g=-m,y=f,v=[t[r]+g,t[r+1]+y],x=[t[o]+g,t[o+1]+y],b=bv.findIntersection(d[0],d[1],p[0],p[1],v[0],v[1],x[0],x[1]);b&&i.push(...b)}return i}static findIntersection(t,e,i,s,r,n,o,a){const l=(a-n)*(i-t)-(o-r)*(s-e),h=(o-r)*(e-n)-(a-n)*(t-r);if(0===l)return 0===h&&0===(i-t)*(e-n)-(s-e)*(t-r)?[(t+i)/2,(e+s)/2]:null;const u=h/l;return[t+u*(i-t),e+u*(s-e)]}static isPolygonClockwise(t){let e=0;for(let i=0,s=t.length-2;i<t.length;s=i,i+=2)e+=(t[i]-t[s])*(t[i+1]+t[s+1]);return e>0}}class wv{constructor(t){this._svgMatrix=null,this._tempMatrix=new Pf,this.renderer=t}_calcCanvasStyle(t,e){let i;return t.texture&&t.texture.baseTexture!==Em.WHITE.baseTexture?t.texture.valid?(i=yv.getTintedPattern(t.texture,e),this.setPatternTransform(i,t.matrix||Pf.IDENTITY)):i="#808080":i=`#${`00000${(0|e).toString(16)}`.slice(-6)}`,i}render(t){const e=this.renderer,i=e.canvasContext.activeContext,s=t.worldAlpha,r=t.transform.worldTransform;e.canvasContext.setContextTransform(r),e.canvasContext.setBlendMode(t.blendMode);const n=t.geometry.graphicsData;let o,a;const l=pp.shared.setValue(t.tint).toArray();for(let h=0;h<n.length;h++){const t=n[h],u=t.shape,c=t.fillStyle,d=t.lineStyle,p=0|t.fillStyle.color,f=0|t.lineStyle.color;if(t.matrix&&e.canvasContext.setContextTransform(r.copyTo(this._tempMatrix).append(t.matrix)),c.visible&&(o=this._calcCanvasStyle(c,pp.shared.setValue(p).multiply(l).toNumber())),d.visible&&(a=this._calcCanvasStyle(d,pp.shared.setValue(f).multiply(l).toNumber())),i.lineWidth=d.width,i.lineCap=d.cap,i.lineJoin=d.join,i.miterLimit=d.miterLimit,t.type===mf.POLY){i.beginPath();const e=u;let r=e.points;const n=t.holes;let l,h,p,f,m;i.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)i.lineTo(r[t],r[t+1]);if(e.closeStroke&&i.closePath(),n.length>0){m=[],l=0,p=r[0],f=r[1];for(let t=2;t+2<r.length;t+=2)l+=(r[t]-p)*(r[t+3]-f)-(r[t+2]-p)*(r[t+1]-f);for(let t=0;t<n.length;t++)if(r=n[t].shape.points,r){h=0,p=r[0],f=r[1];for(let t=2;t+2<r.length;t+=2)h+=(r[t]-p)*(r[t+3]-f)-(r[t+2]-p)*(r[t+1]-f);if(h*l<0){i.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)i.lineTo(r[t],r[t+1])}else{i.moveTo(r[r.length-2],r[r.length-1]);for(let t=r.length-4;t>=0;t-=2)i.lineTo(r[t],r[t+1])}n[t].shape.closeStroke&&i.closePath(),m[t]=h*l<0}}c.visible&&(i.globalAlpha=c.alpha*s,i.fillStyle=o,i.fill()),d.visible&&this.paintPolygonStroke(e,d,a,n,m,s,i)}else if(t.type===mf.RECT){const t=u;if(c.visible&&(i.globalAlpha=c.alpha*s,i.fillStyle=o,i.fillRect(t.x,t.y,t.width,t.height)),d.visible){const e=d.width*(.5-(1-d.alignment)),r=t.width+2*e,n=t.height+2*e;i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.strokeRect(t.x-e,t.y-e,r,n)}}else if(t.type===mf.CIRC){const t=u;if(i.beginPath(),i.arc(t.x,t.y,t.radius,0,2*Math.PI),i.closePath(),c.visible&&(i.globalAlpha=c.alpha*s,i.fillStyle=o,i.fill()),d.visible){if(.5!==d.alignment){const e=d.width*(.5-(1-d.alignment));i.beginPath(),i.arc(t.x,t.y,t.radius+e,0,2*Math.PI),i.closePath()}i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.stroke()}}else if(t.type===mf.ELIP){const t=u,e=1===d.alignment;if(e||this.paintEllipse(t,c,d,o,s,i),d.visible){if(.5!==d.alignment){const e=.5522848,s=d.width*(.5-(1-d.alignment)),r=2*(t.width+s),n=2*(t.height+s),o=t.x-r/2,a=t.y-n/2,l=r/2*e,h=n/2*e,u=o+r,c=a+n,p=o+r/2,f=a+n/2;i.beginPath(),i.moveTo(o,f),i.bezierCurveTo(o,f-h,p-l,a,p,a),i.bezierCurveTo(p+l,a,u,f-h,u,f),i.bezierCurveTo(u,f+h,p+l,c,p,c),i.bezierCurveTo(p-l,c,o,f+h,o,f),i.closePath()}i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.stroke()}e&&this.paintEllipse(t,c,d,o,s,i)}else if(t.type===mf.RREC){const t=u,e=1===d.alignment;if(e||this.paintRoundedRectangle(t,c,d,o,s,i),d.visible){if(.5!==d.alignment){const e=t.width,s=t.height,r=d.width*(.5-(1-d.alignment)),n=t.x-r,o=t.y-r,a=t.width+2*r,l=t.height+2*r,h=r*(d.alignment>=1?Math.min(a/e,l/s):Math.min(e/a,s/l));let u=t.radius+h;const c=Math.min(a,l)/2;u=u>c?c:u,i.beginPath(),i.moveTo(n,o+u),i.lineTo(n,o+l-u),i.quadraticCurveTo(n,o+l,n+u,o+l),i.lineTo(n+a-u,o+l),i.quadraticCurveTo(n+a,o+l,n+a,o+l-u),i.lineTo(n+a,o+u),i.quadraticCurveTo(n+a,o,n+a-u,o),i.lineTo(n+u,o),i.quadraticCurveTo(n,o,n,o+u),i.closePath()}i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.stroke()}e&&this.paintRoundedRectangle(t,c,d,o,s,i)}}}paintPolygonStroke(t,e,i,s,r,n,o){if(.5!==e.alignment){const i=e.width*(.5-(1-e.alignment));let n,a=bv.offsetPolygon(t.points,i);o.beginPath(),o.moveTo(a[0],a[1]);for(let t=2;t<a.length;t+=2)o.lineTo(a[t],a[t+1]);t.closeStroke&&o.closePath();for(let t=0;t<s.length;t++){if(n=s[t].shape.points,a=bv.offsetPolygon(n,i),r[t]){o.moveTo(a[0],a[1]);for(let t=2;t<a.length;t+=2)o.lineTo(a[t],a[t+1])}else{o.moveTo(a[a.length-2],a[a.length-1]);for(let t=a.length-4;t>=0;t-=2)o.lineTo(a[t],a[t+1])}s[t].shape.closeStroke&&o.closePath()}}o.globalAlpha=e.alpha*n,o.strokeStyle=i,o.stroke()}paintEllipse(t,e,i,s,r,n){const o=2*t.width,a=2*t.height,l=t.x-o/2,h=t.y-a/2,u=.5522848,c=o/2*u,d=a/2*u,p=l+o,f=h+a,m=l+o/2,g=h+a/2;0===i.alignment&&n.save(),n.beginPath(),n.moveTo(l,g),n.bezierCurveTo(l,g-d,m-c,h,m,h),n.bezierCurveTo(m+c,h,p,g-d,p,g),n.bezierCurveTo(p,g+d,m+c,f,m,f),n.bezierCurveTo(m-c,f,l,g+d,l,g),n.closePath(),0===i.alignment&&n.clip(),e.visible&&(n.globalAlpha=e.alpha*r,n.fillStyle=s,n.fill()),0===i.alignment&&n.restore()}paintRoundedRectangle(t,e,i,s,r,n){const o=t.x,a=t.y,l=t.width,h=t.height;let u=t.radius;const c=Math.min(l,h)/2;u=u>c?c:u,0===i.alignment&&n.save(),n.beginPath(),n.moveTo(o,a+u),n.lineTo(o,a+h-u),n.quadraticCurveTo(o,a+h,o+u,a+h),n.lineTo(o+l-u,a+h),n.quadraticCurveTo(o+l,a+h,o+l,a+h-u),n.lineTo(o+l,a+u),n.quadraticCurveTo(o+l,a,o+l-u,a),n.lineTo(o+u,a),n.quadraticCurveTo(o,a,o,a+u),n.closePath(),0===i.alignment&&n.clip(),e.visible&&(n.globalAlpha=e.alpha*r,n.fillStyle=s,n.fill()),0===i.alignment&&n.restore()}setPatternTransform(t,e){if(!1!==this._svgMatrix){if(!this._svgMatrix){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");if(e?.createSVGMatrix&&(this._svgMatrix=e.createSVGMatrix()),!this._svgMatrix||!t.setTransform)return void(this._svgMatrix=!1)}this._svgMatrix.a=e.a,this._svgMatrix.b=e.b,this._svgMatrix.c=e.c,this._svgMatrix.d=e.d,this._svgMatrix.e=e.tx,this._svgMatrix.f=e.ty,t.setTransform(this._svgMatrix.inverse())}}destroy(){this.renderer=null,this._svgMatrix=null,this._tempMatrix=null}}wv.extension={name:"graphics",type:Up.CanvasRendererPlugin},Wp.add(wv);class _v{constructor(t){this.maxItemsPerFrame=t,this.itemsLeft=0}beginFrame(){this.itemsLeft=this.maxItemsPerFrame}allowedToUpload(){return this.itemsLeft-- >0}}function Pv(t,e){let i=!1;if(t?._textures?.length)for(let s=0;s<t._textures.length;s++)if(t._textures[s]instanceof Em){const r=t._textures[s].baseTexture;e.includes(r)||(e.push(r),i=!0)}return i}function Ev(t,e){if(t.baseTexture instanceof tf){const i=t.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function Tv(t,e){if(t._texture&&t._texture instanceof Em){const i=t._texture.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function Av(t,e){return e instanceof Fy&&(e.updateText(!0),!0)}function Iv(t,e){if(e instanceof Ny){const t=e.toFontString();return Cy.measureFont(t),!0}return!1}function Sv(t,e){if(t instanceof Fy){e.includes(t.style)||e.push(t.style),e.includes(t)||e.push(t);const i=t._texture.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function Cv(t,e){return t instanceof Ny&&(e.includes(t)||e.push(t),!0)}const Mv=class t{constructor(e){this.limiter=new _v(t.uploadsPerFrame),this.renderer=e,this.uploadHookHelper=null,this.queue=[],this.addHooks=[],this.uploadHooks=[],this.completes=[],this.ticking=!1,this.delayedTick=()=>{this.queue&&this.prepareItems()},this.registerFindHook(Sv),this.registerFindHook(Cv),this.registerFindHook(Pv),this.registerFindHook(Ev),this.registerFindHook(Tv),this.registerUploadHook(Av),this.registerUploadHook(Iv)}upload(t){return new Promise(e=>{t&&this.add(t),this.queue.length?(this.completes.push(e),this.ticking||(this.ticking=!0,Tg.system.addOnce(this.tick,this,_g.UTILITY))):e()})}tick(){setTimeout(this.delayedTick,0)}prepareItems(){for(this.limiter.beginFrame();this.queue.length&&this.limiter.allowedToUpload();){const t=this.queue[0];let e=!1;if(t&&!t._destroyed)for(let i=0,s=this.uploadHooks.length;i<s;i++)if(this.uploadHooks[i](this.uploadHookHelper,t)){this.queue.shift(),e=!0;break}e||this.queue.shift()}if(this.queue.length)Tg.system.addOnce(this.tick,this,_g.UTILITY);else{this.ticking=!1;const t=this.completes.slice(0);this.completes.length=0;for(let e=0,i=t.length;e<i;e++)t[e]()}}registerFindHook(t){return t&&this.addHooks.push(t),this}registerUploadHook(t){return t&&this.uploadHooks.push(t),this}add(t){for(let e=0,i=this.addHooks.length;e<i&&!this.addHooks[e](t,this.queue);e++);if(t instanceof qg)for(let e=t.children.length-1;e>=0;e--)this.add(t.children[e]);return this}destroy(){this.ticking&&Tg.system.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null}};Mv.uploadsPerFrame=4;let Ov=Mv;function Nv(t,e){return e instanceof tf&&(e._glTextures[t.CONTEXT_UID]||t.texture.bind(e),!0)}function Lv(t,e){if(!(e instanceof Ty))return!1;const{geometry:i}=e;e.finishPoly(),i.updateBatches();const{batches:s}=i;for(let r=0;r<s.length;r++){const{texture:e}=s[r].style;e&&Nv(t,e.baseTexture)}return i.batchable||t.geometry.bind(i,e._resolveDirectShader(t)),!0}function Rv(t,e){return t instanceof Ty&&(e.push(t),!0)}Object.defineProperties(Oh,{UPLOADS_PER_FRAME:{get:()=>Ov.uploadsPerFrame,set(t){Md("7.1.0","settings.UPLOADS_PER_FRAME is deprecated, use prepare.BasePrepare.uploadsPerFrame"),Ov.uploadsPerFrame=t}}});class Bv extends Ov{constructor(t){super(t),this.uploadHookHelper=this.renderer,this.registerFindHook(Rv),this.registerUploadHook(Nv),this.registerUploadHook(Lv)}}Bv.extension={name:"prepare",type:Up.RendererSystem},Wp.add(Bv);function kv(t,e){const i=t;if(e instanceof tf){const t=e.source,s=0===t.width?i.canvas.width:Math.min(i.canvas.width,t.width),r=0===t.height?i.canvas.height:Math.min(i.canvas.height,t.height);return i.ctx.drawImage(t,0,0,s,r,0,0,i.canvas.width,i.canvas.height),!0}return!1}class Fv extends Ov{constructor(t){super(t),this.uploadHookHelper=this,this.canvas=Oh.ADAPTER.createCanvas(16,16),this.ctx=this.canvas.getContext("2d"),this.registerUploadHook(kv)}destroy(){super.destroy(),this.ctx=null,this.canvas=null}}Fv.extension={name:"prepare",type:Up.CanvasRendererSystem},Wp.add(Fv),Zg.prototype._tintedCanvas=null,Zg.prototype._renderCanvas=function(t){t.plugins.sprite.render(this)};const Dv=new Pf;class Uv{constructor(t){this.renderer=t}render(t){const e=t._texture,i=this.renderer,s=i.canvasContext.activeContext,r=i.canvasContext.activeResolution;if(!e.valid)return;const n=e._frame.width,o=e._frame.height;let a=e._frame.width,l=e._frame.height;e.trim&&(a=e.trim.width,l=e.trim.height);let h=t.transform.worldTransform,u=0,c=0;const d=e.baseTexture.getDrawableSource();if(e.orig.width<=0||e.orig.height<=0||!e.valid||!d)return;i.canvasContext.setBlendMode(t.blendMode,!0),s.globalAlpha=t.worldAlpha;const p=e.baseTexture.scaleMode===wh.LINEAR,f=i.canvasContext.smoothProperty;f&&s[f]!==p&&(s[f]=p),e.trim?(u=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,c=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(u=(.5-t.anchor.x)*e.orig.width,c=(.5-t.anchor.y)*e.orig.height),e.rotate&&(h.copyTo(Dv),h=Dv,Of.matrixAppendRotationInv(h,e.rotate,u,c),u=0,c=0),u-=a/2,c-=l/2,i.canvasContext.setContextTransform(h,t.roundPixels,1),t.roundPixels&&(u|=0,c|=0);const m=e.baseTexture.resolution,g=i.canvasContext._outerBlend;g&&(s.save(),s.beginPath(),s.rect(u*r,c*r,a*r,l*r),s.clip()),16777215!==t.tint?((t._cachedTint!==t.tintValue||t._tintedCanvas.tintId!==t._texture._updateID)&&(t._cachedTint=t.tintValue,t._tintedCanvas=yv.getTintedCanvas(t,t.tintValue)),s.drawImage(t._tintedCanvas,0,0,Math.floor(n*m),Math.floor(o*m),Math.floor(u*r),Math.floor(c*r),Math.floor(a*r),Math.floor(l*r))):s.drawImage(d,e._frame.x*m,e._frame.y*m,Math.floor(n*m),Math.floor(o*m),Math.floor(u*r),Math.floor(c*r),Math.floor(a*r),Math.floor(l*r)),g&&s.restore(),i.canvasContext.setBlendMode(mh.NORMAL)}destroy(){this.renderer=null}}Uv.extension={name:"sprite",type:Up.CanvasRendererPlugin},Wp.add(Uv);var Gv=Object.defineProperty,Xv=(t,e,i)=>(((t,e,i)=>{e in t?Gv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i})(t,"symbol"!=typeof e?e+"":e,i),i);let Wv=class{constructor(t){Xv(this,"parent"),Xv(this,"paused"),this.parent=t,this.paused=!1}destroy(){}down(t){return!1}move(t){return!1}up(t){return!1}wheel(t){return!1}update(t){}resize(){}reset(){}pause(){this.paused=!0}resume(){this.paused=!1}};var Yv,Hv=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$v={exports:{}};Yv=$v,function(){var t,e;e=t={linear:function(t,e,i,s){return i*t/s+e},easeInQuad:function(t,e,i,s){return i*(t/=s)*t+e},easeOutQuad:function(t,e,i,s){return-i*(t/=s)*(t-2)+e},easeInOutQuad:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,s){return i*(t/=s)*t*t+e},easeOutCubic:function(t,e,i,s){return i*((t=t/s-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,s){return i*(t/=s)*t*t*t+e},easeOutQuart:function(t,e,i,s){return-i*((t=t/s-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,s){return i*(t/=s)*t*t*t*t+e},easeOutQuint:function(t,e,i,s){return i*((t=t/s-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,s){return-i*Math.cos(t/s*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,s){return i*Math.sin(t/s*(Math.PI/2))+e},easeInOutSine:function(t,e,i,s){return-i/2*(Math.cos(Math.PI*t/s)-1)+e},easeInExpo:function(t,e,i,s){return 0===t?e:i*Math.pow(2,10*(t/s-1))+e},easeOutExpo:function(t,e,i,s){return t===s?e+i:i*(1-Math.pow(2,-10*t/s))+e},easeInOutExpo:function(t,e,i,s){return(t/=s/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,s){return-i*(Math.sqrt(1-(t/=s)*t)-1)+e},easeOutCirc:function(t,e,i,s){return i*Math.sqrt(1-(t=t/s-1)*t)+e},easeInOutCirc:function(t,e,i,s){return(t/=s/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),-r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)+e},easeOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),r*Math.pow(2,-10*t)*Math.sin((t*s-o)*(2*Math.PI)/n)+i+e},easeInOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s/2),(n=0)||(n=s*(.3*1.5)),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),t<1?r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*-.5+e:r*Math.pow(2,-10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*.5+i+e},easeInBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*(t/=s)*t*((r+1)*t-r)+e},easeOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*((t=t/s-1)*t*((r+1)*t+r)+1)+e},easeInOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),(t/=s/2)<1?i/2*(t*t*((1+(r*=1.525))*t-r))+e:i/2*((t-=2)*t*((1+(r*=1.525))*t+r)+2)+e},easeInBounce:function(e,i,s,r){return s-t.easeOutBounce(r-e,0,s,r)+i},easeOutBounce:function(t,e,i,s){return(t/=s)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e},easeInOutBounce:function(e,i,s,r){return e<r/2?.5*t.easeInBounce(2*e,0,s,r)+i:.5*t.easeOutBounce(2*e-r,0,s,r)+.5*s+i}},Yv.exports=e}.call(Hv);const jv=$v.exports;function zv(t,e){return t?"function"==typeof t?t:"string"==typeof t?jv[t]:void 0:jv[e]}const Vv={removeOnInterrupt:!1,ease:"linear",time:1e3};let qv=class extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"startX"),Xv(this,"startY"),Xv(this,"deltaX"),Xv(this,"deltaY"),Xv(this,"keepCenter"),Xv(this,"startWidth",null),Xv(this,"startHeight",null),Xv(this,"deltaWidth",null),Xv(this,"deltaHeight",null),Xv(this,"width",null),Xv(this,"height",null),Xv(this,"time",0),this.options=Object.assign({},Vv,e),this.options.ease=zv(this.options.ease),this.setupPosition(),this.setupZoom(),this.time=0}setupPosition(){typeof this.options.position<"u"?(this.startX=this.parent.center.x,this.startY=this.parent.center.y,this.deltaX=this.options.position.x-this.parent.center.x,this.deltaY=this.options.position.y-this.parent.center.y,this.keepCenter=!1):this.keepCenter=!0}setupZoom(){this.width=null,this.height=null,typeof this.options.scale<"u"?this.width=this.parent.screenWidth/this.options.scale:typeof this.options.scaleX<"u"||typeof this.options.scaleY<"u"?(typeof this.options.scaleX<"u"&&(this.width=this.parent.screenWidth/this.options.scaleX),typeof this.options.scaleY<"u"&&(this.height=this.parent.screenHeight/this.options.scaleY)):(typeof this.options.width<"u"&&(this.width=this.options.width),typeof this.options.height<"u"&&(this.height=this.options.height)),null!==this.width&&(this.startWidth=this.parent.screenWidthInWorldPixels,this.deltaWidth=this.width-this.startWidth),null!==this.height&&(this.startHeight=this.parent.screenHeightInWorldPixels,this.deltaHeight=this.height-this.startHeight)}down(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("animate"),!1}complete(){this.parent.plugins.remove("animate"),null!==this.width&&this.parent.fitWidth(this.width,this.keepCenter,null===this.height),null!==this.height&&this.parent.fitHeight(this.height,this.keepCenter,null===this.width),!this.keepCenter&&this.options.position&&this.parent.moveCenter(this.options.position),this.parent.emit("animate-end",this.parent),this.options.callbackOnComplete&&this.options.callbackOnComplete(this.parent)}update(t){if(this.paused)return;this.time+=t;const e=new gf(this.parent.scale.x,this.parent.scale.y);if(this.time>=this.options.time){const t=this.parent.width,i=this.parent.height;this.complete(),(t!==this.parent.width||i!==this.parent.height)&&this.parent.emit("zoomed",{viewport:this.parent,original:e,type:"animate"})}else{const t=this.options.ease(this.time,0,1,this.options.time);if(null!==this.width){const e=this.startWidth,i=this.deltaWidth;this.parent.fitWidth(e+i*t,this.keepCenter,null===this.height)}if(null!==this.height){const e=this.startHeight,i=this.deltaHeight;this.parent.fitHeight(e+i*t,this.keepCenter,null===this.width)}if(null===this.width?this.parent.scale.x=this.parent.scale.y:null===this.height&&(this.parent.scale.y=this.parent.scale.x),!this.keepCenter){const e=this.startX,i=this.startY,s=this.deltaX,r=this.deltaY,n=new gf(this.parent.x,this.parent.y);this.parent.moveCenter(e+s*t,i+r*t),this.parent.emit("moved",{viewport:this.parent,original:n,type:"animate"})}(this.width||this.height)&&this.parent.emit("zoomed",{viewport:this.parent,original:e,type:"animate"})}}};const Jv={sides:"all",friction:.5,time:150,ease:"easeInOutSine",underflow:"center",bounceBox:null};class Kv extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"left"),Xv(this,"top"),Xv(this,"right"),Xv(this,"bottom"),Xv(this,"underflowX"),Xv(this,"underflowY"),Xv(this,"ease"),Xv(this,"toX"),Xv(this,"toY"),this.options=Object.assign({},Jv,e),this.ease=zv(this.options.ease,"easeInOutSine"),this.options.sides?"all"===this.options.sides?this.top=this.bottom=this.left=this.right=!0:"horizontal"===this.options.sides?(this.right=this.left=!0,this.top=this.bottom=!1):"vertical"===this.options.sides?(this.left=this.right=!1,this.top=this.bottom=!0):(this.top=-1!==this.options.sides.indexOf("top"),this.bottom=-1!==this.options.sides.indexOf("bottom"),this.left=-1!==this.options.sides.indexOf("left"),this.right=-1!==this.options.sides.indexOf("right")):this.left=this.top=this.right=this.bottom=!1;const i=this.options.underflow.toLowerCase();"center"===i?(this.underflowX=0,this.underflowY=0):(this.underflowX=-1!==i.indexOf("left")?-1:-1!==i.indexOf("right")?1:0,this.underflowY=-1!==i.indexOf("top")?-1:-1!==i.indexOf("bottom")?1:0),this.reset()}isActive(){return null!==this.toX||null!==this.toY}down(){return this.toX=this.toY=null,!1}up(){return this.bounce(),!1}update(t){if(!this.paused){if(this.bounce(),this.toX){const e=this.toX;e.time+=t,this.parent.emit("moved",{viewport:this.parent,type:"bounce-x"}),e.time>=this.options.time?(this.parent.x=e.end,this.toX=null,this.parent.emit("bounce-x-end",this.parent)):this.parent.x=this.ease(e.time,e.start,e.delta,this.options.time)}if(this.toY){const e=this.toY;e.time+=t,this.parent.emit("moved",{viewport:this.parent,type:"bounce-y"}),e.time>=this.options.time?(this.parent.y=e.end,this.toY=null,this.parent.emit("bounce-y-end",this.parent)):this.parent.y=this.ease(e.time,e.start,e.delta,this.options.time)}}}calcUnderflowX(){let t;switch(this.underflowX){case-1:t=0;break;case 1:t=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:t=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}return t}calcUnderflowY(){let t;switch(this.underflowY){case-1:t=0;break;case 1:t=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:t=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}return t}oob(){const t=this.options.bounceBox;if(t){const e=typeof t.x>"u"?0:t.x,i=typeof t.y>"u"?0:t.y,s=typeof t.width>"u"?this.parent.worldWidth:t.width,r=typeof t.height>"u"?this.parent.worldHeight:t.height;return{left:this.parent.left<e,right:this.parent.right>s,top:this.parent.top<i,bottom:this.parent.bottom>r,topLeft:new gf(e*this.parent.scale.x,i*this.parent.scale.y),bottomRight:new gf(s*this.parent.scale.x-this.parent.screenWidth,r*this.parent.scale.y-this.parent.screenHeight)}}return{left:this.parent.left<0,right:this.parent.right>this.parent.worldWidth,top:this.parent.top<0,bottom:this.parent.bottom>this.parent.worldHeight,topLeft:new gf(0,0),bottomRight:new gf(this.parent.worldWidth*this.parent.scale.x-this.parent.screenWidth,this.parent.worldHeight*this.parent.scale.y-this.parent.screenHeight)}}bounce(){var t,e;if(this.paused)return;let i,s=this.parent.plugins.get("decelerate",!0);s&&(s.x||s.y)&&(s.x&&s.percentChangeX===(null==(t=s.options)?void 0:t.friction)||s.y&&s.percentChangeY===(null==(e=s.options)?void 0:e.friction))&&(i=this.oob(),(i.left&&this.left||i.right&&this.right)&&(s.percentChangeX=this.options.friction),(i.top&&this.top||i.bottom&&this.bottom)&&(s.percentChangeY=this.options.friction));const r=this.parent.plugins.get("drag",!0)||{},n=this.parent.plugins.get("pinch",!0)||{};if(s=s||{},!(null!=r&&r.active||null!=n&&n.active||this.toX&&this.toY||s.x&&s.y)){i=i||this.oob();const t=i.topLeft,e=i.bottomRight;if(!this.toX&&!s.x){let s=null;i.left&&this.left?s=this.parent.screenWorldWidth<this.parent.screenWidth?this.calcUnderflowX():-t.x:i.right&&this.right&&(s=this.parent.screenWorldWidth<this.parent.screenWidth?this.calcUnderflowX():-e.x),null!==s&&this.parent.x!==s&&(this.toX={time:0,start:this.parent.x,delta:s-this.parent.x,end:s},this.parent.emit("bounce-x-start",this.parent))}if(!this.toY&&!s.y){let s=null;i.top&&this.top?s=this.parent.screenWorldHeight<this.parent.screenHeight?this.calcUnderflowY():-t.y:i.bottom&&this.bottom&&(s=this.parent.screenWorldHeight<this.parent.screenHeight?this.calcUnderflowY():-e.y),null!==s&&this.parent.y!==s&&(this.toY={time:0,start:this.parent.y,delta:s-this.parent.y,end:s},this.parent.emit("bounce-y-start",this.parent))}}}reset(){this.toX=this.toY=null,this.bounce()}}const Zv={left:!1,right:!1,top:!1,bottom:!1,direction:null,underflow:"center"};class Qv extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"last"),Xv(this,"noUnderflow"),Xv(this,"underflowX"),Xv(this,"underflowY"),this.options=Object.assign({},Zv,e),this.options.direction&&(this.options.left="x"===this.options.direction||"all"===this.options.direction||null,this.options.right="x"===this.options.direction||"all"===this.options.direction||null,this.options.top="y"===this.options.direction||"all"===this.options.direction||null,this.options.bottom="y"===this.options.direction||"all"===this.options.direction||null),this.parseUnderflow(),this.last={x:null,y:null,scaleX:null,scaleY:null},this.update()}parseUnderflow(){const t=this.options.underflow.toLowerCase();"none"===t?this.noUnderflow=!0:"center"===t?(this.underflowX=this.underflowY=0,this.noUnderflow=!1):(this.underflowX=-1!==t.indexOf("left")?-1:-1!==t.indexOf("right")?1:0,this.underflowY=-1!==t.indexOf("top")?-1:-1!==t.indexOf("bottom")?1:0,this.noUnderflow=!1)}move(){return this.update(),!1}update(){if(this.paused||this.parent.x===this.last.x&&this.parent.y===this.last.y&&this.parent.scale.x===this.last.scaleX&&this.parent.scale.y===this.last.scaleY)return;const t=new gf(this.parent.x,this.parent.y),e=this.parent.plugins.decelerate||{};if(null!==this.options.left||null!==this.options.right){let i=!1;if(!this.noUnderflow&&this.parent.screenWorldWidth<this.parent.screenWidth)switch(this.underflowX){case-1:0!==this.parent.x&&(this.parent.x=0,i=!0);break;case 1:this.parent.x!==this.parent.screenWidth-this.parent.screenWorldWidth&&(this.parent.x=this.parent.screenWidth-this.parent.screenWorldWidth,i=!0);break;default:this.parent.x!==(this.parent.screenWidth-this.parent.screenWorldWidth)/2&&(this.parent.x=(this.parent.screenWidth-this.parent.screenWorldWidth)/2,i=!0)}else null!==this.options.left&&this.parent.left<(!0===this.options.left?0:this.options.left)&&(this.parent.x=-(!0===this.options.left?0:this.options.left)*this.parent.scale.x,e.x=0,i=!0),null!==this.options.right&&this.parent.right>(!0===this.options.right?this.parent.worldWidth:this.options.right)&&(this.parent.x=-(!0===this.options.right?this.parent.worldWidth:this.options.right)*this.parent.scale.x+this.parent.screenWidth,e.x=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-x"})}if(null!==this.options.top||null!==this.options.bottom){let i=!1;if(!this.noUnderflow&&this.parent.screenWorldHeight<this.parent.screenHeight)switch(this.underflowY){case-1:0!==this.parent.y&&(this.parent.y=0,i=!0);break;case 1:this.parent.y!==this.parent.screenHeight-this.parent.screenWorldHeight&&(this.parent.y=this.parent.screenHeight-this.parent.screenWorldHeight,i=!0);break;default:this.parent.y!==(this.parent.screenHeight-this.parent.screenWorldHeight)/2&&(this.parent.y=(this.parent.screenHeight-this.parent.screenWorldHeight)/2,i=!0)}else null!==this.options.top&&this.parent.top<(!0===this.options.top?0:this.options.top)&&(this.parent.y=-(!0===this.options.top?0:this.options.top)*this.parent.scale.y,e.y=0,i=!0),null!==this.options.bottom&&this.parent.bottom>(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)&&(this.parent.y=-(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)*this.parent.scale.y+this.parent.screenHeight,e.y=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-y"})}this.last.x=this.parent.x,this.last.y=this.parent.y,this.last.scaleX=this.parent.scale.x,this.last.scaleY=this.parent.scale.y}reset(){this.update()}}const tx={minWidth:null,minHeight:null,maxWidth:null,maxHeight:null,minScale:null,maxScale:null};class ex extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),this.options=Object.assign({},tx,e),this.clamp()}resize(){this.clamp()}clamp(){if(!this.paused)if(this.options.minWidth||this.options.minHeight||this.options.maxWidth||this.options.maxHeight){let t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight;if(null!==this.options.minWidth&&t<this.options.minWidth){const i=this.parent.scale.x;this.parent.fitWidth(this.options.minWidth,!1,!1,!0),this.parent.scale.y*=this.parent.scale.x/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.maxWidth&&t>this.options.maxWidth){const i=this.parent.scale.x;this.parent.fitWidth(this.options.maxWidth,!1,!1,!0),this.parent.scale.y*=this.parent.scale.x/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.minHeight&&e<this.options.minHeight){const i=this.parent.scale.y;this.parent.fitHeight(this.options.minHeight,!1,!1,!0),this.parent.scale.x*=this.parent.scale.y/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.maxHeight&&e>this.options.maxHeight){const t=this.parent.scale.y;this.parent.fitHeight(this.options.maxHeight,!1,!1,!0),this.parent.scale.x*=this.parent.scale.y/t,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}}else if(this.options.minScale||this.options.maxScale){const t={x:null,y:null},e={x:null,y:null};if("number"==typeof this.options.minScale)t.x=this.options.minScale,t.y=this.options.minScale;else if(null!==this.options.minScale){const e=this.options.minScale;t.x=typeof e.x>"u"?null:e.x,t.y=typeof e.y>"u"?null:e.y}if("number"==typeof this.options.maxScale)e.x=this.options.maxScale,e.y=this.options.maxScale;else if(null!==this.options.maxScale){const t=this.options.maxScale;e.x=typeof t.x>"u"?null:t.x,e.y=typeof t.y>"u"?null:t.y}let i=this.parent.scale.x,s=this.parent.scale.y;null!==t.x&&i<t.x&&(i=t.x),null!==e.x&&i>e.x&&(i=e.x),null!==t.y&&s<t.y&&(s=t.y),null!==e.y&&s>e.y&&(s=e.y),(i!==this.parent.scale.x||s!==this.parent.scale.y)&&(this.parent.scale.set(i,s),this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"}))}}reset(){this.clamp()}}const ix={friction:.98,bounce:.8,minSpeed:.01},sx=16;class rx extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"x"),Xv(this,"y"),Xv(this,"percentChangeX"),Xv(this,"percentChangeY"),Xv(this,"saved"),Xv(this,"timeSinceRelease"),this.options=Object.assign({},ix,e),this.saved=[],this.timeSinceRelease=0,this.reset(),this.parent.on("moved",t=>this.handleMoved(t))}down(){return this.saved=[],this.x=this.y=null,!1}isActive(){return!(!this.x&&!this.y)}move(){if(this.paused)return!1;const t=this.parent.input.count();return(1===t||t>1&&!this.parent.plugins.get("pinch",!0))&&(this.saved.push({x:this.parent.x,y:this.parent.y,time:performance.now()}),this.saved.length>60&&this.saved.splice(0,30)),!1}handleMoved(t){if(this.saved.length){const e=this.saved[this.saved.length-1];"clamp-x"===t.type&&t.original?e.x===t.original.x&&(e.x=this.parent.x):"clamp-y"===t.type&&t.original&&e.y===t.original.y&&(e.y=this.parent.y)}}up(){if(0===this.parent.input.count()&&this.saved.length){const t=performance.now();for(const e of this.saved)if(e.time>=t-100){const i=t-e.time;this.x=(this.parent.x-e.x)/i,this.y=(this.parent.y-e.y)/i,this.percentChangeX=this.percentChangeY=this.options.friction,this.timeSinceRelease=0;break}}return!1}activate(t){typeof(t=t||{}).x<"u"&&(this.x=t.x,this.percentChangeX=this.options.friction),typeof t.y<"u"&&(this.y=t.y,this.percentChangeY=this.options.friction)}update(t){if(this.paused)return;const e=this.x||this.y,i=this.timeSinceRelease,s=this.timeSinceRelease+t;if(this.x){const e=this.percentChangeX,r=Math.log(e);this.parent.x+=this.x*sx/r*(Math.pow(e,s/sx)-Math.pow(e,i/sx)),this.x*=Math.pow(this.percentChangeX,t/sx)}if(this.y){const e=this.percentChangeY,r=Math.log(e);this.parent.y+=this.y*sx/r*(Math.pow(e,s/sx)-Math.pow(e,i/sx)),this.y*=Math.pow(this.percentChangeY,t/sx)}this.timeSinceRelease+=t,this.x&&this.y?Math.abs(this.x)<this.options.minSpeed&&Math.abs(this.y)<this.options.minSpeed&&(this.x=0,this.y=0):(Math.abs(this.x||0)<this.options.minSpeed&&(this.x=0),Math.abs(this.y||0)<this.options.minSpeed&&(this.y=0)),e&&this.parent.emit("moved",{viewport:this.parent,type:"decelerate"})}reset(){this.x=this.y=null}}const nx={direction:"all",pressDrag:!0,wheel:!0,wheelScroll:1,reverse:!1,clampWheel:!1,underflow:"center",factor:1,mouseButtons:"all",keyToPress:null,ignoreKeyToPressOnTouch:!1,lineHeight:20,wheelSwapAxes:!1};class ox extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"moved"),Xv(this,"reverse"),Xv(this,"xDirection"),Xv(this,"yDirection"),Xv(this,"keyIsPressed"),Xv(this,"mouse"),Xv(this,"underflowX"),Xv(this,"underflowY"),Xv(this,"last"),Xv(this,"current"),Xv(this,"windowEventHandlers",[]),this.options=Object.assign({},nx,e),this.moved=!1,this.reverse=this.options.reverse?1:-1,this.xDirection=!this.options.direction||"all"===this.options.direction||"x"===this.options.direction,this.yDirection=!this.options.direction||"all"===this.options.direction||"y"===this.options.direction,this.keyIsPressed=!1,this.parseUnderflow(),this.mouseButtons(this.options.mouseButtons),this.options.keyToPress&&this.handleKeyPresses(this.options.keyToPress)}handleKeyPresses(t){this.addWindowEventHandler("keyup",e=>{t.includes(e.code)&&(this.keyIsPressed=!1)}),this.addWindowEventHandler("keydown",e=>{t.includes(e.code)&&(this.keyIsPressed=!0)})}addWindowEventHandler(t,e){window.addEventListener(t,e),this.windowEventHandlers.push({event:t,handler:e})}destroy(){this.windowEventHandlers.forEach(({event:t,handler:e})=>{window.removeEventListener(t,e)})}mouseButtons(t){this.mouse=t&&"all"!==t?[-1!==t.indexOf("left"),-1!==t.indexOf("middle"),-1!==t.indexOf("right")]:[!0,!0,!0]}parseUnderflow(){const t=this.options.underflow.toLowerCase();"center"===t?(this.underflowX=0,this.underflowY=0):(t.includes("left")?this.underflowX=-1:t.includes("right")?this.underflowX=1:this.underflowX=0,t.includes("top")?this.underflowY=-1:t.includes("bottom")?this.underflowY=1:this.underflowY=0)}checkButtons(t){const e="mouse"===t.pointerType,i=this.parent.input.count();return!(!(1===i||i>1&&!this.parent.plugins.get("pinch",!0))||e&&!this.mouse[t.button])}checkKeyPress(t){return!this.options.keyToPress||this.keyIsPressed||this.options.ignoreKeyToPressOnTouch&&"touch"===t.data.pointerType}down(t){return!(this.paused||!this.options.pressDrag)&&(this.checkButtons(t)&&this.checkKeyPress(t)?(this.last={x:t.global.x,y:t.global.y},this.current=t.pointerId,!0):(this.last=null,!1))}get active(){return this.moved}move(t){if(this.paused||!this.options.pressDrag)return!1;if(this.last&&this.current===t.data.pointerId){const e=t.global.x,i=t.global.y,s=this.parent.input.count();if(1===s||s>1&&!this.parent.plugins.get("pinch",!0)){const s=e-this.last.x,r=i-this.last.y;if(this.moved||this.xDirection&&this.parent.input.checkThreshold(s)||this.yDirection&&this.parent.input.checkThreshold(r)){const s={x:e,y:i};return this.xDirection&&(this.parent.x+=(s.x-this.last.x)*this.options.factor),this.yDirection&&(this.parent.y+=(s.y-this.last.y)*this.options.factor),this.last=s,this.moved||this.parent.emit("drag-start",{event:t,screen:new gf(this.last.x,this.last.y),world:this.parent.toWorld(new gf(this.last.x,this.last.y)),viewport:this.parent}),this.moved=!0,this.parent.emit("moved",{viewport:this.parent,type:"drag"}),!0}}else this.moved=!1}return!1}up(t){if(this.paused)return!1;const e=this.parent.input.touches;if(1===e.length){const t=e[0];return t.last&&(this.last={x:t.last.x,y:t.last.y},this.current=t.id),this.moved=!1,!0}if(this.last&&this.moved){const e=new gf(this.last.x,this.last.y);return this.parent.emit("drag-end",{event:t,screen:e,world:this.parent.toWorld(e),viewport:this.parent}),this.last=null,this.moved=!1,!0}return!1}wheel(t){if(this.paused)return!1;if(this.options.wheel){const e=this.parent.plugins.get("wheel",!0);if(!e||!e.options.wheelZoom&&!t.ctrlKey){const e=t.deltaMode?this.options.lineHeight:1,i=[t.deltaX,t.deltaY],[s,r]=this.options.wheelSwapAxes?i.reverse():i;return this.xDirection&&(this.parent.x+=s*e*this.options.wheelScroll*this.reverse),this.yDirection&&(this.parent.y+=r*e*this.options.wheelScroll*this.reverse),this.options.clampWheel&&this.clamp(),this.parent.emit("wheel-scroll",this.parent),this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.options.passiveWheel||t.preventDefault(),this.parent.options.stopPropagation&&t.stopPropagation(),!0}}return!1}resume(){this.last=null,this.paused=!1}clamp(){const t=this.parent.plugins.get("decelerate",!0)||{};if("y"!==this.options.clampWheel)if(this.parent.screenWorldWidth<this.parent.screenWidth)switch(this.underflowX){case-1:this.parent.x=0;break;case 1:this.parent.x=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:this.parent.x=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}else this.parent.left<0?(this.parent.x=0,t.x=0):this.parent.right>this.parent.worldWidth&&(this.parent.x=-this.parent.worldWidth*this.parent.scale.x+this.parent.screenWidth,t.x=0);if("x"!==this.options.clampWheel)if(this.parent.screenWorldHeight<this.parent.screenHeight)switch(this.underflowY){case-1:this.parent.y=0;break;case 1:this.parent.y=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:this.parent.y=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}else this.parent.top<0&&(this.parent.y=0,t.y=0),this.parent.bottom>this.parent.worldHeight&&(this.parent.y=-this.parent.worldHeight*this.parent.scale.y+this.parent.screenHeight,t.y=0)}}const ax={speed:0,acceleration:null,radius:null};class lx extends Wv{constructor(t,e,i={}){super(t),Xv(this,"options"),Xv(this,"target"),Xv(this,"velocity"),this.target=e,this.options=Object.assign({},ax,i),this.velocity={x:0,y:0}}update(t){if(this.paused)return;const e=this.parent.center;let i=this.target.x,s=this.target.y;if(this.options.radius){if(!(Math.sqrt(Math.pow(this.target.y-e.y,2)+Math.pow(this.target.x-e.x,2))>this.options.radius))return;{const t=Math.atan2(this.target.y-e.y,this.target.x-e.x);i=this.target.x-Math.cos(t)*this.options.radius,s=this.target.y-Math.sin(t)*this.options.radius}}const r=i-e.x,n=s-e.y;if(r||n)if(this.options.speed)if(this.options.acceleration){const t=Math.atan2(s-e.y,i-e.x),o=Math.sqrt(Math.pow(r,2)+Math.pow(n,2));if(o){const a=(Math.pow(this.velocity.x,2)+Math.pow(this.velocity.y,2))/(2*this.options.acceleration);this.velocity=o>a?{x:Math.min(this.velocity.x+(this.options.acceleration,this.options.speed)),y:Math.min(this.velocity.y+(this.options.acceleration,this.options.speed))}:{x:Math.max(this.velocity.x-this.options.acceleration*this.options.speed,0),y:Math.max(this.velocity.y-this.options.acceleration*this.options.speed,0)};const l=Math.cos(t)*this.velocity.x,h=Math.sin(t)*this.velocity.y,u=Math.abs(l)>Math.abs(r)?i:e.x+l,c=Math.abs(h)>Math.abs(n)?s:e.y+h;this.parent.moveCenter(u,c),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}else{const t=Math.atan2(s-e.y,i-e.x),o=Math.cos(t)*this.options.speed,a=Math.sin(t)*this.options.speed,l=Math.abs(o)>Math.abs(r)?i:e.x+o,h=Math.abs(a)>Math.abs(n)?s:e.y+a;this.parent.moveCenter(l,h),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}else this.parent.moveCenter(i,s),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}const hx={radius:null,distance:null,top:null,bottom:null,left:null,right:null,speed:8,reverse:!1,noDecelerate:!1,linear:!1,allowButtons:!1};let ux=class extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"reverse"),Xv(this,"radiusSquared"),Xv(this,"left"),Xv(this,"top"),Xv(this,"right"),Xv(this,"bottom"),Xv(this,"horizontal"),Xv(this,"vertical"),this.options=Object.assign({},hx,e),this.reverse=this.options.reverse?1:-1,this.radiusSquared="number"==typeof this.options.radius?Math.pow(this.options.radius,2):null,this.resize()}resize(){const t=this.options.distance;null!==t?(this.left=t,this.top=t,this.right=this.parent.screenWidth-t,this.bottom=this.parent.screenHeight-t):this.options.radius||(this.left=this.options.left,this.top=this.options.top,this.right=null===this.options.right?null:this.parent.screenWidth-this.options.right,this.bottom=null===this.options.bottom?null:this.parent.screenHeight-this.options.bottom)}down(){return this.paused||this.options.allowButtons||(this.horizontal=this.vertical=null),!1}move(t){if(this.paused||"mouse"!==t.pointerType&&1!==t.pointerId||!this.options.allowButtons&&0!==t.buttons)return!1;const e=t.global.x,i=t.global.y;if(this.radiusSquared){const t=this.parent.toScreen(this.parent.center);if(Math.pow(t.x-e,2)+Math.pow(t.y-i,2)>=this.radiusSquared){const s=Math.atan2(t.y-i,t.x-e);this.options.linear?(this.horizontal=Math.round(Math.cos(s))*this.options.speed*this.reverse*.06,this.vertical=Math.round(Math.sin(s))*this.options.speed*this.reverse*.06):(this.horizontal=Math.cos(s)*this.options.speed*this.reverse*.06,this.vertical=Math.sin(s)*this.options.speed*this.reverse*.06)}else this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=0}else null!==this.left&&e<this.left?this.horizontal=Number(this.reverse)*this.options.speed*.06:null!==this.right&&e>this.right?this.horizontal=-1*this.reverse*this.options.speed*.06:(this.decelerateHorizontal(),this.horizontal=0),null!==this.top&&i<this.top?this.vertical=Number(this.reverse)*this.options.speed*.06:null!==this.bottom&&i>this.bottom?this.vertical=-1*this.reverse*this.options.speed*.06:(this.decelerateVertical(),this.vertical=0);return!1}decelerateHorizontal(){const t=this.parent.plugins.get("decelerate",!0);this.horizontal&&t&&!this.options.noDecelerate&&t.activate({x:this.horizontal*this.options.speed*this.reverse/(1e3/60)})}decelerateVertical(){const t=this.parent.plugins.get("decelerate",!0);this.vertical&&t&&!this.options.noDecelerate&&t.activate({y:this.vertical*this.options.speed*this.reverse/(1e3/60)})}up(){return this.paused||(this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=null),!1}update(){if(!this.paused&&(this.horizontal||this.vertical)){const t=this.parent.center;this.horizontal&&(t.x+=this.horizontal*this.options.speed),this.vertical&&(t.y+=this.vertical*this.options.speed),this.parent.moveCenter(t),this.parent.emit("moved",{viewport:this.parent,type:"mouse-edges"})}}};const cx={noDrag:!1,percent:1,center:null,factor:1,axis:"all"};class dx extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"active",!1),Xv(this,"pinching",!1),Xv(this,"moved",!1),Xv(this,"lastCenter"),this.options=Object.assign({},cx,e)}down(){return this.parent.input.count()>=2&&(this.active=!0,!0)}isAxisX(){return["all","x"].includes(this.options.axis)}isAxisY(){return["all","y"].includes(this.options.axis)}move(t){if(this.paused||!this.active)return!1;const e=t.global.x,i=t.global.y,s=this.parent.input.touches;if(s.length>=2){const r=s[0],n=s[1],o=r.last&&n.last?Math.sqrt(Math.pow(n.last.x-r.last.x,2)+Math.pow(n.last.y-r.last.y,2)):null;if(r.id===t.pointerId?r.last={x:e,y:i,data:t}:n.id===t.pointerId&&(n.last={x:e,y:i,data:t}),o){let t;const e=new gf(r.last.x+(n.last.x-r.last.x)/2,r.last.y+(n.last.y-r.last.y)/2);this.options.center||(t=this.parent.toLocal(e));let i=Math.sqrt(Math.pow(n.last.x-r.last.x,2)+Math.pow(n.last.y-r.last.y,2));i=0===i?i=1e-10:i;const s=(1-o/i)*this.options.percent*(this.isAxisX()?this.parent.scale.x:this.parent.scale.y);this.isAxisX()&&(this.parent.scale.x+=s),this.isAxisY()&&(this.parent.scale.y+=s),this.parent.emit("zoomed",{viewport:this.parent,type:"pinch",center:e});const a=this.parent.plugins.get("clamp-zoom",!0);if(a&&a.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=(e.x-i.x)*this.options.factor,this.parent.y+=(e.y-i.y)*this.options.factor,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})}!this.options.noDrag&&this.lastCenter&&(this.parent.x+=(e.x-this.lastCenter.x)*this.options.factor,this.parent.y+=(e.y-this.lastCenter.y)*this.options.factor,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})),this.lastCenter=e,this.moved=!0}else this.pinching||(this.parent.emit("pinch-start",this.parent),this.pinching=!0);return!0}return!1}up(){return!!(this.pinching&&this.parent.input.touches.length<=1)&&(this.active=!1,this.lastCenter=null,this.pinching=!1,this.moved=!1,this.parent.emit("pinch-end",this.parent),!0)}}const px={topLeft:!1,friction:.8,time:1e3,ease:"easeInOutSine",interrupt:!0,removeOnComplete:!1,removeOnInterrupt:!1,forceStart:!1};class fx extends Wv{constructor(t,e,i,s={}){super(t),Xv(this,"options"),Xv(this,"ease"),Xv(this,"x"),Xv(this,"y"),Xv(this,"percent"),Xv(this,"snapping"),Xv(this,"deltaX"),Xv(this,"deltaY"),Xv(this,"startX"),Xv(this,"startY"),this.options=Object.assign({},px,s),this.ease=zv(s.ease,"easeInOutSine"),this.x=e,this.y=i,this.options.forceStart&&this.snapStart()}snapStart(){this.percent=0,this.snapping={time:0};const t=this.options.topLeft?this.parent.corner:this.parent.center;this.deltaX=this.x-t.x,this.deltaY=this.y-t.y,this.startX=t.x,this.startY=t.y,this.parent.emit("snap-start",this.parent)}wheel(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("snap"),!1}down(){return this.options.removeOnInterrupt?this.parent.plugins.remove("snap"):this.options.interrupt&&(this.snapping=null),!1}up(){if(0===this.parent.input.count()){const t=this.parent.plugins.get("decelerate",!0);t&&(t.x||t.y)&&(t.percentChangeX=t.percentChangeY=this.options.friction)}return!1}update(t){if(!(this.paused||this.options.interrupt&&0!==this.parent.input.count()))if(this.snapping){const e=this.snapping;let i,s,r;e.time+=t;const n=this.startX,o=this.startY,a=this.deltaX,l=this.deltaY;if(e.time>this.options.time)i=!0,s=n+a,r=o+l;else{const t=this.ease(e.time,0,1,this.options.time);s=n+a*t,r=o+l*t}this.options.topLeft?this.parent.moveCorner(s,r):this.parent.moveCenter(s,r),this.parent.emit("moved",{viewport:this.parent,type:"snap"}),i&&(this.options.removeOnComplete&&this.parent.plugins.remove("snap"),this.parent.emit("snap-end",this.parent),this.snapping=null)}else{const t=this.options.topLeft?this.parent.corner:this.parent.center;(t.x!==this.x||t.y!==this.y)&&this.snapStart()}}}const mx={width:0,height:0,time:1e3,ease:"easeInOutSine",center:null,interrupt:!0,removeOnComplete:!1,removeOnInterrupt:!1,forceStart:!1,noMove:!1};class gx extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"ease"),Xv(this,"xScale"),Xv(this,"yScale"),Xv(this,"xIndependent"),Xv(this,"yIndependent"),Xv(this,"snapping"),this.options=Object.assign({},mx,e),this.ease=zv(this.options.ease),this.xIndependent=!1,this.yIndependent=!1,this.xScale=0,this.yScale=0,this.options.width>0&&(this.xScale=t.screenWidth/this.options.width,this.xIndependent=!0),this.options.height>0&&(this.yScale=t.screenHeight/this.options.height,this.yIndependent=!0),this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale,0===this.options.time?(t.container.scale.x=this.xScale,t.container.scale.y=this.yScale,this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom")):e.forceStart&&this.createSnapping()}createSnapping(){const t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,i=this.parent.screenWidth/this.xScale,s=this.parent.screenHeight/this.yScale;this.snapping={time:0,startX:t,startY:e,deltaX:i-t,deltaY:s-e},this.parent.emit("snap-zoom-start",this.parent)}resize(){this.snapping=null,this.options.width>0&&(this.xScale=this.parent.screenWidth/this.options.width),this.options.height>0&&(this.yScale=this.parent.screenHeight/this.options.height),this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale}wheel(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("snap-zoom"),!1}down(){return this.options.removeOnInterrupt?this.parent.plugins.remove("snap-zoom"):this.options.interrupt&&(this.snapping=null),!1}update(t){if(this.paused||this.options.interrupt&&0!==this.parent.input.count())return;let e;if(!this.options.center&&!this.options.noMove&&(e=this.parent.center),this.snapping){if(this.snapping){const i=this.snapping;if(i.time+=t,i.time>=this.options.time)this.parent.scale.set(this.xScale,this.yScale),this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom"),this.parent.emit("snap-zoom-end",this.parent),this.snapping=null;else{const t=this.snapping,e=this.ease(t.time,t.startX,t.deltaX,this.options.time),i=this.ease(t.time,t.startY,t.deltaY,this.options.time);this.parent.scale.x=this.parent.screenWidth/e,this.parent.scale.y=this.parent.screenHeight/i}const s=this.parent.plugins.get("clamp-zoom",!0);s&&s.clamp(),this.options.noMove||(this.options.center?this.parent.moveCenter(this.options.center):this.parent.moveCenter(e))}}else(this.parent.scale.x!==this.xScale||this.parent.scale.y!==this.yScale)&&this.createSnapping()}resume(){this.snapping=null,super.resume()}}const yx={percent:.1,smooth:!1,interrupt:!0,reverse:!1,center:null,lineHeight:20,axis:"all",keyToPress:null,trackpadPinch:!1,wheelZoom:!0};class vx extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"smoothing"),Xv(this,"smoothingCenter"),Xv(this,"smoothingCount"),Xv(this,"keyIsPressed"),this.options=Object.assign({},yx,e),this.keyIsPressed=!1,this.options.keyToPress&&this.handleKeyPresses(this.options.keyToPress)}handleKeyPresses(t){window.addEventListener("keydown",e=>{t.includes(e.code)&&(this.keyIsPressed=!0)}),window.addEventListener("keyup",e=>{t.includes(e.code)&&(this.keyIsPressed=!1)})}checkKeyPress(){return!this.options.keyToPress||this.keyIsPressed}down(){return this.options.interrupt&&(this.smoothing=null),!1}isAxisX(){return["all","x"].includes(this.options.axis)}isAxisY(){return["all","y"].includes(this.options.axis)}update(){if(this.smoothing){const t=this.smoothingCenter,e=this.smoothing;let i;this.options.center||(i=this.parent.toLocal(t)),this.isAxisX()&&(this.parent.scale.x+=e.x),this.isAxisY()&&(this.parent.scale.y+=e.y),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const s=this.parent.plugins.get("clamp-zoom",!0);if(s&&s.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const e=this.parent.toGlobal(i);this.parent.x+=t.x-e.x,this.parent.y+=t.y-e.y}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.smoothingCount++,this.smoothingCount>=this.options.smooth&&(this.smoothing=null)}}pinch(t){if(this.paused)return;const e=this.parent.input.getPointerPosition(t),i=-t.deltaY*(t.deltaMode?this.options.lineHeight:1)/200,s=Math.pow(2,(1+this.options.percent)*i);let r;this.options.center||(r=this.parent.toLocal(e)),this.isAxisX()&&(this.parent.scale.x*=s),this.isAxisY()&&(this.parent.scale.y*=s),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const n=this.parent.plugins.get("clamp-zoom",!0);if(n&&n.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const t=this.parent.toGlobal(r);this.parent.x+=e.x-t.x,this.parent.y+=e.y-t.y}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.emit("wheel-start",{event:t,viewport:this.parent})}wheel(t){if(this.paused||!this.checkKeyPress())return!1;if(t.ctrlKey&&this.options.trackpadPinch)this.pinch(t);else if(this.options.wheelZoom){const e=this.parent.input.getPointerPosition(t),i=(this.options.reverse?-1:1)*-t.deltaY*(t.deltaMode?this.options.lineHeight:1)/500,s=Math.pow(2,(1+this.options.percent)*i);if(this.options.smooth){const t={x:this.smoothing?this.smoothing.x*(this.options.smooth-this.smoothingCount):0,y:this.smoothing?this.smoothing.y*(this.options.smooth-this.smoothingCount):0};this.smoothing={x:((this.parent.scale.x+t.x)*s-this.parent.scale.x)/this.options.smooth,y:((this.parent.scale.y+t.y)*s-this.parent.scale.y)/this.options.smooth},this.smoothingCount=0,this.smoothingCenter=e}else{let t;this.options.center||(t=this.parent.toLocal(e)),this.isAxisX()&&(this.parent.scale.x*=s),this.isAxisY()&&(this.parent.scale.y*=s),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const i=this.parent.plugins.get("clamp-zoom",!0);if(i&&i.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=e.x-i.x,this.parent.y+=e.y-i.y}}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.emit("wheel-start",{event:t,viewport:this.parent})}return!this.parent.options.passiveWheel}}let xx=class{constructor(t){Xv(this,"viewport"),Xv(this,"clickedAvailable"),Xv(this,"isMouseDown"),Xv(this,"last"),Xv(this,"wheelFunction"),Xv(this,"touches"),this.viewport=t,this.touches=[],this.addListeners()}addListeners(){this.viewport.eventMode="static",this.viewport.forceHitArea||(this.viewport.hitArea=new vf(0,0,this.viewport.worldWidth,this.viewport.worldHeight)),this.viewport.on("pointerdown",this.down,this),this.viewport.options.allowPreserveDragOutside?this.viewport.on("globalpointermove",this.move,this):this.viewport.on("pointermove",this.move,this),this.viewport.on("pointerup",this.up,this),this.viewport.on("pointerupoutside",this.up,this),this.viewport.on("pointercancel",this.up,this),this.viewport.options.allowPreserveDragOutside||this.viewport.on("pointerleave",this.up,this),this.wheelFunction=t=>this.handleWheel(t),this.viewport.options.events.domElement.addEventListener("wheel",this.wheelFunction,{passive:this.viewport.options.passiveWheel}),this.isMouseDown=!1}destroy(){this.viewport.options.events.domElement.removeEventListener("wheel",this.wheelFunction)}down(t){if(!this.viewport.pause&&this.viewport.worldVisible){if("mouse"===t.pointerType?this.isMouseDown=!0:this.get(t.pointerId)||this.touches.push({id:t.pointerId,last:null}),1===this.count()){this.last=t.global.clone();const e=this.viewport.plugins.get("decelerate",!0),i=this.viewport.plugins.get("bounce",!0);e&&e.isActive()||i&&i.isActive()?this.clickedAvailable=!1:this.clickedAvailable=!0}else this.clickedAvailable=!1;this.viewport.plugins.down(t)&&this.viewport.options.stopPropagation&&t.stopPropagation()}}clear(){this.isMouseDown=!1,this.touches=[],this.last=null}checkThreshold(t){return Math.abs(t)>=this.viewport.threshold}move(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.plugins.move(t);if(this.clickedAvailable&&this.last){const e=t.global.x-this.last.x,i=t.global.y-this.last.y;(this.checkThreshold(e)||this.checkThreshold(i))&&(this.clickedAvailable=!1)}e&&this.viewport.options.stopPropagation&&t.stopPropagation()}up(t){if(this.viewport.pause||!this.viewport.worldVisible)return;"mouse"===t.pointerType&&(this.isMouseDown=!1),"mouse"!==t.pointerType&&this.remove(t.pointerId);const e=this.viewport.plugins.up(t);this.clickedAvailable&&0===this.count()&&this.last&&(this.viewport.emit("clicked",{event:t,screen:this.last,world:this.viewport.toWorld(this.last),viewport:this.viewport}),this.clickedAvailable=!1),e&&this.viewport.options.stopPropagation&&t.stopPropagation()}getPointerPosition(t){const e=new gf;return this.viewport.options.events.mapPositionToPoint(e,t.clientX,t.clientY),e}handleWheel(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.toLocal(this.getPointerPosition(t));this.viewport.left<=e.x&&e.x<=this.viewport.right&&this.viewport.top<=e.y&&e.y<=this.viewport.bottom&&this.viewport.plugins.wheel(t)&&!this.viewport.options.passiveWheel&&t.preventDefault()}pause(){this.touches=[],this.isMouseDown=!1}get(t){for(const e of this.touches)if(e.id===t)return e;return null}remove(t){for(let e=0;e<this.touches.length;e++)if(this.touches[e].id===t)return void this.touches.splice(e,1)}count(){return(this.isMouseDown?1:0)+this.touches.length}};const bx=["drag","pinch","wheel","follow","mouse-edges","decelerate","animate","bounce","snap-zoom","clamp-zoom","snap","clamp"];class wx{constructor(t){Xv(this,"plugins"),Xv(this,"list"),Xv(this,"viewport"),this.viewport=t,this.list=[],this.plugins={}}add(t,e,i=bx.length){const s=this.plugins[t];s&&s.destroy(),this.plugins[t]=e;const r=bx.indexOf(t);-1!==r&&bx.splice(r,1),bx.splice(i,0,t),this.sort()}get(t,e){var i;return e&&null!=(i=this.plugins[t])&&i.paused?null:this.plugins[t]}update(t){for(const e of this.list)e.update(t)}resize(){for(const t of this.list)t.resize()}reset(){for(const t of this.list)t.reset()}removeAll(){this.list.forEach(t=>{t.destroy()}),this.plugins={},this.sort()}remove(t){var e;this.plugins[t]&&(null==(e=this.plugins[t])||e.destroy(),delete this.plugins[t],this.viewport.emit("plugin-remove",t),this.sort())}pause(t){var e;null==(e=this.plugins[t])||e.pause()}resume(t){var e;null==(e=this.plugins[t])||e.resume()}sort(){this.list=[];for(const t of bx)this.plugins[t]&&this.list.push(this.plugins[t])}down(t){let e=!1;for(const i of this.list)i.down(t)&&(e=!0);return e}move(t){let e=!1;for(const i of this.viewport.plugins.list)i.move(t)&&(e=!0);return e}up(t){let e=!1;for(const i of this.list)i.up(t)&&(e=!0);return e}wheel(t){let e=!1;for(const i of this.list)i.wheel(t)&&(e=!0);return e}}const _x={screenWidth:window.innerWidth,screenHeight:window.innerHeight,worldWidth:null,worldHeight:null,threshold:5,passiveWheel:!0,stopPropagation:!1,forceHitArea:null,noTicker:!1,disableOnContextMenu:!1,ticker:Tg.shared,allowPreserveDragOutside:!1};class Px extends qg{constructor(t){super(),Xv(this,"moving"),Xv(this,"screenWidth"),Xv(this,"screenHeight"),Xv(this,"threshold"),Xv(this,"input"),Xv(this,"plugins"),Xv(this,"zooming"),Xv(this,"lastViewport"),Xv(this,"options"),Xv(this,"_dirty"),Xv(this,"_forceHitArea"),Xv(this,"_hitAreaDefault"),Xv(this,"_pause"),Xv(this,"tickerFunction"),Xv(this,"_worldWidth"),Xv(this,"_worldHeight"),Xv(this,"_disableOnContextMenu",t=>t.preventDefault()),this.options={..._x,...t},this.screenWidth=this.options.screenWidth,this.screenHeight=this.options.screenHeight,this._worldWidth=this.options.worldWidth,this._worldHeight=this.options.worldHeight,this.forceHitArea=this.options.forceHitArea,this.threshold=this.options.threshold,this.options.disableOnContextMenu&&this.options.events.domElement.addEventListener("contextmenu",this._disableOnContextMenu),this.options.noTicker||(this.tickerFunction=()=>this.update(this.options.ticker.elapsedMS),this.options.ticker.add(this.tickerFunction)),this.input=new xx(this),this.plugins=new wx(this)}destroy(t){!this.options.noTicker&&this.tickerFunction&&this.options.ticker.remove(this.tickerFunction),this.options.disableOnContextMenu&&this.options.events.domElement.removeEventListener("contextmenu",this._disableOnContextMenu),this.input.destroy(),super.destroy(t)}update(t){this.pause||(this.plugins.update(t),this.lastViewport&&(this.lastViewport.x!==this.x||this.lastViewport.y!==this.y?this.moving=!0:this.moving&&(this.emit("moved-end",this),this.moving=!1),this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y?this.zooming=!0:this.zooming&&(this.emit("zoomed-end",this),this.zooming=!1)),this.forceHitArea||(this._hitAreaDefault=new vf(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight),this.hitArea=this._hitAreaDefault),this._dirty=this._dirty||!this.lastViewport||this.lastViewport.x!==this.x||this.lastViewport.y!==this.y||this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y,this.lastViewport={x:this.x,y:this.y,scaleX:this.scale.x,scaleY:this.scale.y},this.emit("frame-end",this))}resize(t=window.innerWidth,e=window.innerHeight,i,s){this.screenWidth=t,this.screenHeight=e,typeof i<"u"&&(this._worldWidth=i),typeof s<"u"&&(this._worldHeight=s),this.plugins.resize(),this.dirty=!0}get worldWidth(){return this._worldWidth?this._worldWidth:this.width/this.scale.x}set worldWidth(t){this._worldWidth=t,this.plugins.resize()}get worldHeight(){return this._worldHeight?this._worldHeight:this.height/this.scale.y}set worldHeight(t){this._worldHeight=t,this.plugins.resize()}getVisibleBounds(){return new vf(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight)}toWorld(t,e){return 2===arguments.length?this.toLocal(new gf(t,e)):this.toLocal(t)}toScreen(t,e){return 2===arguments.length?this.toGlobal(new gf(t,e)):this.toGlobal(t)}get worldScreenWidth(){return this.screenWidth/this.scale.x}get worldScreenHeight(){return this.screenHeight/this.scale.y}get screenWorldWidth(){return this.worldWidth*this.scale.x}get screenWorldHeight(){return this.worldHeight*this.scale.y}get center(){return new gf(this.worldScreenWidth/2-this.x/this.scale.x,this.worldScreenHeight/2-this.y/this.scale.y)}set center(t){this.moveCenter(t)}moveCenter(...t){let e,i;"number"==typeof t[0]?(e=t[0],i=t[1]):(e=t[0].x,i=t[0].y);const s=(this.worldScreenWidth/2-e)*this.scale.x,r=(this.worldScreenHeight/2-i)*this.scale.y;return(this.x!==s||this.y!==r)&&(this.position.set(s,r),this.plugins.reset(),this.dirty=!0),this}get corner(){return new gf(-this.x/this.scale.x,-this.y/this.scale.y)}set corner(t){this.moveCorner(t)}moveCorner(...t){let e,i;return 1===t.length?(e=-t[0].x*this.scale.x,i=-t[0].y*this.scale.y):(e=-t[0]*this.scale.x,i=-t[1]*this.scale.y),(e!==this.x||i!==this.y)&&(this.position.set(e,i),this.plugins.reset(),this.dirty=!0),this}get screenWidthInWorldPixels(){return this.screenWidth/this.scale.x}get screenHeightInWorldPixels(){return this.screenHeight/this.scale.y}findFitWidth(t){return this.screenWidth/t}findFitHeight(t){return this.screenHeight/t}findFit(t,e){const i=this.screenWidth/t,s=this.screenHeight/e;return Math.min(i,s)}findCover(t,e){const i=this.screenWidth/t,s=this.screenHeight/e;return Math.max(i,s)}fitWidth(t=this.worldWidth,e,i=!0,s){let r;e&&(r=this.center),this.scale.x=this.screenWidth/t,i&&(this.scale.y=this.scale.x);const n=this.plugins.get("clamp-zoom",!0);return!s&&n&&n.clamp(),e&&r&&this.moveCenter(r),this}fitHeight(t=this.worldHeight,e,i=!0,s){let r;e&&(r=this.center),this.scale.y=this.screenHeight/t,i&&(this.scale.x=this.scale.y);const n=this.plugins.get("clamp-zoom",!0);return!s&&n&&n.clamp(),e&&r&&this.moveCenter(r),this}fitWorld(t){let e;t&&(e=this.center),this.scale.x=this.screenWidth/this.worldWidth,this.scale.y=this.screenHeight/this.worldHeight,this.scale.x<this.scale.y?this.scale.y=this.scale.x:this.scale.x=this.scale.y;const i=this.plugins.get("clamp-zoom",!0);return i&&i.clamp(),t&&e&&this.moveCenter(e),this}fit(t,e=this.worldWidth,i=this.worldHeight){let s;t&&(s=this.center),this.scale.x=this.screenWidth/e,this.scale.y=this.screenHeight/i,this.scale.x<this.scale.y?this.scale.y=this.scale.x:this.scale.x=this.scale.y;const r=this.plugins.get("clamp-zoom",!0);return r&&r.clamp(),t&&s&&this.moveCenter(s),this}setZoom(t,e){let i;e&&(i=this.center),this.scale.set(t);const s=this.plugins.get("clamp-zoom",!0);return s&&s.clamp(),e&&i&&this.moveCenter(i),this}zoomPercent(t,e){return this.setZoom(this.scale.x+this.scale.x*t,e)}zoom(t,e){return this.fitWidth(t+this.worldScreenWidth,e),this}get scaled(){return this.scale.x}set scaled(t){this.setZoom(t,!0)}snapZoom(t){return this.plugins.add("snap-zoom",new gx(this,t)),this}OOB(){return{left:this.left<0,right:this.right>this.worldWidth,top:this.top<0,bottom:this.bottom>this.worldHeight,cornerPoint:new gf(this.worldWidth*this.scale.x-this.screenWidth,this.worldHeight*this.scale.y-this.screenHeight)}}get right(){return-this.x/this.scale.x+this.worldScreenWidth}set right(t){this.x=-t*this.scale.x+this.screenWidth,this.plugins.reset()}get left(){return-this.x/this.scale.x}set left(t){this.x=-t*this.scale.x,this.plugins.reset()}get top(){return-this.y/this.scale.y}set top(t){this.y=-t*this.scale.y,this.plugins.reset()}get bottom(){return-this.y/this.scale.y+this.worldScreenHeight}set bottom(t){this.y=-t*this.scale.y+this.screenHeight,this.plugins.reset()}get dirty(){return!!this._dirty}set dirty(t){this._dirty=t}get forceHitArea(){return this._forceHitArea}set forceHitArea(t){t?(this._forceHitArea=t,this.hitArea=t):(this._forceHitArea=null,this.hitArea=new vf(0,0,this.worldWidth,this.worldHeight))}drag(t){return this.plugins.add("drag",new ox(this,t)),this}clamp(t){return this.plugins.add("clamp",new Qv(this,t)),this}decelerate(t){return this.plugins.add("decelerate",new rx(this,t)),this}bounce(t){return this.plugins.add("bounce",new Kv(this,t)),this}pinch(t){return this.plugins.add("pinch",new dx(this,t)),this}snap(t,e,i){return this.plugins.add("snap",new fx(this,t,e,i)),this}follow(t,e){return this.plugins.add("follow",new lx(this,t,e)),this}wheel(t){return this.plugins.add("wheel",new vx(this,t)),this}animate(t){return this.plugins.add("animate",new qv(this,t)),this}clampZoom(t){return this.plugins.add("clamp-zoom",new ex(this,t)),this}mouseEdges(t){return this.plugins.add("mouse-edges",new ux(this,t)),this}get pause(){return!!this._pause}set pause(t){this._pause=t,this.lastViewport=null,this.moving=!1,this.zooming=!1,t&&this.input.pause()}ensureVisible(t,e,i,s,r){r&&(i>this.worldScreenWidth||s>this.worldScreenHeight)&&(this.fit(!0,i,s),this.emit("zoomed",{viewport:this,type:"ensureVisible"}));let n=!1;t<this.left?(this.left=t,n=!0):t+i>this.right&&(this.right=t+i,n=!0),e<this.top?(this.top=e,n=!0):e+s>this.bottom&&(this.bottom=e+s,n=!0),n&&this.emit("moved",{viewport:this,type:"ensureVisible"})}}const Ex=100;var Tx,Ax={exports:{}};var Ix=function(){if(Tx)return Ax.exports;function t(){}return Tx=1,t.prototype={on:function(t,e,i){var s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var s=this;function r(){s.off(t,r),e.apply(i,arguments)}return r._=e,this.on(t,r,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),s=0,r=i.length;s<r;s++)i[s].fn.apply(i[s].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),s=i[t],r=[];if(s&&e)for(var n=0,o=s.length;n<o;n++)s[n].fn!==e&&s[n].fn._!==e&&r.push(s[n]);return r.length?i[t]=r:delete i[t],this}},Ax.exports=t,Ax.exports.TinyEmitter=t,Ax.exports}();class Sx extends Ix.TinyEmitter{constructor({floorPlan:t,helperId:e}){super(),this.floorPlan=t,this.helperId=e}destroy(){delete this.floorPlan.helper[this.helperId],this.floorPlan=null}}class Cx extends Sx{constructor({floorPlan:t,parentEl:e,helperId:i}){super({floorPlan:t,helperId:i}),e&&t&&(this.data={cursor:["0","0"]},this.floorPlan.on("mousemove",this.update,this),this.mount(e),this.update())}update(){this.rootEl&&this.setData({cursor:[c(this.floorPlan.interaction.cursor[0],this.floorPlan.settings.units.system,this.floorPlan.settings.units.lengthDecimals),c(this.floorPlan.interaction.cursor[1],this.floorPlan.settings.units.system,this.floorPlan.settings.units.lengthDecimals)]})}setData(t={}){for(let e in t)this.data[e]=t[e];this.rootEl.innerHTML=this.template(this.data)}template(t={}){return`<span class="fpe-coordinates__unit">x:${t.cursor[0]}</span>\n <span class="fpe-coordinates__unit">z:${t.cursor[1]}</span>`}mount(t){this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.classList.add("fpe-coordinates"),t.appendChild(this.rootEl))}destroy(){this.floorPlan.off("mousemove",this.update),this.rootEl.remove(),delete this.floorPlan,delete this.data}}class Mx extends Sx{constructor({floorPlan:t,parentEl:e,helperId:i}){super({floorPlan:t,helperId:i}),e&&t&&(this.data={width:100,height:4,margin:2,style:"lines",box:{},scaleStep:null,scaleDisplay:null,steps:[],leftHanded:!1,isImperial:"imperial"===t.settings.units.system},this.floorPlan.view.on("zoom",this.update,this),this.floorPlan.on("update-settings",this.update,this),this.mount(e),this.update())}update(){this.data.isImperial="imperial"===this.floorPlan.settings.units.system;const t=this.data.isImperial?3.28084:1;if(!this.floorPlan.view.viewbox)return;this.data.box.length=this.floorPlan.view.viewbox.max[0]-this.floorPlan.view.viewbox.min[0],this.data.box.width=this.floorPlan.view.viewbox.max[1]-this.floorPlan.view.viewbox.min[1];const e=Math.min(this.floorPlan.view.client[0],this.floorPlan.view.client[1]),i=Math.min(this.data.box.length,this.data.box.width),s=e/i;if(!s)return;const r=200/s;this.data.scaleStep=i<=.5/t?.01/t:i<=1/t?.05/t:i<=2.5/t?.1/t:i<=5.4/t?.2/t:i<=12/t?.5/t:i<=25/t?1/t:i<=50/t?2/t:i<=100/t?5/t:i<=200/t?10/t:i<=550/t?20/t:50/t,this.data.scaleDisplay=this.data.scaleStep*t;const n=this.data.width,o=n*this.data.scaleStep/r,a=this.leftHanded?0:n;let l=0,h=[];if(this.data.leftHanded)for(;l<n-o;){let t=o<n-l?o:n-l;h.push([l+a,t]),l+=o}else for(;l>-n+o;){let t=o;h.push([l+a,-t]),l-=o}this.data.steps=h,this.setData()}setData(t={}){for(let e in t)this.data[e]=t[e];this.rootEl.setAttribute("viewBox",`-${this.data.margin} -${3*this.data.margin} ${this.data.width+2*this.data.margin} ${this.data.height+2*this.data.margin}`),this.rootEl.innerHTML=this.template(this.data)}template(t={}){let e="";return t.steps[0]&&(e+=`<rect\n class="fpe-scale-bar__background"\n style="fill:${this.backgroundClr()}"\n y="${2.5*-t.height}"\n x="${t.width+t.steps[0][1]-t.margin}"\n width="${-t.steps[0][1]+2*t.margin}"\n height="${4*t.height}"\n />`),e+=`<text x="${t.leftHanded?0:t.width}" text-anchor="${t.leftHanded?"start":"end"}" y="-3">\n ${t.scaleDisplay} ${t.isImperial?"ft":"m"}\n </text>`,"lines"===t.style&&(e+=`<path d="${this.stepStr(t.steps)}" />`),"solid"===t.style&&(e+="<g>",t.steps.forEach((t,i)=>{e+=`<rect\n class="${i%2!=0?"white":""}"\n x="${t[0]}"\n y="0"\n width="${t[1]}"\n height="0.5"\n />`}),e+="</g>"),e}backgroundClr(){let t=this.floorPlan.settings&&function(t,e=1){if(null!==f(t).match(/^#[a-f0-9]{6}$/i)){const{r:i,g:s,b:r}=g(t);return`rgba(${i},${s},${r},${e})`}}(this.floorPlan.settings.theme.background.color);return t||(t="rgba(255, 255, 255, 0.8)"),t+"!important"}stepStr(t){if(!t)return"";let e="",i=this.data.height;return t.forEach((t,s)=>{if(s>=1&&!this.data.leftHanded)return;t=t.map(t=>Math.round(1e3*t)/1e3);let r=s%2==0?0:i,n=s%2==0?i:0;0===s&&(e+=`M ${t[0]} ${i} L ${t[0]} 0`),e+=`L ${t[0]+t[1]} ${r} `,e+=`L ${t[0]+t[1]} ${n} `}),e}mount(t){this.rootEl||(this.rootEl=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.rootEl.classList.add("fpe-scale-bar"),t.appendChild(this.rootEl))}destroy(){this.floorPlan.view.off("viewbox",this.update),this.floorPlan.off("update-settings",this.update),this.rootEl.remove(),delete this.floorPlan.helper.scaleBar,delete this.floorPlan,delete this.data}}const Ox=100,Nx=80;class Lx{constructor({width:t,height:e,position:i=[0,0],html:s="",closeButton:r=!0,floorPlan:n}={}){this._floorPlan=n,this.position=i,this.html=s,this.closeButton=r,this._anchorPos=null;let o=t||Ox;this.width=Math.max(100,o);let a=e||Nx;this.height=Math.max(50,a),this._getPosition=()=>{this._anchorPos=this._floorPlan.getScreenPosition(this.position),this._updateInfoWindow()},this._getPosition(),this._createInfoWindow(),this._floorPlan.view.on("viewbox",this._getPosition,this),this._floorPlan.view.on("resize-canvas",this._getPosition,this)}_createInfoWindow(){const t=document.querySelector(`#${this._floorPlan.fpeId}.fpe`),e=t.querySelector("canvas");this.el||(this.el=document.createElement("div"),this.el.classList.add("fpe-info-window"),t.appendChild(this.el),this.el.addEventListener("wheel",t=>{let i=new WheelEvent(t.type,t);e.dispatchEvent(i)})),this._setContent(),this._updateInfoWindow()}_setContent(){let t=`<div class="fpe-info-window__content">${this.html}</div>`;this.closeButton&&(t+='<div class="fpe-info-window__close" @click="infoWindow.remove"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">\n <g fill="none" stroke="#000" stroke-width="1.2" stroke-miterlimit="10">\n <path d="M11.8 11.8l16.4 16.4M11.8 28.2l16.3-16.4" />\n </g>\n</svg></div>'),this.el.innerHTML=t;const e=this.el.querySelector(".fpe-info-window__close");e&&e.addEventListener("click",this.remove.bind(this))}_updateInfoWindow(){if(!this.el)return;const t=this._floorPlan.interaction.isPanning?"pointer-events: none;":"",e=this._anchorPos[0]-47,i=this._anchorPos[1]-this.height-15,s=1e3+2*this.position[1],r=this.height,n=this.width;this.el.setAttribute("style",`transform: translate(${e}px, ${i}px);${t} height:${r}px; width:${n}px; z-index:${s}`)}set({width:t,height:e,position:i,html:s,closeButton:r}){void 0!==i&&(this.position=i),void 0!==t&&(this.width=Math.max(100,t)),void 0!==e&&(this.height=Math.max(50,e)),void 0!==s&&(this.html=s),void 0!==r&&(this.closeButton=r),void 0===s&&void 0===r||this._setContent(),this._getPosition()}remove(){this._floorPlan.view.off("viewbox",this._getPosition),this._floorPlan.view.off("resize-canvas",this._getPosition),this.el.remove(),this._floorPlan=null}}class Rx{constructor({position:t=[0,0],offset:e=[0,0],el:i,floorPlan:s}){if(this._updateHtmlMarker=()=>{this.el&&(this.isHidden=!(([t,e],i,s=0)=>i.min[0]-s<t&&i.max[0]+s>t&&i.min[1]-s<e&&i.max[1]+s>e)(this.position,this._floorPlan.view.viewbox,5),this.el.classList.toggle("fpe-marker--hidden",this.isHidden),this.isHidden||(this._anchorPos=this._floorPlan.getScreenPosition(this.position),this._updateHtmlMarkerStyle()))},!s)return;if(i instanceof HTMLElement==!1)return void Nl.warn("no Element provided");this.el=i;const r=document.querySelector(`#${s.fpeId}.fpe`),n=r.querySelector("canvas");r.appendChild(this.el),this.el.classList.add("fpe-marker");const{width:o,height:a}=i.getBoundingClientRect();this.el.addEventListener("wheel",t=>{let e=new WheelEvent(t.type,t);n.dispatchEvent(e)}),this.id=O(),this._floorPlan=s,this.position=t,this.size=[o,a],this.offset=e,this._updateHtmlMarker(),this._floorPlan.view.on("viewbox",this._updateHtmlMarker),this._floorPlan.on("drag-end",this._updateHtmlMarker),this._floorPlan.view.on("resize-canvas",this._updateHtmlMarker)}_updateHtmlMarkerStyle(){const t=this._floorPlan.interaction.isPanning,e=this.offset?this.offset:[0,0],i=this._anchorPos[0]-this.size[0]/2+e[0],s=this._anchorPos[1]-this.size[1]/2+e[1];this.el.style.pointerEvents=t?"none":"",this.el.style.transform=`translate(${i}px, ${s}px)`}set({position:t,offset:e}){void 0!==t&&(this.position=t),void 0!==e&&(this.offset=e),this._updateHtmlMarker()}remove(){this._floorPlan.view.off("viewbox",this._updateHtmlMarker),this._floorPlan.view.off("resize-canvas",this._updateHtmlMarker),this._floorPlan.off("drag-end",this._updateHtmlMarker),this.el.remove(),this._floorPlan=null}}var Bx={grad:.9,turn:360,rad:360/(2*Math.PI)},kx=function(t){return"string"==typeof t?t.length>0:"number"==typeof t},Fx=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=Math.pow(10,e)),Math.round(i*t)/i+0},Dx=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=1),t>i?i:t>e?t:e},Ux=function(t){return(t=isFinite(t)?t%360:0)>0?t:t+360},Gx=function(t){return{r:Dx(t.r,0,255),g:Dx(t.g,0,255),b:Dx(t.b,0,255),a:Dx(t.a)}},Xx=function(t){return{r:Fx(t.r),g:Fx(t.g),b:Fx(t.b),a:Fx(t.a,3)}},Wx=/^#([0-9a-f]{3,8})$/i,Yx=function(t){var e=t.toString(16);return e.length<2?"0"+e:e},Hx=function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=Math.max(e,i,s),o=n-Math.min(e,i,s),a=o?n===e?(i-s)/o:n===i?2+(s-e)/o:4+(e-i)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},$x=function(t){var e=t.h,i=t.s,s=t.v,r=t.a;e=e/360*6,i/=100,s/=100;var n=Math.floor(e),o=s*(1-i),a=s*(1-(e-n)*i),l=s*(1-(1-e+n)*i),h=n%6;return{r:255*[s,a,o,o,l,s][h],g:255*[l,s,s,a,o,o][h],b:255*[o,o,l,s,s,a][h],a:r}},jx=function(t){return{h:Ux(t.h),s:Dx(t.s,0,100),l:Dx(t.l,0,100),a:Dx(t.a)}},zx=function(t){return{h:Fx(t.h),s:Fx(t.s),l:Fx(t.l),a:Fx(t.a,3)}},Vx=function(t){return $x((i=(e=t).s,{h:e.h,s:(i*=((s=e.l)<50?s:100-s)/100)>0?2*i/(s+i)*100:0,v:s+i,a:e.a}));var e,i,s},qx=function(t){return{h:(e=Hx(t)).h,s:(r=(200-(i=e.s))*(s=e.v)/100)>0&&r<200?i*s/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,i,s,r},Jx=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Kx=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Zx=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Qx=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,tb={string:[[function(t){var e=Wx.exec(t);return e?(t=e[1]).length<=4?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16),a:4===t.length?Fx(parseInt(t[3]+t[3],16)/255,2):1}:6===t.length||8===t.length?{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16),a:8===t.length?Fx(parseInt(t.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(t){var e=Zx.exec(t)||Qx.exec(t);return e?e[2]!==e[4]||e[4]!==e[6]?null:Gx({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:void 0===e[7]?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(t){var e=Jx.exec(t)||Kx.exec(t);if(!e)return null;var i,s,r=jx({h:(i=e[1],s=e[2],void 0===s&&(s="deg"),Number(i)*(Bx[s]||1)),s:Number(e[3]),l:Number(e[4]),a:void 0===e[5]?1:Number(e[5])/(e[6]?100:1)});return Vx(r)},"hsl"]],object:[[function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=void 0===r?1:r;return kx(e)&&kx(i)&&kx(s)?Gx({r:Number(e),g:Number(i),b:Number(s),a:Number(n)}):null},"rgb"],[function(t){var e=t.h,i=t.s,s=t.l,r=t.a,n=void 0===r?1:r;if(!kx(e)||!kx(i)||!kx(s))return null;var o=jx({h:Number(e),s:Number(i),l:Number(s),a:Number(n)});return Vx(o)},"hsl"],[function(t){var e=t.h,i=t.s,s=t.v,r=t.a,n=void 0===r?1:r;if(!kx(e)||!kx(i)||!kx(s))return null;var o,a=(o={h:Number(e),s:Number(i),v:Number(s),a:Number(n)},{h:Ux(o.h),s:Dx(o.s,0,100),v:Dx(o.v,0,100),a:Dx(o.a)});return $x(a)},"hsv"]]},eb=function(t,e){for(var i=0;i<e.length;i++){var s=e[i][0](t);if(s)return[s,e[i][1]]}return[null,void 0]},ib=function(t,e){var i=qx(t);return{h:i.h,s:Dx(i.s+100*e,0,100),l:i.l,a:i.a}},sb=function(t){return(299*t.r+587*t.g+114*t.b)/1e3/255},rb=function(t,e){var i=qx(t);return{h:i.h,s:i.s,l:Dx(i.l+100*e,0,100),a:i.a}},nb=function(){function t(t){this.parsed=function(t){return"string"==typeof t?eb(t.trim(),tb.string):"object"==typeof t&&null!==t?eb(t,tb.object):[null,void 0]}(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return t.prototype.isValid=function(){return null!==this.parsed},t.prototype.brightness=function(){return Fx(sb(this.rgba),2)},t.prototype.isDark=function(){return sb(this.rgba)<.5},t.prototype.isLight=function(){return sb(this.rgba)>=.5},t.prototype.toHex=function(){return e=(t=Xx(this.rgba)).r,i=t.g,s=t.b,n=(r=t.a)<1?Yx(Fx(255*r)):"","#"+Yx(e)+Yx(i)+Yx(s)+n;var t,e,i,s,r,n},t.prototype.toRgb=function(){return Xx(this.rgba)},t.prototype.toRgbString=function(){return e=(t=Xx(this.rgba)).r,i=t.g,s=t.b,(r=t.a)<1?"rgba("+e+", "+i+", "+s+", "+r+")":"rgb("+e+", "+i+", "+s+")";var t,e,i,s,r},t.prototype.toHsl=function(){return zx(qx(this.rgba))},t.prototype.toHslString=function(){return e=(t=zx(qx(this.rgba))).h,i=t.s,s=t.l,(r=t.a)<1?"hsla("+e+", "+i+"%, "+s+"%, "+r+")":"hsl("+e+", "+i+"%, "+s+"%)";var t,e,i,s,r},t.prototype.toHsv=function(){return t=Hx(this.rgba),{h:Fx(t.h),s:Fx(t.s),v:Fx(t.v),a:Fx(t.a,3)};var t},t.prototype.invert=function(){return ob({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},t.prototype.saturate=function(t){return void 0===t&&(t=.1),ob(ib(this.rgba,t))},t.prototype.desaturate=function(t){return void 0===t&&(t=.1),ob(ib(this.rgba,-t))},t.prototype.grayscale=function(){return ob(ib(this.rgba,-1))},t.prototype.lighten=function(t){return void 0===t&&(t=.1),ob(rb(this.rgba,t))},t.prototype.darken=function(t){return void 0===t&&(t=.1),ob(rb(this.rgba,-t))},t.prototype.rotate=function(t){return void 0===t&&(t=15),this.hue(this.hue()+t)},t.prototype.alpha=function(t){return"number"==typeof t?ob({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):Fx(this.rgba.a,3);var e},t.prototype.hue=function(t){var e=qx(this.rgba);return"number"==typeof t?ob({h:t,s:e.s,l:e.l,a:e.a}):Fx(e.h)},t.prototype.isEqual=function(t){return this.toHex()===ob(t).toHex()},t}(),ob=function(t){return t instanceof nb?t:new nb(t)},ab=[];!function(t){t.forEach(function(t){ab.indexOf(t)<0&&(t(nb,tb),ab.push(t))})}([function(t,e){var i={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},s={};for(var r in i)s[i[r]]=r;var n={};t.prototype.toName=function(e){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var r,o,a=s[this.toHex()];if(a)return a;if(null==e?void 0:e.closest){var l=this.toRgb(),h=1/0,u="black";if(!n.length)for(var c in i)n[c]=new t(i[c]).toRgb();for(var d in i){var p=(r=l,o=n[d],Math.pow(r.r-o.r,2)+Math.pow(r.g-o.g,2)+Math.pow(r.b-o.b,2));p<h&&(h=p,u=d)}return u}},e.string.push([function(e){var s=e.toLowerCase(),r="transparent"===s?"#0000":i[s];return r?new t(r).toRgb():null},"name"])}]);const lb=class t{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(t){return this.value=t,this}set value(e){if(e instanceof t)this._value=this.cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(null===e)throw new Error("Cannot set PIXI.Color#value to null");(null===this._value||!this.isSourceEqual(this._value,e))&&(this.normalize(e),this._value=this.cloneSource(e))}}get value(){return this._value}cloneSource(t){return"string"==typeof t||"number"==typeof t||t instanceof Number||null===t?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):"object"==typeof t&&null!==t?{...t}:t}isSourceEqual(t,e){const i=typeof t;if(i!==typeof e)return!1;if("number"===i||"string"===i||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length===e.length&&t.every((t,i)=>t===e[i]);if(null!==t&&null!==e){const i=Object.keys(t),s=Object.keys(e);return i.length===s.length&&i.every(i=>t[i]===e[i])}return t===e}toRgba(){const[t,e,i,s]=this._components;return{r:t,g:e,b:i,a:s}}toRgb(){const[t,e,i]=this._components;return{r:t,g:e,b:i}}toRgbaString(){const[t,e,i]=this.toUint8RgbArray();return`rgba(${t},${e},${i},${this.alpha})`}toUint8RgbArray(t){const[e,i,s]=this._components;return(t=t??[])[0]=Math.round(255*e),t[1]=Math.round(255*i),t[2]=Math.round(255*s),t}toRgbArray(t){t=t??[];const[e,i,s]=this._components;return t[0]=e,t[1]=i,t[2]=s,t}toNumber(){return this._int}toLittleEndianNumber(){const t=this._int;return(t>>16)+(65280&t)+((255&t)<<16)}multiply(e){const[i,s,r,n]=t.temp.setValue(e)._components;return this._components[0]*=i,this._components[1]*=s,this._components[2]*=r,this._components[3]*=n,this.refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this.refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(1===t)return(255<<24)+this._int;if(0===t)return e?0:this._int;let i=this._int>>16&255,s=this._int>>8&255,r=255&this._int;return e&&(i=i*t+.5|0,s=s*t+.5|0,r=r*t+.5|0),(255*t<<24)+(i<<16)+(s<<8)+r}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const t=Math.round(255*this._components[3]).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(t){return this._components[3]=this._clamp(t),this}round(t){const[e,i,s]=this._components;return this._components[0]=Math.round(e*t)/t,this._components[1]=Math.round(i*t)/t,this._components[2]=Math.round(s*t)/t,this.refreshInt(),this._value=null,this}toArray(t){t=t??[];const[e,i,s,r]=this._components;return t[0]=e,t[1]=i,t[2]=s,t[3]=r,t}normalize(e){let i,s,r,n;if(("number"==typeof e||e instanceof Number)&&e>=0&&e<=16777215){i=(e>>16&255)/255,s=(e>>8&255)/255,r=(255&e)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[i,s,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[i,s,r,n=255]=e,i/=255,s/=255,r/=255,n/=255;else if("string"==typeof e||"object"==typeof e){if("string"==typeof e){const i=t.HEX_PATTERN.exec(e);i&&(e=`#${i[2]}`)}const o=ob(e);o.isValid()&&(({r:i,g:s,b:r,a:n}=o.rgba),i/=255,s/=255,r/=255)}if(void 0===i)throw new Error(`Unable to convert color ${e}`);this._components[0]=i,this._components[1]=s,this._components[2]=r,this._components[3]=n,this.refreshInt()}refreshInt(){this._clamp(this._components);const[t,e,i]=this._components;this._int=(255*t<<16)+(255*e<<8)+(255*i|0)}_clamp(t,e=0,i=1){return"number"==typeof t?Math.min(Math.max(t,e),i):(t.forEach((s,r)=>{t[r]=Math.min(Math.max(s,e),i)}),t)}};lb.shared=new lb,lb.temp=new lb,lb.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let hb=lb;class ub{constructor({position:t,color:e,size:i,floorPlan:s}){this.position=t,this.color=e,this.size=i,this.floorPlan=s,this.id=O(),this.draw()}draw(){const t=this.size/4e3;this.layer=this.floorPlan.addLayer({id:"fpe-markers"});let e=[{type:"curve:composite",segments:[{type:"curve:arc",position:[0,-27.8],radius:12.4,startAngle:-25,endAngle:205},{type:"curve:line",end:[0,0],start:[-11.2,-22.5]}],style:{fill:new hb(this.color).toNumber(),stroke:6710886,strokeWidth:.5/t}},{type:"curve:circle",position:[0,-28],radius:5,style:{fill:1,fillOpacity:.2}}];this.graphic=this.layer.addGraphic({shapes:e,position:this.position,id:"marker_"+this.id,scale:t,scaleOnZoom:!0})}remove(){this.off("click"),this.layer.deleteGraphic(this.graphic),delete this.floorPlan,0===this.layer.graphics.size&&this.layer.destroy()}on(t="click",e,i){this.graphic.gfx.eventMode="static",this.graphic.gfx.on(t,e,i)}off(t="click",e){this.graphic.gfx.off(t,e)}set(t){let e=["position","color","size"];Object.keys(t).forEach(i=>{e.includes(i)&&(this[i]=t[i])}),this.draw()}}const cb=t=>{if(t?.children)for(var e=t.children.length-1;e>=0;e--)t.children[e].destroy({children:!0}),t.removeChild(t.children[e])};function db(t,e,i){const s=new Zg(t);return s.x=0,s.y=0,s.anchor.x=.5,s.anchor.y=.5,s.rotation=0,e&&(s.width=e),i&&(s.height=i),s}function pb(t=[]){return(t=t.sort((t,e)=>K(t)>K(e)?-1:1))&&t.length?[{type:"curve:polygonWithHoles",polygons:t}]:[]}function fb(t,e,i=!1,s=16,r=8){let n=[];for(let m=0;m<e.length-1;m+=2)n.push({x:e[m],y:e[m+1]});let o,a,l,h=0,u=0,c=i?1:0;for(o=0;o<n.length-c;o++){a=n[o],l=o==n.length-1?n[0]:n[o+1];let e=l.x-a.x,i=l.y-a.y;var d=Math.sqrt(e*e+i*i),p={x:e/d,y:i/d},f=0;for(t.moveTo(a.x+u*p.x,a.y+u*p.y);f<=d;)f+=u,(f+=h>0?h:s)>d?(h=f-d,f=d):h=0,t.lineTo(a.x+f*p.x,a.y+f*p.y),(f+=r)>d&&0==h?u=f-d:(u=0,t.moveTo(a.x+f*p.x,a.y+f*p.y))}}function mb(t){return t.stroke?{alpha:t.strokeOpacity||1,color:eh(t.stroke),native:"native"===t.strokeWidth,width:"number"==typeof t.strokeWidth?t.strokeWidth:1,alignment:"number"==typeof t.alignment?t.alignment:.5}:{}}function gb({shape:t,settings:e,gfx:i,style:s={}}){if(!i||!i.lineStyle)return;const r={...s,...t.style};t.style||(r.stroke??=vl),r.strokeWidth??="native";const n=Ex,o=!["curve:line","curve:polyline","curve:arc"].includes(t.type)&&!!r.fill;if("string"==typeof r?.fill&&r.fill.startsWith("url("))!function({shape:t,settings:e,style:i,gfx:s}){if(tf.defaultOptions.scaleMode=wh.NEAREST,"string"!=typeof i?.fill||"curve:rectangle"!==t.type&&"curve:polygon"!==t.type)return;let r,n,o=[0,0],a=i.fill.match(/url\((.*?)\)/)?.[1];if(!a||!a.startsWith("data:image")&&!a.startsWith("https://"))return;let l=Zg.from(a);if("curve:polygon"===t.type){let{min:i,max:a}=W([t.points]);r=a[0]-i[0],n=a[1]-i[1],o=i;let h=new Ty;gb({shape:{type:"curve:polygon",points:t.points,style:{fill:16777215}},settings:e,gfx:h}),s.addChild(h),l.mask=h}else r=t.dimensions[0],n=t.dimensions[1],o=t.position;l.width=r*Ex,l.height=n*Ex,l.x=o[0]*Ex,l.y=o[1]*Ex,l.anchor.set(0),s.addChild(l)}({shape:t,settings:e,style:r,gfx:i});else{if(o&&r.fill&&i.beginFill(eh(r.fill),r.fillOpacity),i.lineStyle(mb(r)),"curve:rectangle"===t.type){let{position:e,dimensions:s}=t;i.drawRect(e[0]*n,e[1]*n,s[0]*n,s[1]*n)}else if("curve:circle"===t.type||"curve:composite"===t.type){yb((t=>{const e={type:"curve:polygon",points:[],style:t.style};switch(t.type){case"curve:circle":const i=t.radius,s=lh(2*Math.PI,i),r=t.position,n=2*Math.PI/s;let o=0;for(let t=0;t<s;t++)e.points.push([i*Math.cos(o)+r[0],-i*Math.sin(o)+r[1]]),o+=n;break;case"curve:polygon":e.points=t.points;break;case"curve:rectangle":const a=t.dimensions,[l,h]=t.position||[0,0];e.points=[[l,h],[l,h+a[1]],[l+a[0],h+a[1]],[l+a[0],h]];break;case"curve:composite":for(const u of t.segments){let t=hh(u);e.points.push(...t.points)}}return e})(t).points,[],r,n,i,o)}else if("curve:arc"===t.type||"curve:quadraticBezier"===t.type){hh(t).points.forEach((t,e)=>{0===e?i.moveTo(t[0]*n,t[1]*n):i.lineTo(t[0]*n,t[1]*n)})}else if("curve:polygon"===t.type)yb(t.points,[],r,n,i,o);else if("curve:polygonWithHoles"===t.type){let{polygons:e}=t;yb(e[0],e.slice(1),r,n,i,o)}else if("curve:line"===t.type){let{start:e,end:s}=t;i.moveTo(e[0]*n,e[1]*n),i.lineTo(s[0]*n,s[1]*n)}else if("curve:polyline"===t.type){let{points:e}=t;r.dash?fb(i,e.flat().map(t=>t*n),!0):e.forEach((t,e)=>{0===e?i.moveTo(t[0]*n,t[1]*n):i.lineTo(t[0]*n,t[1]*n)})}else if("group"===t.type){let{position:r=[0,0],rotation:o=0}=t,a=new Ty;a.x=r[0]*n,a.y=r[1]*n,a.rotation=-Math.PI/180*o,t.children.forEach(t=>gb({shape:t,settings:e,gfx:a,style:s})),i.addChild(a)}else if("text"===t.type){let s=t.style?.fill?eh(t.style.fill):0,r=t.style?.stroke?eh(t.style.stroke):16777215,{position:o=[0,0],rotation:a=0,text:l,alignH:h="center",alignV:u="center",fontSize:c=16}=t;const d=new Ny({fontFamily:e?.theme?.fontFamily||Sl.theme?.fontFamily,fontSize:c,fill:s,align:h,stroke:r,strokeThickness:3});let p=new Fy(l,d);p.x=o[0]*n,p.y=o[1]*n,p.rotation=-Math.PI/180*a,p.anchor.x=.5,p.anchor.y="center"===u?.5:"bottom"===u?1:0,i.addChild(p)}o&&i.endFill()}}function yb(t=[],e=[],i={},s=100,r,n){if(!t||!Array.isArray(t)||!t.length)return r;r.lineStyle(mb(i));let o=t.flat().map(t=>t*s);if(i.dash?(fb(r,o),n&&(r.lineStyle(0),r.drawPolygon(o))):r.drawPolygon(o),e.length){n&&r.beginHole();for(const t of e){let e=t.flat().map(t=>t*s);r.drawPolygon(e)}n&&r.endHole()}return r}function vb(t,e){e.on("product-load-texture",({resourceId:i})=>{!function(t,e){let i=t.resources.productJson.get(e);if(!i.boundingBox)return void Nl.warn("product boundingBox missing");const{boundingBox:s}=i,r=$l(s);let n={x:s.min[0],y:s.min[2]},o={x:Math.abs(s.min[0]/r[0]),y:Math.abs(s.min[2]/r[2])},a={x:s.max[0]-r[0]/2,y:s.max[2]-r[2]/2},l=t.resources.texture.get(e);l.offset=a,l.anchor=o,l.position=n}(e,i),xb({view:t,resourceId:i,loader:e})});const i=new Ty;i.lineStyle({native:!0,color:3355443}),i.drawCircle(0,0,1),t._dummyTexture=t._renderer.generateTexture(i)}function xb({resourceId:t,loader:e,view:i}){if(!e.resources.texture.has(t))return Promise.reject(`no texture data to load ${t}`);const s=e.resources.texture.get(t);if(s.texture)return Promise.resolve();let{textureUrl:r}=s;return Mp(),function(t){return new Promise((e,i)=>{var s=new Image;s.addEventListener("load",()=>{URL.revokeObjectURL(s.src),e(new Em(new tf(s)))}),s.addEventListener("error",()=>{URL.revokeObjectURL(s.src),i("image loading failed: "+t)});const r=t.includes("/storage/get/"),n=t.startsWith("https://")?t:Ml+t;s.src=n,s.crossOrigin=r?"use-credentials":"anonymous"})}(r).then(r=>{s.imageData=r,function(t,e,i){const s=e?._renderer;if(!s)return;const r=i.resources.texture.get(t),n=r.error;if(Mp(),!r.texture){const e=i.resources.productJson.get(t),o=new qg;let a,l;n||(a=new Zg(r.imageData),a=wb(a,r.applyFilter),o.addChild(a));const h=i.resources.productContour.get(t),u=h?.length?[{type:"curve:polygon",points:h[0],holes:h.slice(1)}]:[];if(u.length&&e?.boundingBox){let t;n?t={strokeWidth:.5,stroke:1,fill:16316664}:(t=nh({settings:{theme:{showAssetTextures:!0,byType:{}}},elementType:"element:asset"}),t.stroke=vl),l=bb(u,t);const i=new Zg(l);i.anchor.x=r.anchor.x,i.anchor.y=r.anchor.y;const s=$l(e.boundingBox);if(!n){let t=a.width/s[0],e=r?.offset||{x:0,y:0};i.scale.x=a.width/i.width,i.scale.y=a.height/i.height,i.x=a.width/2-e.x*t,i.y=a.height/2-e.y*t}o.addChild(i)}r.texture=s.generateTexture(o,{scaleMode:wh.LINEAR,resolution:1.5}),o.destroy(!0),l&&l.destroy(!0)}i.emit("resource-loaded",{resourceId:t})}(t,i,e)}).catch(i=>{Nl.warn(i),s.error={message:i},e.emit("resource-loaded",{resourceId:t})})}function bb(t,e){let i,s=new Ty;for(const r of t)gb({shape:r,gfx:s,style:e});return i=s.generateCanvasTexture(wh.LINEAR,2),s.destroy(),i}function wb(t,e){switch(e){case Xl.Default:{const e=new Dy;e.matrix=[.7,0,0,0,.25,0,.7,0,0,.25,0,0,.7,0,.25,0,0,0,1,0],t.filters=[e];break}case Xl.Grayscale:{const e=new Dy;e.blackAndWhite(!0),t.filters=[e];break}case Xl.None:}return t}function _b(t,e,i,s,r,n,o){const a=$l(t.boundingBox),l=db(e.texture,a[0]*o,a[2]*o);l.anchor.x=e.anchor.x,l.anchor.y=e.anchor.y,l.zIndex=1,function(t,e,i,s){if(!e.categories?.includes("tables")&&!e.categories?.includes("seating")||!i[0]?.polygons[0])return;const r=new wf(i[0].polygons[0].flatMap(e=>[e[0]*s/t.scale.x,e[1]*s/t.scale.y]));t.hitArea=r,t.eventMode="static"}(l,t,i,o);const h=[];let u=[];if(!n&&(null!=r.fill||null!=r.stroke)&&i?.length){const t=function(t,e,i,s,r){const n=null!=i.fill,o=null!=i.stroke,a=e.fillOpacity??1;if(!n&&!o)return null;if(n&&a<=0&&!o)return null;const l=bb(t,{fill:n?e.fill:void 0,fillOpacity:n?a:0,stroke:o?e.stroke:void 0,strokeWidth:o?e.strokeWidth:void 0,strokeOpacity:o?e.strokeOpacity:void 0}),h=new Zg(l);return h.anchor.x=s,h.anchor.y=r,h.zIndex=2,h.eventMode="none",h}(i,s,r,e.anchor.x,e.anchor.y);t&&h.push(t)}if("selected"===n)h.push(function(t,e,i,s){e.contourTexture||(e.contourTexture=bb(t,{stroke:i.stroke,strokeWidth:i.strokeWidth||1}));const r=new Zg(e.contourTexture);return r.anchor.x=e.anchor.x,r.anchor.y=e.anchor.y,r.zIndex=5,r.eventMode="none",i.fill&&(s.tint=eh(i.fill)),r}(i,e,s,l));else if(n){const{overlay:t,shapes:e}=function(t){const e=new Ty;return e.zIndex=5,e.eventMode="none",{overlay:e,shapes:t||[]}}(i);h.push(t),u=e}return{gfx:l,overlays:h,shapes:u}}function Pb(t,e,i,s){!function(t,e){const i=t.product?.id,{loader:s}=e,r=s.resources.nodes.get(i);if(i&&!r?.has(t))Ll(e.loader,t).catch(t=>Nl.warn(t))}(t,i);const{view:r,settings:n,loader:o}=i,{theme:a,showCeilingLamps:l}=n;let h,u=[];const c=[],d=t.product?.id,p=o.resources.productJson.get(d)||{subCategories:[]},f="product:component"===t.product?.type,m=o.resources.productContour.get(d),g=o.resources.texture.get(d),y=pb(m);if(p?.subCategories.includes("ceilingLight")&&!l)return[];const v=function(t,e,i){if(!i)return ch(e);let s=0;for(const r of t.elements){if("element:asset"!==r.type||!r.product)continue;const t=ch(r.product.attributes);t>s&&(s=t)}return s}(t,p,f),x=th(t.type,v);e.zIndex=x||0;let b=nh({element:t,settings:n,style:s});if(m||f||!p.boundingBox)if(a.showAssetTextures&&!g?.error||!m)if(a.showAssetTextures&&g?.texture){const e=t.parent?.id,i=_b(p,g,y,b,sh({settings:n,nodeId:t.id,parentId:e,nodeType:t.type}),s,100);h=i.gfx,c.push(...i.overlays),u=i.shapes}else h=new Zg(r._dummyTexture);else{const e={...a,showAssetTextures:!1};b=nh({element:t,settings:{...n,theme:e},style:s}),u=y,h=new Ty}else{u=pb(function(t){const e=t;if(e){let t;return t=[[e.min[0],e.min[2]],[e.min[0],e.max[2]],[e.max[0],e.max[2]],[e.max[0],e.min[2]]],[t]}return[]}(p.boundingBox)),h=new Ty}const w=c.length>0?c[c.length-1]:h;for(const _ of u)gb({shape:_,settings:n,gfx:w,style:b});return[h,...c].filter(Boolean)}function Eb(t,e){const i=[];if("element:wall"===t.type)i.push(...function(t){let{valid:e,points:i}=t.geometryProfile,s=[];if(t.layout?.debugIds){for(let t of i)s.push({type:"curve:circle",radius:.02,position:t,style:{stroke:0,fill:e?32768:16711680,fillOpacity:.2}});let r=nh({element:t});e||(r.stroke=16711680),s.push({type:"curve:polygon",points:i,style:r})}else s.push({type:"curve:polygon",points:i});return s}(t));else if("element:opening"===t.type)i.push(...jl(t));else if("spatialGraph:edge"===t.type)i.push(...function(t,e={}){let[i,s]=t.vertices,r="selected"===e,n=[{type:"curve:line",start:i.position,end:s.position}];if(t.layout.debugIds){let e,r=fl(t.id)?t.id.substring(0,4):t.id;t.element&&(e=fl(t.element.id)?t.element.id.substring(0,4):t.element.id);let o=t.element?`${r} (${e})`:r;n.push({type:"text",position:ti(i.position,hi(ui(s.position,i.position),.5)),text:o,fontSize:10})}if(null===t.element||"element:spaceDivider"===t.element.type){let t=ai(li(ui(s.position,i.position))),e=.02,o=ti(i.position,hi(t,-e)),a=ti(i.position,hi(t,e)),l=ti(s.position,hi(t,e)),h=ti(s.position,hi(t,-e));n.unshift({type:"curve:polygon",points:[o,a,l,h],style:{stroke:null,fill:r?Tl:El,fillOpacity:.1}})}return n}(t));else if("layout:space"===t.type){const e=t.geometry.polygons;e.length>0&&i.push({type:"curve:polygonWithHoles",polygons:e})}else if("geometries"in t&&t.geometries.length){const{shapes:s,maxY:r}=function(t){const e=dl(t).sort((t,e)=>t.boundingBox.max[1]<e.boundingBox.max[1]?-1:1);"element:door"!==t.type&&"element:window"!==t.type||e.pop();let i=e.length?e[e.length-1].boundingBox.max[1]:0,s=[];for(let r of e)for(let t=0;t<r.outlines.length;t++)s.push({type:"curve:polygonWithHoles",polygons:[r.outlines[t],...r.holes[t]||[]]});return{shapes:s,maxY:i}}(t);i.push(...s),e.zIndex=e.zIndex+r}return i}function Tb(t,e,i,s,r,n){if(!e||e.destroyed)return void Nl.warn(`graphic container for node ${t.id} is missing`);let o,a,l=[];const{view:h}=i;if("element:asset"!==t.type||t.isComponentInstance)if("annotation:floorPlanImage"===t.type){const s=function(t,e,i){const{view:s,settings:r,loader:n}=i,o=Ex;let a,l;e.x=t.position[0]*o,e.y=t.position[2]*o,e.rotation=-Math.PI/180*t.rotation||0;const{uri:h,length:u,width:c}=t.parameters,d=t.id,p=r.theme.byType["annotation:floorPlanImage"]?.grayscale?Xl.Grayscale:Xl.None,f=n.resources.texture.get(d);return f?.texture?(a=db(f.texture,u*o,c*o),a=wb(a,p),l=new Ty,a.zIndex=1,l.zIndex=5):(n.resources.nodes.set(d,/* @__PURE__ */new Set([t])),n.resources.texture.set(d,{textureUrl:h,applyFilter:p}),xb({loader:n,view:s,resourceId:d}),a=new Ty),[a,l]}(t,e,i);o=s[0],a=s[1]}else o=function(t,e,i,s){const{settings:r}=i,n=Eb(t,e),o=Zl(t);n.push(...o);const a=new Ty,l=nh({element:t,settings:r,style:s});for(const h of n)gb({shape:h,settings:r,gfx:a,style:l});return a}(t,e,i,s);else{const r=Pb(t,e,i,s);o=r[0],l=r.slice(1)}!function(t,e,i){if(!Wn(t))return;const s=t.parent&&t.parent.id!==i?.name?t.getWorldTransform():t.getTransform();e.x=s.position[0]*Ex,e.y=s.position[2]*Ex,e.rotation=-Math.PI/180*s.rotation||0}(t,e,n),!r&&o&&function(t,e,i,s){s.gfxNodes[t.id]=e,i.eventMode="static";let r=t.id;"element"in t&&t.element&&(r=t.element.id),i._nodeId=r}(t,e,o,h),o&&e.addChild(o),a&&e.addChild(a);for(const u of l)u&&e.addChild(u)}function Ab(t,e,{ctx:i,style:s,container:r,preview:n}){const{view:o,settings:a}=e;if(!t?.spaceGraph)return;let l;n||(s?o.styleCache[t.id]=s:!1===s?delete o.styleCache[t.id]:s=o.styleCache[t.id]),r?(l=r,cb(l)):l=new qg;const h=a.hideElements.includes(t.type)||"spatialGraph:edge"===t.type&&!a.showSpaceDividers||"element:spaceDivider"===t.type||"annotation:floorPlanImage"===t.type&&!a.showFloorPlan||"element:asset"===t.type&&"product"in t&&t.product?.attributes?.subCategories?.includes("ceilingLight")&&!a.showCeilingLamps||"space"in t||("element:window"===t.type||"element:door"===t.type)&&!t.parent||e.computed.wallContours.length&&["element:wall","element:boundaryWall","element:column","spatialGraph:edge"].includes(t.type),u=th(t.type);if(l.zIndex=u||0,l.name=t.id,h||Tb(t,l,e,s,n,i),t&&"elements"in t){t.elements.length&&(l.sortableChildren=!0);for(const i of t.elements)Ab(i,e,{ctx:l,style:s,preview:n})}r||i.addChild(l),o.viewportNeedsUpdate=!0}function Ib(t,e){const i=e.getChildByName(t);i?.destroy(!0)}function Sb(t,e,i,s){if(Ib(t.id,e),s.hideElements.includes("roomStamp"))return;const{text:r,textOutline:n=!0}=s.theme?.roomStamps||{},o=s.theme.background.color,a="transparent"!==o?o:"#eee",l=r?(h=r.map(t=>t/255),"#"+((255*h[0]<<16)+(255*h[1]<<8)+(255*h[2]|0)).toString(16).padStart(6,"0")):"#333333";var h;const u=new Ny({fontFamily:s.theme.fontFamily||Sl.theme.fontFamily,fontSize:16,align:"center",fill:l,stroke:a,strokeThickness:n?3:0});let p=t.geometry.polygons;if(0===p.length)return;let f=Pi(p),m=function(t,e){let i=t.getArea(),s=t.attributes.usage;if("void"===Ql(s))return[];let{roomStampDisplay:r}=e.theme?.roomStamps||{};const n=e.spaceLabelMapping||{};let o,a;switch(void 0!==n[s]&&(o=n[s]),void 0!==n[t.id]&&(o=n[t.id]),e.units?.roomDimensions){case"area":a=d(i,e.units.system,e.units.areaDecimals);break;case"boundingBox":{const{min:i,max:s}=t.getBoundingBox(),r=s[0]-i[0],n=s[2]-i[2];a=`${c(r,e.units.system,e.units.lengthDecimals)} x ${c(n,e.units.system,e.units.lengthDecimals)}`;break}default:a=""}let l="";l||"undefined"===s||(l=(s||"").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/^./,t=>t.toUpperCase()).trim()),void 0!==o&&("string"!=typeof o?Nl.warn("space label mapping has to be a string"):o.length>50?Nl.warn("space label mapping has to be less than 50 characters"):l=o),r||(r=[],t.layout.debugIds?r.push("id"):r.push("usage","area"));const h=[];return r.forEach(e=>{switch(e){case"id":let i=fl(t.id)?t.id.substring(0,4):t.id;h.push(i);break;case"name":t.name&&h.push(t.name);break;case"customId":t.customId&&h.push(t.customId);break;case"usage":h.push(l);break;case"area":h.push(a);break;default:Array.isArray(e)&&"customAttribute"===e[0]&&t.customAttributes[e[1]]&&h.push(String(t.customAttributes[e[1]]))}}),h}(t,s),g=m.join("\n");const y=new Fy(g,u);y.x=f[0]*Ex,y.y=f[1]*Ex,y.anchor.x=.5,y.anchor.y=.5,Cb(y,i,t),y.name=t.id,y.eventMode="none",e.addChild(y)}function Cb(t,e,i){let s=Math.min(1/e,2);t.scale.x=s,t.scale.y=s,t.visible=i.getArea()>1.5*s}function Mb(t="linear"){return Yy[t]}function Ob({bb:t,animate:e=!1,view:i}){const s=i._viewport;if(!s)throw new Error("no viewport");return s.destroyed||!s.transform?Promise.resolve(!1):(i.viewportPaused&&i.startAnimationLoop(),new Promise(r=>{if(!Number.isFinite(t.min?.[0]))return r(!1);const{min:n,max:o}=t;let a=n[0],l=n[1];let h=o[0]-a,u=o[1]-l;a*=Ex,l*=Ex,h*=Ex,u*=Ex;let c=0;"number"==typeof e&&Number.isFinite(e)?c=e:!0===e&&(c=500);let d={x:a+h/2,y:l+u/2,width:h,height:u};if(c){let t={x:s.center.x,y:s.center.y,width:s.worldScreenWidth,height:s.worldScreenHeight},e={x:t.x-d.x,y:t.y-d.y,width:t.width-d.width,height:t.height-d.height};i._zoomTarget={delta:e,start:t,target:d,time:0,duration:c,destroy:()=>{i.ticker.remove("animateView"),delete i._zoomTarget,r(!0)},ease:Mb("easeInOutQuad"),updateViewport:Lb.bind(i)},i.ticker.add("animateView",Nb,i)}else s.fit(!1,d.width,d.height).moveCenter(d.x,d.y),Lb.bind(i)({type:"animation"}),i.viewportNeedsUpdate=!0,r(!0)}))}function Nb(t){if(!this._viewport||this._viewport.destroyed||!this._viewport.transform)return void this._zoomTarget?.destroy();let e=this._zoomTarget,i=!1;e.time+=t;let s=e.ease(e.time,0,1,e.duration),r={x:e.start.x-e.delta.x*s,y:e.start.y-e.delta.y*s,width:e.start.width-e.delta.width*s,height:e.start.height-e.delta.height*s};e.time>e.duration&&(r=e.target,i=!0),this._viewport.fit(!1,r.width,r.height).moveCenter(r.x,r.y),this.viewportNeedsUpdate=!0,e.updateViewport({type:"animation"});const n=0!==this._viewport.input.count();(i||n)&&e.destroy()}function Lb(t){this.viewportNeedsUpdate=!0,this.viewportPaused&&this.startAnimationLoop(),"animation"!==t.type&&this._zoomTarget&&this._zoomTarget.destroy();const e=this._viewport,i=Ex,s=e.scale._x,r=e.left,n=e.top,o=e.worldScreenWidth,a=e.worldScreenHeight;this.viewbox={min:[r/i,n/i],max:[(r+o)/i,(n+a)/i]},this.client=[e.screenWidth,e.screenHeight];const l=this.zoom!==s;this.zoom=s;const h={sourceEvent:{type:t.type},viewbox:this.viewbox,zoom:this.zoom};l?this.emit("zoom",h):this.emit("pan",h),this.emit("viewbox",h)}function Rb({position:t,nodeId:e}){Bb(this.interaction,{cursor:t,cursorTarget:e&&this.layout&&(this.layout.elementsById[e]||this.layout.spacesById[e])})}function Bb(t,e){for(const i in e)t[i]=e[i],"cursorAction"===i&&kb(e[i])}function kb(t){let e="";switch(t){case"split-wall":e="var(--fpe-split-cursor) 16 16, pointer";break;case"duplicate":e="var(--fpe-duplicate-cursor) 16 16, pointer";break;case"move":e="move";break;default:e="default"}document.body.style.cursor=e}function Fb(t){if(2===t?.data?.originalEvent?.button)return;if(!this||!this.view)throw new Error("Viewport context is missing");let e=this.interaction._dragStart||{x:0,y:0},i=t.data.global||{x:0,y:0},s=Math.abs(i.x-e.x),r=Math.abs(i.y-e.y);if(!(s<5&&r<5))return;let n,o=/* @__PURE__ */(new Date).getTime();if(this.interaction.lastClick){let t=o-this.interaction.lastClick.time,e=this.interaction.lastClick.position&&Math.max(Math.abs(i.x-this.interaction.lastClick.position.x),Math.abs(i.y-this.interaction.lastClick.position.y));n=t<400&&e<10}this.interaction.lastClick={time:o,position:{...i}};const a=n?"dblclick":"click",l=t.target?._nodeId,{x:h,y:u}=t.data?.global||{},c=this.getPlanPosition([h,u]);Bb(this.interaction,{cursor:[c[0],c[1]]});let d={sourceEvent:t,nodeId:l,position:c,isDoubleClick:!!n};this.emit(a,d)}function Db(t){const{x:e,y:i}=t.data.global;this.view.windowPos=[e,i];const s=this.getPlanPosition(this.view.windowPos);this.interaction.lastSceneClick=s;const r=t.target?._nodeId;this.emit("context-menu",{sourceEvent:t,nodeId:r,position:s})}function Ub(t){t.drag().pinch({percent:4}).wheel()}function Gb(t){t.plugins.remove("wheel"),t.plugins.remove("pinch"),t.plugins.remove("drag")}function Xb(t){const{settings:e,view:i}=t;e.panZoom&&Ub(i._viewport),i._viewport.on("pointerdown",Wb,t).on("pointerup",Yb,t).on("pointerup",Fb,t).on("rightup",Db,t).on("pointerupoutside",Yb,t).on("globalpointermove",Hb,t).on("moved",Lb,i).on("zoomed",Lb,i);const s=$b(t),r=(t=>{const{view:e,interaction:i}=t,s=(s,r)=>{e.viewportInFocus&&("Alt"===s.key&&"keyup"===r&&i.preventFocusoutOnAltKeyup&&s.preventDefault(),i.shiftKey=s.shiftKey,i.ctrlKey=s.ctrlKey,i.altKey=s.altKey,i.metaKey=s.metaKey,t.emit(r,{key:s.key,lowerCaseKey:s.key&&s.key.toLowerCase(),sourceEvent:s}))},r=t=>s(t,"keyup"),n=t=>s(t,"key");return document.addEventListener("keydown",n),document.addEventListener("keyup",r),()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r)}})(t);return t.on("mousemove",Rb,t),()=>{e.panZoom&&Gb(i._viewport),i._viewport.destroyed||i._viewport.off("pointerdown",Wb).off("pointerup",Yb).off("pointerup",Fb).off("rightup",Db).off("pointerupoutside",Yb).off("globalpointermove",Hb).off("moved",Lb).off("zoomed",Lb),s?.(),r?.(),t.off("mousemove",Rb)}}function Wb(t){this.interaction._dragStart={x:t.data.global.x,y:t.data.global.y};const e=t.data.getLocalPosition(this.view._viewport);this.emit("drag-start",{position:this.interaction.cursor,sourceEvent:t,screenPos:[e.x,e.y]})}function Yb(t){this.view.resume("drag");const e=t.data.getLocalPosition(this.view._viewport);this.emit("drag-end",{position:this.interaction.cursor,sourceEvent:t,screenPos:[e.x,e.y]}),this.interaction.isDragging=!1,this.interaction.dragOffset=null}function Hb(t){const{srcElement:e}=t?.data?.originalEvent||{};if(!e||!this.view._renderer)return;if(!(e===this.view._renderer.view)&&!this.interaction.isDragging)return;const i=t.data.getLocalPosition(this.view._viewport);let s=[i.x/Ex,i.y/Ex];const r=t.target&&t.target._nodeId;if(this.interaction.cursor=s,this.interaction.isDragging){const e=[i.x,i.y];this.emit("drag-move",{position:this.interaction.cursor,screenPos:e,sourceEvent:t})}this.emit("mousemove",{sourceEvent:t,nodeId:r,position:s})}const $b=t=>{const e=document.querySelector(`#${t.fpeId} .fpe__plan`);if(!e)return()=>{};const i=()=>t.view.emit("focus",!1,t.view),s=()=>t.view.emit("focus",!0,t.view),r=()=>t.view.emit("focus","visible"===document.visibilityState,t.view),n=t=>(t.preventDefault(),!1);return e.addEventListener("mouseleave",i),e.addEventListener("mouseenter",s),document.addEventListener("visibilitychange",r),e.addEventListener("contextmenu",n,!1),()=>{e.removeEventListener("mouseleave",i),e.removeEventListener("mouseenter",s),document.removeEventListener("visibilitychange",r),e.removeEventListener("contextmenu",n,!1)}};const jb=t=>`floor-${t.id}`,zb=t=>`fpe-room-stamp-floor-${t.id.substring(0,8)}`;function Vb(t,e){t.x=e.position[0]*Ex,t.y=e.position[2]*Ex,t.rotation=-Math.PI/180*e.rotation||0}function qb(t,e,i,s){for(let r of e.spaces)Ab(r,t,i);for(let r of e.elements)Ab(r,t,i);for(let r of e.annotations)Ab(r,t,i);for(let r of e.spatialGraph.edges)Ab(r,t,i);t.computed.wallContours.length&&function(t,e){const{ctx:i,style:s}=e,{wallContours:r}=t.computed,n="wallContours",o=r.map(t=>({type:"curve:polygonWithHoles",polygons:t}));let a=i.getChildByName(n);a?cb(a):(a=new qg,a.name=n);const l=th("element:wall");a.zIndex=l||0;const h=nh({style:s,settings:t.settings,elementType:"element:wall"}),u=new Ty;for(const c of o)gb({shape:c,gfx:u,style:h});a.addChild(u),i.addChild(a)}(t,i),Zb(t,!0,s,e)}const Jb=t=>`fpe-room-stamp-${t.id.substring(0,8)}`;function Kb({floorPlan:t,update:e=!1}){const{layout:i,view:s,settings:r}=t,{_renderer:n,_viewport:o}=s;if(!n)return;let a=r.theme.background.color;4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),n.background.color=new hb(a).toNumber();const l=s.gfxLayers.scene;if(cb(l),e||(s.styleCache={}),s.floorContainers.clear(),s.roomStampLayers.clear(),t.building&&r.loadFloorLevel){const e=t.building.floorsByLevel[r.loadFloorLevel]||[];for(const i of e){const e=i.layouts[0];if(!e)continue;const r=new qg;r.name=jb(i),Vb(r,i),l.addChild(r),s.floorContainers.set(i.id,r);const n=t.addLayer({id:zb(i),baseLayer:"annotation"});Vb(n.container,i),s.roomStampLayers.set(i.id,n),qb(t,e,{ctx:r},n)}}else qb(t,i,{ctx:l});s.emit("scene-rendered",{update:e}),s.viewportNeedsUpdate=!0,e&&(r.panZoom?Ub(o):Gb(o)),s.viewportPaused&&s.startAnimationLoop()}function Zb(t,e=!1,i,s){const{view:r,settings:n}=t,o=s??t.layout;i??=t.addLayer({id:Jb(o),baseLayer:"annotation"}),e?(cb(i.container),o.spaces.forEach(t=>Sb(t,i.container,r.zoom,n))):i.container.children.forEach(t=>{let e=o.spaces.find(e=>e.id===t.name);Cb(t,r.zoom,e)})}function Qb(t){const{shapeLayers:e}=t.settings;for(const i in e){const s=e[i];t.addLayer({id:i}).addGraphic({shapes:s})}}Wp.add(um),Wp.add(ov),Wp.add(wv),Wp.add(Fv),Wp.add(Uv);class tw extends Px{}const ew=(t,e,i)=>{const s=t.getChildByName(e);if(s)return cb(s),s;{const s=new qg;return s.sortableChildren=!0,s.zIndex=i,s.name=e,t.addChild(s),s}},iw={top:0,left:0,center:.5,right:1,bottom:1};class sw{constructor(){this.methods={},this.add=(t,e,i)=>{this.methods[t]={fn:e,ctx:i}},this.remove=t=>{delete this.methods[t]}}}class rw extends Ix.TinyEmitter{constructor(t,e,i){super(),this.windowPos=[0,0],this.zoom=1,this.client=[0,0],this.layers=/* @__PURE__ */new Map,this.viewbox={min:[0,0],max:[0,0]},this.styleCache={},this.viewportNeedsUpdate=!1,this.viewportPaused=!1,this.viewportInFocus=!1,this.wallNodesToUpdate=[],this.wallNodeUpdateInProgress=!1,this.floorContainers=/* @__PURE__ */new Map,this.roomStampLayers=/* @__PURE__ */new Map,this.gfxNodes={},this._canvasMargin={x:0,y:0},this.ticker=new sw,this._resizeRafId=null,this._oldTime=Date.now(),this.parentEl=i;const s=this.parentEl.querySelector(".fpe__canvas");let r=this.parentEl.clientWidth,n=this.parentEl.clientHeight;this._settings=e;const o=window.devicePixelRatio||1;let a=e.theme.background.color;const l="transparent"===a;4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),this._renderer=function(t){for(const e of Ig)if(e.test(t))return new e(t);throw new Error("Unable to auto-detect a suitable renderer.")}({width:r,height:n,view:s,antialias:!0,hello:!1,backgroundAlpha:l?0:1,autoDensity:!0,resolution:o,powerPreference:"high-performance",preserveDrawingBuffer:!0,backgroundColor:l?new hb(a).toNumber():void 0}),this.parentEl.appendChild(this._renderer.view),4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),l||(this._renderer.background.color=new hb(a).toNumber()),this._stage=new qg,this._stage.sortableChildren=!0,this._viewport=new tw({screenWidth:r,screenHeight:n,worldWidth:r,worldHeight:n,events:this._renderer.events,noTicker:!0,passiveWheel:!1,allowPreserveDragOutside:!0}),Tg?.system&&Tg.system.stop(),this.startAnimationLoop(),this.watchResize(),this._stage.addChild(this._viewport),this.on("focus",t=>{t&&this.viewportPaused?this.startAnimationLoop():t||this.stopAnimationLoop(),this.viewportInFocus=t}),this.gfxLayers=nw(this._viewport),vb(this,t)}draw(){if(this.parentEl&&!this.parentEl.isConnected)return void this.destroy();if(!this._viewport||this._viewport?.destroyed||!this._renderer)return;const t=Date.now();let e=t-this._oldTime;this._oldTime=t,e<0&&(e=0),e>1e3&&(e=1e3);let i=Object.keys(this.ticker.methods).length;(this.viewportNeedsUpdate||i)&&(this.ticker?.methods&&Object.values(this.ticker.methods).forEach(({fn:t,ctx:i})=>{"function"==typeof t&&(i?t.call(i,e):t(e))}),this._viewport.update(e),this._renderer.render(this._stage)),this.viewportPaused||requestAnimationFrame(()=>this.draw()),this.viewportNeedsUpdate=!1}startAnimationLoop(){this._oldTime=Date.now(),this.viewportNeedsUpdate=!0,this.viewportPaused=!1,requestAnimationFrame(()=>this.draw())}stopAnimationLoop(){this.viewportPaused=!0}updateView(){if(this._viewport?.destroyed||!this._renderer)return;if(!this.parentEl.clientWidth||!this.parentEl.clientHeight)return;const t=this._viewport,e=this._renderer,i=Ex,s=t.screenWidth,r=t.screenHeight,n=this.parentEl.clientWidth-this._canvasMargin.x,o=this.parentEl.clientHeight-this._canvasMargin.y;e.resize(n,o),t.resize(n,o);const a=this._settings.preserveViewbox;if("screen-space"===a&&this._lastCanvasRect){const e=this.parentEl.getBoundingClientRect(),i=e.left-this._lastCanvasRect.left,s=e.top-this._lastCanvasRect.top;t.position.set(t.x-i,t.y-s),this._lastCanvasRect=e}else{const e=s-n,i=r-o,[l=.5,h=.5]=a.split("-").map(t=>iw[t]),u=l*e,c=h*i;t.position.set(t.x-u,t.y-c)}t.plugins.get("clamp-zoom")||t.clampZoom({minHeight:this._settings.zoomRange[0]*i,maxHeight:this._settings.zoomRange[1]*i}),e.render(this._stage);let l=t.left,h=t.top,u=t.worldScreenWidth,c=t.worldScreenHeight;this.viewbox={min:[l/i,h/i],max:[(l+u)/i,(h+c)/i]},this.client=[t.screenWidth,t.screenHeight]}async watchResize(){this._canvasMargin.x=this.parentEl.clientWidth-this._viewport.screenWidth,this._canvasMargin.y=this.parentEl.clientHeight-this._viewport.screenHeight,"screen-space"===this._settings.preserveViewbox&&(this._lastCanvasRect=this.parentEl.getBoundingClientRect()),this._resizeObserver=new ResizeObserver(()=>{null===this._resizeRafId&&(this.updateView(),this._resizeRafId=requestAnimationFrame(()=>{if(this._resizeRafId=null,!this.parentEl)return;const t=this.parentEl.clientWidth-this._canvasMargin.x,e=this.parentEl.clientHeight-this._canvasMargin.y;t===this._viewport.screenWidth&&e===this._viewport.screenHeight||(this.updateView(),this.emit("resize-canvas",this.viewbox))}))}),this._resizeObserver.observe(this.parentEl)}get gfxNodeCount(){return Object.keys(this.gfxNodes).length}reset(){this.styleCache={},this.gfxNodes={},this.floorContainers.clear(),this.roomStampLayers.clear(),this.gfxLayers=nw(this._viewport)}pause(t="drag"){this._viewport.plugins.pause(t)}resume(t="drag"){this._viewport.plugins.resume(t)}destroy(){this.stopAnimationLoop(),null!==this._resizeRafId&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=null),this._resizeObserver?.disconnect(),this._viewport&&!this._viewport.destroyed&&this._viewport.destroy(),this._renderer?.destroy(!0),this._renderer=void 0}}const nw=t=>{t.sortableChildren=!0;return{base:ew(t,"base",0),scene:ew(t,"scene",1),preview:ew(t,"preview",2),annotation:ew(t,"annotation",3),helper:ew(t,"helper",4)}};function ow(t,e,i){e=e||this;const{view:s,settings:r}=e,n=s.gfxNodes[t.id];if(n&&!n.destroyed){if("layout:space"===t.type){const e=Jb(t.layout),i=s.layers.get(e);i&&Sb(t,i.container,s.zoom,r)}Ab(t,e,{ctx:n.parent,container:n,...i}),s.viewportNeedsUpdate=!0,s.viewportPaused&&s.startAnimationLoop()}}class aw{constructor({shapes:t=[],position:e=[0,0],alpha:i=1,scale:s=1,clearLayer:r=!1,interactive:n=!1,id:o,isHandler:a=!1,scaleOnZoom:l=!1,updatePositionOnDrag:h=!1,baseLayer:u,container:c,floorPlan:d}){if(this.shapes=t,this.gfxScale=s,this.scaleOnZoom=l,this.container=c,this.floorPlan=d,!this.container)return;r&&cb(this.container);let p=new Ty;this.gfx=p,p.alpha=i;const f=Math.min(1/this.floorPlan.view.zoom)*this.gfxScale;e&&(p.x=e[0]*Ex,p.y=e[1]*Ex),p.eventMode=n?"static":"none",p._nodeId=o,a&&(p._isHandler=!0),h&&this.on("drag",this.doUpdatePositionOnDrag,this),f&&l&&(p.scale.x=p.scale.y=f),u.addChild(this.container),this.container.addChild(p),t.forEach(t=>gb({shape:t,settings:this.floorPlan.settings,gfx:p})),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}set({position:t,rotation:e,style:i,shapes:s}={}){const r=Math.min(1/this.floorPlan.view.zoom)*this.gfxScale,n=this.gfx;if(function(t,{position:e,rotation:i}){e&&(t.x=e[0]*Ex,t.y=e[1]*Ex),i&&(t.rotation=-Math.PI/180*i)}(n,{position:t,rotation:e}),s&&(this.shapes=s,n.clear(),cb(n),s.forEach(t=>gb({shape:t,settings:this.floorPlan.settings,gfx:n}))),r&&this.scaleOnZoom&&(n.scale.x=n.scale.y=r),i){const t=mb(i);i.fill&&(n.geometry.graphicsData[0].fillStyle.color=eh(i.fill)),n.geometry.graphicsData[0].lineStyle.color=Number(t.color),n.geometry.graphicsData[0].lineStyle.width=t.width,n.geometry.graphicsData[0].lineStyle.native=t.native,n.geometry.invalidate()}this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}doUpdatePositionOnDrag({position:t}){this.set({position:t})}on(t,e,i){return this.gfx.eventMode="static","drag"===t?this.addDragEvent(e,i):this.gfx.on(t,e,i),this}off(t,e){return"drag"===t?this.removeDragEvent():this.gfx.off(t,e),this}destroy(){this.off("drag"),this.gfx.destroy(),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}addDragEvent(t,e){function i(){this.floorPlan.interaction.isDragging=!1,this.floorPlan.view.resume("drag"),this.floorPlan.off("mousemove",t)}this.on("pointerdown",function(){this.floorPlan.interaction.isDragging=!0,this.floorPlan.view.pause("drag"),this.floorPlan.on("mousemove",t,e)},this),this.on("pointerup",i,this),this.on("pointerupoutside",i,this),this.on("pointercancel",i,this)}removeDragEvent(){this.off("pointerdown"),this.off("pointerup"),this.off("pointerupoutside"),this.off("pointercancel")}}class lw{constructor(t,e,i){this.graphics=/* @__PURE__ */new Set,this.container=new qg,this.id=i,this.baseLayer=t.view.gfxLayers[e]||t.view.gfxLayers.helper,this.floorPlan=t,this.baseLayer.addChild(this.container)}addGraphic(t){const e=new aw({...t,floorPlan:this.floorPlan,baseLayer:this.baseLayer,container:this.container});return this.graphics.add(e),e}findGraphic(t){return this.container.getChildByName(t)}deleteGraphic(t){this.graphics.delete(t),t.destroy()}clear(){cb(this.container),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}destroy(){this.container&&(this.floorPlan.view.layers.delete(this.id),this.container.destroy({children:!0,texture:!0,baseTexture:!0}),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop(),delete this.container,delete this.floorPlan)}}function hw(t,{format:e,fileName:i,quality:s}={}){if("svg"===e)return;const r=new Image;r.src=t,r.onload=function(){const t=document.createElement("canvas");t.width=r.naturalWidth,t.height=r.naturalHeight;const n=t.getContext("2d");n.imageSmoothingEnabled=!1,n.drawImage(r,0,0),function(t,{format:e="png",fileName:i="floorplan",quality:s=.95}){let r="png"===e?"image/png":"image/jpeg";t.toBlob(function(t){!function({fileName:t,href:e,ext:i}){const s=document.createElement("a");Object.assign(s,{href:e,download:p(t,i),target:"_blank",rel:"noopener",style:"display:none;"}),document.body.appendChild(s),s.click(),document.body.removeChild(s)}({fileName:i,href:URL.createObjectURL(t),ext:e})},r,s)}(t,{format:e,fileName:i,quality:s})}}const uw=Tl,cw=Tl,dw=Tl,pw=Tl,fw=Tl,mw=gl;class gw extends Sx{constructor({floorPlan:t,helperId:e,mode:i="distance"}){super({floorPlan:t,helperId:e}),this.drawing=!1,this.polygonsOrPolylines=[],this.floorPlan=t,this.mode=i,this.floorPlan.on("mousemove",this.handlePointerMove,this),this.floorPlan.on("click",this.handlePointerDown,this),this.floorPlan.on("dblclick",this.handlePointerDown,this),this.floorPlan.on("update-settings",this.draw,this),this.startDrawing()}get isInAreaMode(){return"area"===this.mode}get isDrawing(){return this.drawing}set({mode:t}){this.mode=t,this.draw()}handlePointerMove(t){this.setSnapCursor(t)}handlePointerDown(t){this.setSnapCursor(t),this.drawPoint(t)}setSnapCursor({position:t}){this._snapCursor??=this.floorPlan.addHelper("snapCursor",{position:t});const{snapPoints:e,snapMargin:i}=this.floorPlan.computed;if(!e.length)return this._snapCursor.set({position:t}),void this.draw();const s=uh(t,e,i);this._snapCursor.isSnapping=!!s,this._snapCursor.set({position:s||t}),this.draw()}stopDrawing(){this.polygonsOrPolylines[this.polygonsOrPolylines.length-1].points.length>1&&this.drawing&&this.polygonDone()}cancelDrawing(){this.destroy()}startDrawing(){this.drawing=!0,this.polygonsOrPolylines.push({points:[],isClosed:!1,length:0,area:0,areaDisplay:"",lengthDisplay:"",contour:null,label:null,pointGraphics:[]})}removeLastPoint(){const t=this.polygonsOrPolylines[this.polygonsOrPolylines.length-1];if(t?.points.length>0){t.points.pop();const e=t.pointGraphics.pop();e&&this.layer.deleteGraphic(e),t.points.length<=1&&(t.contour&&(this.layer?.deleteGraphic(t.contour),t.contour=null),t.label&&(this.layer?.deleteGraphic(t.label),t.label=null)),0===t.points.length?(this.polygonsOrPolylines.pop(),this.drawing=!1):this.draw()}}polygonDone(){this.drawing=!1,this.emit("polygon-done",{}),this.draw()}drawPoint(t){this.drawing||this.startDrawing();const e=this.polygonsOrPolylines.length-1,i=this.polygonsOrPolylines[e],s=t.nodeId?.startsWith(`point/${e}/`);if(s||t.isDoubleClick){const s=t.nodeId===`point/${e}/0`;return"distance"===this.mode&&s&&(i.isClosed=!0),void this.polygonDone()}const{position:r}=this._snapCursor;i.points.push([...r]);const n=i.points.length-1,o=`point/${e}/${n}`;this.layer||(this.layer=this.floorPlan.addLayer());const a=this.layer.addGraphic({shapes:[{type:"curve:circle",position:[0,0],radius:.15,style:{fill:pw,fillOpacity:.1}},{type:"curve:circle",position:[0,0],radius:.05,style:{stroke:fw,fill:mw,strokeWidth:1.5}}],position:r,scaleOnZoom:!0,id:o,isHandler:!0});i.pointGraphics[n]=a,a.on("drag",function(){this.updatePolygon(e,n,this.floorPlan.interaction.cursor),a.set({position:i.points[n]})},this)}updatePolygon(t,e,i){const s=i,{snapPoints:r,snapMargin:n}=this.floorPlan.computed,o=r.length&&uh(s,r,n);this.polygonsOrPolylines[t].points[e]=o||s,this.draw()}getLengthText(t){const{units:e}=this.floorPlan.settings;return c(t,e.system,e.lengthDecimals)}getAreaText(t){const{units:e}=this.floorPlan.settings;return d(t,e.system,e.areaDecimals)}reset(){this.drawing=!1,this.polygonsOrPolylines=[],this.floorPlan.removeHelper("snapCursor"),this._snapCursor=null,this.layer&&(this.layer.destroy(),this.layer=null)}draw(){this.polygonsOrPolylines.length&&(this.layer||(this.layer=this.floorPlan.addLayer()),this.polygonsOrPolylines.forEach((t,e)=>{if(!t.points.length)return;const i=this.drawing&&this._snapCursor&&e===this.polygonsOrPolylines.length-1?[...t.points,this._snapCursor.position]:t.points;if(i.length<2)return;t.length=function(t,e=!0){let i=0,s=e?t.length:t.length-1;for(var r=0;r<s;r++){let e=r,s=r<t.length-1?r+1:0;i+=ni(t[e],t[s])}return i}(i,t.isClosed),t.lengthDisplay=this.getLengthText(t.length);const s=i.length<2?0:180*gi(i[0],i[1])/Math.PI,r=i.map(t=>t.map(t=>Number(t.toFixed(10)))).slice(0,this.isInAreaMode?void 0:2),n=this.isInAreaMode?Pi([r]):[r[0][0]+(r[1][0]-r[0][0])/2,r[0][1]+(r[1][1]-r[0][1])/2];t.area=Math.abs(J(i)),t.areaDisplay=this.getAreaText(t.area);const o=this.isInAreaMode||t.isClosed?"curve:polygon":"curve:polyline",a={stroke:dw,dash:!0,strokeWidth:"native"};let l=t.lengthDisplay,h=-s;this.isInAreaMode&&(a.fill=cw,a.fillOpacity=.04,l=t.areaDisplay,h=0);const u=[{type:o,points:i,style:a}],c={shapes:[{type:"text",text:l,position:[0,0],rotation:h,alignV:"bottom",fontSize:15,style:{fill:uw}}],id:"text",position:n,scaleOnZoom:!0};t.contour?t.contour.set({shapes:u}):t.contour=this.layer.addGraphic({shapes:u}),t.label?t.label.set(c):t.label=this.layer.addGraphic(c);const d=this.isInAreaMode?{area:t.area}:{distance:t.length};this.emit("polygon-draw",d)}))}destroy(){this.reset(),this.floorPlan.off("mousemove",this.handlePointerMove),this.floorPlan.off("click",this.handlePointerDown),this.floorPlan.off("dblclick",this.handlePointerDown),this.floorPlan.off("update-settings",this.draw),super.destroy()}}class yw extends Sx{constructor({floorPlan:t,helperId:e,position:i}){super({floorPlan:t,helperId:e}),this.position=[0,0],this.floorPlan.on("mousemove",this.draw,this),this.isSnapping=!1,this.isEdge=!1,this.isError=!1,i&&(this.position=i)}draw(){if(this.floorPlan)if(this.layer||(this.layer=this.floorPlan.addLayer({id:"fpe-snap-cursor"})),this.cursor){let t=vl;this.isError?t=Il:this.isSnapping&&(t=Tl);const e=this.isSnapping?2:1.5;this.cursor.set({position:this.position,style:{stroke:t,strokeWidth:e}})}else this.cursor=this.layer.addGraphic({shapes:[{type:"curve:circle",position:[0,0],radius:.06,style:{stroke:Tl,strokeWidth:1.5}}],position:this.position,scaleOnZoom:!0})}set({position:t,isSnapping:e,isEdge:i,isError:s}){this.position=t,this.isSnapping=e,this.isEdge=i,this.isError=s,this.draw()}snapState(){return this.isSnapping?this.isEdge?"edge":"point":""}destroy(){this.floorPlan?.off("mousemove",this.draw),this.layer&&this.layer.destroy(),this.layer=void 0,this.cursor=null,super.destroy()}}function vw(t,e){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: node ID change, type ${t.type}, previous ID ${e}`),this.drawNodeUpdate(t.id))}function xw(t,e){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: node property change, type ${t.type}, property name ${e}`),this.drawNodeUpdate(t.id))}function bw(t){this.preventUpdateOnSpaceGraphEvent||Nl.debug(`${t.id}: vertex create`)}function ww(t){this.preventUpdateOnSpaceGraphEvent||Nl.debug(`${t.id}: vertex delete`)}function _w(t){if(!this.preventUpdateOnSpaceGraphEvent){Nl.debug(`${t.id}: vertex set position`);for(let e of t.edges)this.drawNodeUpdate(e.id)}}function Pw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: edge create`),this.drawNodeUpdate(t.id))}function Ew(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: edge delete`),this.drawNodeUpdate(t.id))}function Tw(t,e){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: edge set vertices`),this.drawNodeUpdate(t.id))}function Aw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: space create`),this.drawNodeUpdate(t.id))}function Iw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: space delete`),this.drawNodeUpdate(t.id))}function Sw(t,e){this.preventUpdateOnSpaceGraphEvent||Nl.debug(`${t.id}: space split into ${e[0].id} and ${e[1].id}`)}function Cw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: space attributes change`),this.drawNodeUpdate(t.id))}function Mw(t){this.preventUpdateOnSpaceGraphEvent||"layout:space"!==t.type||(Nl.debug(`${t.id}: custom attributes change`),this.drawNodeUpdate(t.id))}function Ow(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: element create, type ${t.type}`),this.drawNodeUpdate(t.id))}function Nw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: element delete, type ${t.type}`),this.drawNodeUpdate(t.id))}function Lw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: element transform change, type ${t.type}`),this.drawNodeUpdate(t.id))}function Rw(t){if(!this.preventUpdateOnSpaceGraphEvent)if(Nl.debug(`${t.id}: element parameters change, type ${t.type}`),"element:wall"===t.type){let e=t.getAdjacentElementsByVertex().flat();if(this.view.wallNodesToUpdate.push(t.id,...e.map(t=>t.id)),this.view.wallNodeUpdateInProgress)return;this.view.wallNodeUpdateInProgress=!0,setTimeout(()=>{const t=new Set(this.view.wallNodesToUpdate);Ia(this.layout);for(const e of t)this.drawNodeUpdate(e);this.view.wallNodeUpdateInProgress=!1,this.view.wallNodesToUpdate=[]})}else Br(t),this.drawNodeUpdate(t.id)}function Bw(t){this.preventUpdateOnSpaceGraphEvent||queueMicrotask(()=>this.drawNodeUpdate(t.id))}function kw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: annotation change, type ${t.type}`),this.drawNodeUpdate(t.id))}function Fw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: geometry profile update`),this.drawNodeUpdate(t.id))}function Dw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: geometry update`),["element:boundaryWall","element:generic"].includes(t.type)&&this.drawNodeUpdate(t.id))}function Uw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: floor transform change`),function(t,e){const{view:i}=t,s=i.floorContainers.get(e.id),r=i.roomStampLayers.get(e.id);s&&!s.destroyed&&Vb(s,e),r?.container&&!r.container.destroyed&&Vb(r.container,e),i.viewportNeedsUpdate=!0}(this,t))}function Gw(t){const e=t.addLayer({id:"fpe-grid-lines",baseLayer:"base"});let i;function s(t,e,s=!1){const r=Ex;if(!t)return;let n;if(n=e.view.zoom>2?.1:e.view.zoom>.25?1:(e.view.zoom,10),!s&&n===i)return;if(cb(t),!e.settings.theme.background.showGrid)return;const o=new Ty;let a=eh(Pl);o.lineStyle({width:1,color:a,native:!0});for(let i=-100;i<100;i+=n)Math.round(100*i)/100==0?o.lineStyle({width:2,color:a,native:!0}):(Math.round(100*i)/100%10==0||Math.round(100*i),o.lineStyle({width:1,color:a,native:!0})),o.moveTo(-1e4,i*r),o.lineTo(1e4,i*r),o.moveTo(i*r,-1e4),o.lineTo(i*r,1e4);t.addChild(o),i=n}return s(e?.container,t),{update:i=>s(e.container,t,i)}}function Xw(t,e="Floor plan engine couldn't load properly on this page. For technical details check the browser console."){const i=t.querySelector(".fpe-err")??function(t){const e=document.createElement("div"),i=document.createElement("div"),s=document.createElement("div"),r=document.createElement("div");return e.classList.add("fpe-err"),i.classList.add("fpe-err__box"),s.classList.add("fpe-err__title"),r.classList.add("fpe-err__msg"),t.append(e),e.append(i),i.append(s),i.append(r),s.textContent="Something went wrong",t.append(e),t}(t);i.querySelector(".fpe-err__msg").textContent=e}const Ww={lastSceneClick:[0,0],cursor:[0,0],cursorTarget:null,isDragging:!1,altKey:!1,shiftKey:!1,metaKey:!1,ctrlKey:!1,dragOffset:null,cursorAction:"none",isPanning:!1,lastClick:{time:null,position:{x:0,y:0}},_dragStart:{x:0,y:0},preventFocusoutOnAltKeyup:!1};class Yw extends Jl{constructor({container:t,options:e={}}={}){let i;super({options:e}),this.interaction=Ww,this.availableHelpers={cursorCoordinates:Cx,scaleBar:Mx},this.helper={},this.preventUpdateOnSpaceGraphEvent=!1,this.#t=Sl.theme.fontFamily,i=t instanceof Element?t:document.body,this.mountFloorPlan(i),this.availableHelpers.polygonHelper=gw,this.availableHelpers.snapCursor=yw,this.on("space-api-floor-error",(t,e)=>{Xw(this.fpeNode,e)}),this.on("space-api-floor-loaded",()=>{!function(t){t.querySelector(".fpe-err")?.remove()}(this.fpeNode)})}#t;#e;prevent(t){t.preventDefault()}on(t,e,i){return this._emitter.on(t,e,i),this}once(t,e,i){return this._emitter.once(t,e,i),this}off(t,e,i){return this._emitter.off(t,e),this}emit(t,...e){return this._emitter.emit(t,...e),this}handleDrop(t){t.preventDefault(),t.stopPropagation();const e=[t.offsetX,t.offsetY],i=this.getPlanPosition(e);this.interaction.cursor=[...i];const{spaces:s}=this.getResourcesFromPosition(i),r=s[0]?.slabs.find(t=>"element:floor"===t.type),n=r?.parameters.elevation||0;this.emit("drop",{position:i,sourceEvent:t,verticalPos:n,screenPos:e})}set(t){super.set(t),this.view&&(Kb({floorPlan:this,update:!0}),Qb(this),Gw(this))}drawNodePreview(t,e,i,s){Ab(e?.elementsById[t]||e?.spacesById[t]||e?.spatialGraph.edgesById[t],this,{preview:!0,style:s,ctx:i.container})}#i(t){let e=this.layout?.elementsById[t]||this.layout?.spacesById[t]||this.layout?.annotationsById[t]||this.layout?.spatialGraph.edgesById[t];if(!e&&this.building&&this.settings.loadFloorLevel){const i=this.building.floorsByLevel[this.settings.loadFloorLevel]||[];for(const s of i){const i=s.layouts[0];if(i&&(e=i.elementsById[t]||i.spacesById[t]||i.annotationsById[t]||i.spatialGraph.edgesById[t],e))break}}return e}drawNodeUpdate(t,e){if(!this.layout)return;let i=this.#i(t);if(function(t,e){const i=t.settings?.theme?.byFilter,s=t.settings?.theme?.byResolvedFilter;if(i&&s&&t.layout){delete s[e];for(const r of i)Va(t.layout,{id:e,where:r.where})&&"style"in r&&(s[e]=r.style)}}(this,t),i)if(this.view.gfxNodes[t]&&!this.view.gfxNodes[t].destroyed)ow(i,this,{style:e});else{let t=this.view.gfxLayers.scene;"parent"in i&&this.view.gfxNodes[i.parent?.id]&&(t=this.view.gfxNodes[i.parent.id]),Ab(i,this,{ctx:t,style:e})}else!function(t,e){const i=e.view.gfxNodes[t];i&&(i.parent?.removeChild(i),i.destroy({children:!0})),delete e.view.gfxNodes[t],delete e.view.styleCache[t];const s=Jb(e.layout),r=e.getLayer(s);r?.container&&Ib(t,r.container),e.view.viewportNeedsUpdate=!0,e.view.viewportPaused&&e.view.startAnimationLoop()}(t,this);if(i&&"getEdges"in i)for(const s of i.getEdges())this.drawNodeUpdate(s.id,e)}drawResourceUpdate({resourceId:t}){const e=this.loader.resources.nodes.get(t);if(e)for(const i of e)ow(i,this,{})}mountFloorPlan(t){const e=t.querySelector(".fpe");e&&e.remove();const i=document.createElement("div");i.id=this.fpeId,i.classList.add("fpe"),t.appendChild(i);const s=document.createElement("div");s.classList.add("fpe__plan");const r=document.createElement("canvas");r.setAttribute("alt","fpe-canvas"),r.classList.add("fpe__canvas"),i.appendChild(s),s.appendChild(r),this.fpeNode=i;try{i.style.setProperty("--fpe-font-family",this.settings.theme.fontFamily)}catch(n){console.warn("Failed to set font-family",n)}this.view=new rw(this.loader,this.settings,s),this.loader.on("resource-loaded",this.drawResourceUpdate,this),this.loader.on("spaces-loaded",this.initDrawing,this),r.addEventListener("drop",this.handleDrop.bind(this)),r.addEventListener("gesturestart",this.prevent),r.addEventListener("gesturechange",this.prevent),r.addEventListener("gestureend",this.prevent),r.addEventListener("dragover",this.prevent),this.settings.destroyOnDomRemove&&function(t,e,i){const s=new MutationObserver(()=>{(function t(i){return i.parentNode!==e&&(null===i.parentNode||t(i.parentNode))})(t)&&(s.disconnect(),i())});s.observe(e,{childList:!0,subtree:!0})}(i,t,()=>this.destroy()),this.#e=Xb(this),this.view.on("scene-rendered",({update:t})=>{t||this.zoomExtents(1,0)}),this.view.on("zoom",()=>{if(this.view.layers.forEach(t=>{t.graphics.forEach(t=>{t.scaleOnZoom&&!t.gfx.destroyed&&t.set()})}),this.building&&this.settings.loadFloorLevel){const t=this.building.floorsByLevel[this.settings.loadFloorLevel]||[];for(const e of t){const t=e.layouts[0],i=this.view.roomStampLayers.get(e.id);t&&i&&Zb(this,!1,i,t)}}else Zb(this);Gw(this)}),this.view&&Gw(this),this.#s(this.settings.theme.fontFamily),this.on("update-settings",t=>{this.#s(t.theme.fontFamily)}),this.generateUi()}initDrawing(){!this.loader.initialLoading&&this.view.gfxLayers?.scene&&cb(this.view.gfxLayers.scene),Kb({floorPlan:this}),Qb(this),this.initDrawingEvents()}initDrawingEvents(){this.spaceGraph&&(this.spaceGraph.on("node-id-change",vw,this),this.spaceGraph.on("node-property-change",xw,this),this.spaceGraph.on("node-custom-attributes-change",Mw,this),this.spaceGraph.on("vertex-create",bw,this),this.spaceGraph.on("vertex-delete",ww,this),this.spaceGraph.on("vertex-set-position",_w,this),this.spaceGraph.on("edge-create",Pw,this),this.spaceGraph.on("edge-delete",Ew,this),this.spaceGraph.on("edge-set-vertices",Tw,this),this.spaceGraph.on("space-create",Aw,this),this.spaceGraph.on("space-delete",Iw,this),this.spaceGraph.on("space-split",Sw,this),this.spaceGraph.on("space-attributes-change",Cw,this),this.spaceGraph.on("element-create",Ow,this),this.spaceGraph.on("element-delete",Nw,this),this.spaceGraph.on("element-transform-change",Lw,this),this.spaceGraph.on("element-parameters-change",Rw,this),this.spaceGraph.on("element-edges-change",Bw,this),this.spaceGraph.on("geometry-profile-update",Fw,this),this.spaceGraph.on("geometry-update",Dw,this),this.spaceGraph.on("annotation-transform-change",kw,this),this.spaceGraph.on("annotation-parameters-change",kw,this),this.spaceGraph.on("floor-transform-change",Uw,this))}freeDrawingEvents(){this.spaceGraph&&(this.spaceGraph.off("node-id-change",vw),this.spaceGraph.off("node-property-change",xw),this.spaceGraph.off("vertex-create",bw),this.spaceGraph.off("vertex-delete",ww),this.spaceGraph.off("vertex-set-position",_w),this.spaceGraph.off("edge-create",Pw),this.spaceGraph.off("edge-delete",Ew),this.spaceGraph.off("edge-set-vertices",Tw),this.spaceGraph.off("space-create",Aw),this.spaceGraph.off("space-delete",Iw),this.spaceGraph.off("space-split",Sw),this.spaceGraph.off("space-attributes-change",Cw),this.spaceGraph.off("element-create",Ow),this.spaceGraph.off("element-delete",Nw),this.spaceGraph.off("element-transform-change",Lw),this.spaceGraph.off("element-parameters-change",Rw),this.spaceGraph.off("geometry-profile-update",Fw),this.spaceGraph.off("geometry-update",Dw),this.spaceGraph.off("annotation-transform-change",kw),this.spaceGraph.off("annotation-parameters-change",kw),this.spaceGraph.off("floor-transform-change",Uw))}generateUi(){this.settings.ui.coordinates?this.addHelper("cursorCoordinates",{parentEl:this.fpeNode}):this.helper.cursorCoordinates&&this.removeHelper("cursorCoordinates"),this.settings.ui.scale?this.addHelper("scaleBar",{parentEl:this.fpeNode}):this.helper.scaleBar&&this.removeHelper("scaleBar")}getZoomExtentsBoundingBox(t,e,i,s,r,n,o){return function({layoutBoundingBox:t,rectLeft:e,rectTop:i,rectRight:s,rectBottom:r,viewportWidth:n,viewportHeight:o}){if([e,i,s,r].some(t=>t>0)&&n&&o){const a=s-e,l=r-i,h=function(t,e,i){const{min:s,max:r}=t;let n=s[0],o=s[1],a=r[0],l=r[1],h=a-n,u=l-o;const c=e/i;if(h/u>c){const t=u;u=h/c;const e=(t-u)/2;o+=e,l-=e}else{const t=h;h=u*c;const e=(t-h)/2;n+=e,a-=e}return{min:[n,o],max:[a,l]}}(t,a,l);let{min:u,max:c}=h,d=u[0],p=u[1],f=c[0]-d,m=c[1]-p;return f*=n/a,m*=o/l,d-=e/n*f,p-=i/o*m,{min:[d,p],max:[d+f,p+m]}}return t}({layoutBoundingBox:t,rectLeft:e,rectTop:i,rectRight:s,rectBottom:r,viewportWidth:n,viewportHeight:o})}zoomExtents(t=1,e=!1,i=null){return function({margin:t=0,animate:e,floorPlan:i,boundingBox:s}){return i.view.gfxLayers.scene?Ob(s?{bb:s,animate:e,view:i.view}:{bb:i.getBoundingBox(t),animate:e,view:i.view}):Promise.resolve(!1)}({margin:t,animate:e,floorPlan:this,boundingBox:i})}zoomToElement(t,e=1,i){let s;if("string"==typeof t){const e=t;s=this.layout.elementsById[e]||this.layout.spacesById[e]||this.layout.spatialGraph.edgesById[e]||null}else s=t;if(!s)return Promise.resolve(!0);const{min:[r,n,o],max:[a,l,h]}=s.getAxisAlignedBoundingBox();return Ob({bb:{min:[r-e,o-e],max:[a+e,h+e]},animate:i,view:this.view})}setZoom(t,e=!0){return Ob({bb:t,animate:e,view:this.view})}zoomByFactor(t,e=!0){if(!Number.isFinite(t)||t<=0)return Promise.reject("factor is not a positive number");let{min:i,max:s}=this.view.viewbox,r=i[0],n=i[1],o=s[0]-r,a=s[1]-n;const l=o/t,h=a/t;r-=(l-o)/2,n-=(h-a)/2;const u=r+l,c=n+h;return this.setZoom({min:[r,n],max:[u,c]},e)}addInfoWindow(t={}){return new Lx({...t,floorPlan:this})}addHtmlMarker(t={}){return new Rx({...t,floorPlan:this})}addMarker({position:t=[0,0],color:e="#669cff",size:i=40}={}){return new ub({position:t,color:e,size:i,floorPlan:this})}getPlanPosition(t){if(!this.view._viewport||this.view._viewport.destroyed)throw Error("No viewport present");const e=this.view._viewport.toWorld(t[0],t[1]);return[e.x/Ex,e.y/Ex]}getScreenPosition(t){if(!this.view._viewport||this.view._viewport.destroyed)throw Error("No viewport present");const e=t.map(t=>t*Ex),i=this.view._viewport.toScreen(e[0],e[1]);return[i.x,i.y]}addLayer({id:t,baseLayer:e}={}){if(!this.view?.layers)return;if(t||(t=O()),this.view.layers.has(t)){const e=this.view.layers.get(t);if(e?.container)return e}const i=new lw(this,e,t);return this.view.layers.set(t,i),i}getLayer(t){return this.view.layers.get(t)}addHelper(t,e={}){let i=e?.helperId;return i||(i="string"==typeof t?t:O()),this.helper[i]&&this.removeHelper(i),"string"==typeof t?this.availableHelpers[t]?this.helper[i]=new this.availableHelpers[t]({floorPlan:this,helperId:i,...e}):Nl.warn(`No helper registered for: ${t}`):this.helper[i]=new t({floorPlan:this,helperId:i,...e}),this.helper[i]}removeHelper(t){this.helper[t]?.destroy?.(),delete this.helper[t]}async exportImage({format:t="png",fileName:e,quality:i=90,output:s="base64",maxWidth:r,download:n=!1}={}){let o={format:t,quality:i};n&&(o.format="png");const a=document.querySelector("#"+this.fpeId+" canvas"),l=await function(t,{format:e="png",quality:i=.95}){return new Promise(s=>{let r;r="jpg"===e?t.toDataURL("image/jpeg",i):t.toDataURL(),s(r)})}(a,o).catch(t=>t);if(!n)return l;hw(l,{format:t,fileName:e,quality:i})}#s(t){if(t!==this.#t){this.#t=t;try{this.fpeNode.style.setProperty("--fpe-font-family",t)}catch(e){console.warn("Failed to set font-family",e)}}}destroy(){this.#e?.(),this.view.destroy(),this.loader.reset(),this.freeDrawingEvents(),this.layout=null,this.fpeNode&&this.fpeNode.remove(),this.fpeNode=null}}export{Yw as FloorPlanEngine,Ol as setApiUrls};
|
|
1
|
+
const t=3.28084,e=(t,e=1/64)=>{const i=1/e;return Math.round(t*i)/i};function i(t){return Math.sign(t)*Math.floor(Math.abs(t))}function s(t,e){return typeof t<"u"&&null!==t&&Number.isFinite(t)&&t>=-e&&t<=e}const r=" ",n="m",o="′",a="″",l="m²",h="ft²";function u(t,e=.5,i=1/64){return!(t%e)||e<=i?[t/e,1/e]:u(t,e/2)}const c=(s=0,l="metric",h=3)=>{if("imperial"===l){const{feet:n,inches:l,fraction:h,isNegative:c}=function(s){const r=s*t,n=Math.abs(r),o=e(n%1*12);return{feet:i(n),inches:i(o),fraction:e(o%1),isNegative:Math.sign(s)<0}}(s);let d="";if(h>0){const[t,i]=u(e(h));d=`${r}${t}/${i}`}return`${c?"-":""}${n}${o}${r}${l}${d}${a}`}const c=Math.pow(10,h);return`${Math.round(s*c)/c}${r}${n}`},d=(e=0,i="metric",s=0,n=!0)=>{let o="",a="";const u=Math.pow(10,s);if("imperial"===i){const i=function(e){return e*t*t}(e);o=""+Math.round(i*u)/u,a=`${r}${h}`}else o=""+Math.round(e*u)/u,a=`${r}${l}`;return n&&(o+=a),o};["US","USA","United States","U.S","U.S.A","England","UK","U.K","United Kingdom","Liberia","Myanmar"].map(t=>t.toLowerCase());const p=(t,e)=>{const i=`.${e}`;return(t=>t.replace(/[/\\]/g,"_"))((t=>t.replace(/[.,\s]/g,"_"))(t.endsWith(i)?t.split(i)[0]:t))+i};function f(t){const e=function(t){return"#"===t.slice(0,1)&&(t=t.slice(1)),t}(t);return 3===e.length?`#${e.split("").map(t=>t+t).join("")}`:t}function m(t){return t>=0&&t<=255}function g(t){const e=f(t),i={r:parseInt(e.substring(1,3),16),g:parseInt(e.substring(3,5),16),b:parseInt(e.substring(5,7),16)};if(function({r:t,g:e,b:i}){return m(t)&&m(e)&&m(i)}(i))return i;throw"invalid hex color input"}function y(t){return JSON.parse(JSON.stringify(t))}function v(...t){let e={};for(const i of t)if(i instanceof Array)e instanceof Array||(e=[]),e=[...e,...i];else if(i instanceof Object)for(const t of Object.entries(i)){const i=t[0];let s=t[1];s instanceof Object&&i in e&&(s=v(e[i],s)),e={...e,[i]:s}}return e}function x(){return typeof window<"u"&&typeof navigator<"u"&&typeof document<"u"}!x()||window.self===window.top||window.location.ancestorOrigins&&window.location.ancestorOrigins[0]||document.referrer,x()&&navigator.platform.toUpperCase().indexOf("MAC");var b={exports:{}};function w(){}w.prototype={on:function(t,e,i){var s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var s=this;function r(){s.off(t,r),e.apply(i,arguments)}return r._=e,this.on(t,r,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),s=0,r=i.length;s<r;s++)i[s].fn.apply(i[s].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),s=i[t],r=[];if(s&&e)for(var n=0,o=s.length;n<o;n++)s[n].fn!==e&&s[n].fn._!==e&&r.push(s[n]);return r.length?i[t]=r:delete i[t],this}},b.exports=w;var _=b.exports.TinyEmitter=w;const P=["info","warnings","errors"];class E extends _{constructor(t){super(),this.levels=P.slice(),this.info=this.log,t&&this.setLevels(t),this.levelStack=[]}setLevels(t){const e=this.levels.slice();if("string"==typeof t)switch(t){case"none":this.levels=[];break;case"all":this.levels=["debug","info","warnings","errors"];break;case"debug":this.levels=["debug"];break;case"info":this.levels=["info"];break;case"warnings":this.levels=["warnings"];break;case"errors":this.levels=["errors"];break;default:console.error(`Unknown setting '${t}'.`)}else this.levels=t.slice();return e}push(){this.levelStack.push(this.levels)}pushAndSetLevels(t){return this.push(),this.setLevels(t)}pop(){if(this.levelStack.length>0){const t=this.levelStack.pop();this.setLevels(t)}}debug(...t){this.levels.includes("debug")&&(console.debug(...t),this.emit("debug",...t))}log(...t){this.levels.includes("info")&&(console.log(...t),this.emit("info",...t))}warn(...t){this.levels.includes("warnings")&&(console.warn(...t),this.emit("warning",...t))}error(...t){this.levels.includes("errors")&&(console.error(...t),this.emit("error",...t))}}for(var T,A=[],I=0;I<256;++I)A.push((I+256).toString(16).slice(1));var S=new Uint8Array(16);function C(){if(!T&&!(T="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return T(S)}const M={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function O(t,e,i){if(M.randomUUID&&!t)return M.randomUUID();var s=(t=t||{}).random||(t.rng||C)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(t,e=0){return(A[t[e+0]]+A[t[e+1]]+A[t[e+2]]+A[t[e+3]]+"-"+A[t[e+4]]+A[t[e+5]]+"-"+A[t[e+6]]+A[t[e+7]]+"-"+A[t[e+8]]+A[t[e+9]]+"-"+A[t[e+10]]+A[t[e+11]]+A[t[e+12]]+A[t[e+13]]+A[t[e+14]]+A[t[e+15]]).toLowerCase()}(s)}const N=t=>{const e=[];for(const[i,s]of Object.entries(t))void 0!==s&&e.push(`${i}=${String(s)}`);return e.length?`?${e.join("&")}`:""};class L extends Error{code;data;constructor(t,e,i){super(t||"There was a problem. Please check your internet connection and try again."),this.name="SpaceApiError",this.stack=(new Error).stack,this.code=e,this.data=i}}let R="https://api.archilogic.com";function B(t){let e;if(t.secretAccessToken)e={type:"secret",secretAccessToken:t.secretAccessToken};else if(t.temporaryAccessToken||t.temporaryAccessTokenFunction)e={type:"temporary",temporaryAccessToken:t.temporaryAccessToken};else{if(!t.publishableAccessToken)throw new L("Programming error: token is not provided.",void 0,void 0);e={type:"publishable",publishableAccessToken:t.publishableAccessToken}}return t.sdkVersion&&(e.sdkVersion=t.sdkVersion),e}function k(t){return t.status>=200&&t.status<400?t:t.json().then(e=>{const i=e?.message||e?.error||e;switch(typeof i){case"string":return Promise.reject(new L(i,t.status,void 0));case"object":return Promise.reject(new L(i.message,t.status,i.data));default:return Promise.reject(new L(null,null,e))}})}async function F(t,e,i={},s){const r=new URL(R+e),n=function(t){const e=new Headers;switch(t.type){case"secret":e.set("authorization",`AL-Secret-Token ${t.secretAccessToken}`);break;case"temporary":e.set("authorization",`${t.temporaryAccessToken?.authorization}`)}return t.sdkVersion&&e.set("x-sdk-version",t.sdkVersion),e}(s);let o=!1;switch("publishable"===s.type&&r.searchParams.set("pubtoken",s.publishableAccessToken),t){case"GET":i&&"object"==typeof i&&Object.entries(i).forEach(([t,e])=>{void 0!==e&&r.searchParams.set(t,e.toString())});break;case"POST":case"PUT":case"PATCH":n.set("content-type","application/json"),o=!0;break;case"DELETE":break;default:return Promise.reject(new L("Programming error, unsupported method: "+t,void 0,void 0))}return fetch(r.toString(),{method:t,headers:n,body:o?JSON.stringify(i):void 0}).then(k,t=>{throw t}).then(t=>t.json()).catch(t=>Promise.reject(t))}class D{config;temporaryAccessTokenFunction;tempScopes=[{resource:"floor",action:"readPublic"},{resource:"floor",action:"readPrivate"},{resource:"floor",action:"queryPublic"},{resource:"floor",action:"queryPrivate"},{resource:"floor",action:"archive"},{resource:"customFields",action:"readPublic"},{resource:"customFields",action:"readPrivate"},{resource:"customFields",action:"write"}];temporaryAccessToken;temporaryAccessTokenPromise;durationSeconds=3600;constructor(t){this.config=B(t),(t.temporaryAccessToken||t.temporaryAccessTokenFunction)&&(this.temporaryAccessTokenFunction=t.temporaryAccessTokenFunction,this.temporaryAccessToken=t.temporaryAccessToken),t.temporaryAccessTokenScopes&&(this.tempScopes=t.temporaryAccessTokenScopes)}get isAccessTokenActive(){const t=/* @__PURE__ */(new Date).getTime()/1e3;return!!this.temporaryAccessToken&&this.temporaryAccessToken.expiresAt>t}async getTemporaryAccessToken(){if(this.isAccessTokenActive&&this.temporaryAccessToken)return this.temporaryAccessToken;this.temporaryAccessTokenPromise||(this.temporaryAccessTokenPromise=new Promise(async(t,e)=>{if(this.temporaryAccessTokenFunction&&(this.temporaryAccessToken=await this.temporaryAccessTokenFunction({scopes:this.tempScopes,durationSeconds:this.durationSeconds}),this.isAccessTokenActive&&t(this.temporaryAccessToken)),this.temporaryAccessToken){const t=/* @__PURE__ */new Date;t.setTime(1e3*this.temporaryAccessToken.expiresAt),e(new L(`Temporary access token expired at ${t.toString()}`,void 0,void 0))}else e(new L("Temporary access token not defined",void 0,void 0))}));try{return await this.temporaryAccessTokenPromise}catch(t){throw this.temporaryAccessTokenPromise=void 0,t}finally{this.isAccessTokenActive&&(this.temporaryAccessTokenPromise=void 0)}}async callSpaceAPI(t,e,i={},s=this.config){switch(s.type){case"secret":case"publishable":return F(t,e,i,s);case"temporary":{const r=await this.getTemporaryAccessToken();return F(t,e,i,{...s,temporaryAccessToken:r})}}}}class U{connection;constructor(t,e={}){this.connection=new D(t);for(const[i,s]of Object.entries(e))this[i]=s}async getTemporaryAccessToken(){return this.connection.getTemporaryAccessToken()}async createFloor(t){return this.connection.callSpaceAPI("POST","/v2/floor",t)}async duplicateFloor(t,e){const i=e.revisionId?`?revisionId=${e.revisionId}`:"";return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/duplicate${i}`)}async updateFloor(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/floor/${t}`,e)}async archiveFloor(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/archive`)}async unarchiveFloor(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/unarchive`)}async searchFloorsBasic(t){const{name:e,id:i,paginationInput:s,teamId:r}=t,n=((t,e,i,s)=>{const r={};return t&&(r.name={contains:`${t}`}),e&&(r.ids=[e]),s&&(r.team={id:{eq:s}}),{query:"query ($floorFilter: FloorFilter!, $paginationInput: PaginationInput) { getFloors(where: $floorFilter, paginationInput: $paginationInput) { floors { id name area createdAt updatedAt labels { name color } }, paginationInfo { currentPage limit offset totalCount totalPageCount} } }",variables:{floorFilter:r,paginationInput:i}}})(e,i,s,r);return this.connection.callSpaceAPI("POST","/graphql",n)}async searchFloorsAdvanced(t,e){const i=((t,e)=>({query:t,variables:{paginationInput:e}}))(t,e);return this.connection.callSpaceAPI("POST","/graphql",i)}async getFloorById(t,e=!1,i=!0,s=!1,r,n=!1){const o=N({includeAddress:s,includeRelations:i,includeCustomAttributes:n}),a=await this.connection.callSpaceAPI("GET",`/v2/floor/${t}${e?"/geo-json":""}${o}`);let l={};if(a.properties?.defaultLayoutId){const{layout:t,id:e,lastRevision:i,categories:s}=await this.getLayout(a.properties.defaultLayoutId,r);l={layout:{id:e,layout:t,lastRevision:i,categories:s}}}return{...a,...l}}async getFloorGeoJson(t,e){const i=N(e??{}),s=await this.connection.callSpaceAPI("GET",`/v2/floor/${t}/geo-json${i}`);let r;if(e?.includeAllElements){const t=s.features.find(t=>"Floor"===t.properties.resourceType);r=t?.properties.defaultLayoutId}else{r=s.properties.defaultLayoutId}if(r){const{layout:t,id:e,lastRevision:i,categories:n}=await this.getLayout(r);return{...s,layout:{id:e,layout:t,lastRevision:i,categories:n}}}return s}getFloorStatistics(t){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/statistics`)}queryFloors(t){return this.connection.callSpaceAPI("GET","/v2/floor",t)}async getAllFloors(t=!1,e=!1,i=!1,s,r){const n=t||i?1e3:1e4,o=await this.queryFloors({geometry:t,includeArchived:e,includeRelations:i,includeCustomAttributes:r,teamId:s,limit:n});let a=o.features||[];if(a.length<n)return o;for(;a?.length;)a=(await this.queryFloors({geometry:t,includeArchived:e,includeRelations:i,includeCustomAttributes:r,teamId:s,offset:o.features.length,limit:n})).features||[],o.features.push(...a);return o}getFloorplanImage(t,e){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/2d-image`,e)}getSceneStructure(t,e=!1){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/scene-structure`,{includeMetadata:e})}assignLabel(t,e){return this.connection.callSpaceAPI("PUT",`/v2/floor/${t}/label/${e}`)}removeLabel(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/floor/${t}/label/${e}`)}getSpaceById(t,e=!1,i=!0){const s=`?includeRelations=${i}`;return this.connection.callSpaceAPI("GET",`/v2/space/${t}/${e?"geo-json":""}${s}`)}querySpaces(t){return this.connection.callSpaceAPI("GET","/v2/space",t)}async getAllSpacesByFloorId(t,e=!1,i,s){const r=1e3,n=await this.querySpaces({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:s,limit:r});let o=n.features||[];if(o.length<r)return n;for(;o?.length;)o=(await this.querySpaces({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:s,offset:n.features.length,limit:r})).features||[],n.features.push(...o);return n}getAssetById(t,e=!1,i=!0,s=!1){const r=N({includeRelations:i,includeCustomAttributes:s});return this.connection.callSpaceAPI("GET",`/v2/asset/${t}/${e?"geo-json":""}${r}`)}queryAssets(t){return this.connection.callSpaceAPI("GET","/v2/asset",t)}async getAllAssets(t){const{limit:e=1e4,...i}=t,s=await this.queryAssets({...i,limit:e});let r=s.features||[];if(r.length<e)return s;for(;r?.length;)r=(await this.queryAssets({...t,offset:(t.offset||0)+s.features.length,limit:e})).features||[],s.features.push(...r);return s}getAllAssetsByFloorId(t,e=!1,i,s){return this.getAllAssets({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:s})}getAllAssetsBySpaceId(t,e=!1,i,s){return this.getAllAssets({spaceId:t,geometry:e,includeRelations:i,includeCustomAttributes:s})}getCustomField(t,e,i){return this.connection.callSpaceAPI("GET",`/v2/${t}/${e}/custom-field/${i}`)}getAllCustomFields(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t}/${e}/custom-field`)}setCustomField(t,e,i,s){return this.connection.callSpaceAPI("PUT",`/v2/${t}/${e}/custom-field/${i}`,s)}deleteCustomField(t,e,i){return this.connection.callSpaceAPI("DELETE",`/v2/${t}/${e}/custom-field/${i}`)}getLabel(t){return this.connection.callSpaceAPI("GET",`/v2/label/${t}`)}listLabels(){return this.connection.callSpaceAPI("GET","/v2/label/")}createOrUpdateLabel(t,e){return this.connection.callSpaceAPI("PUT",`/v2/label/${t}`,e)}deleteLabel(t){return this.connection.callSpaceAPI("DELETE",`/v2/label/${t}`)}getCustomAttributes(){return this.connection.callSpaceAPI("GET","/v2/custom-attributes")}getCustomAttribute(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/custom-attributes/${e}`)}getCustomAttributesForResourceType(t){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/custom-attributes`)}createCustomAttribute(t){const{resourceType:e,...i}=t;return this.connection.callSpaceAPI("POST",`/v2/${e.toLowerCase()}/custom-attributes`,i)}updateCustomAttribute(t){const{apiFieldName:e,resourceType:i,...s}=t;return this.connection.callSpaceAPI("PATCH",`/v2/${i.toLowerCase()}/custom-attributes/${e}`,s)}deleteCustomAttribute(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/${t.toLowerCase()}/custom-attributes/${e}`)}getCustomAttributeValues(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/${e}/custom-attributes`)}createCustomAttributeValue(t){const{apiFieldName:e,resourceId:i,resourceType:s,...r}=t;return this.connection.callSpaceAPI("POST",`/v2/${s.toLowerCase()}/${i}/custom-attributes/${e}`,r)}updateCustomAttributeValue(t){const{apiFieldName:e,resourceId:i,resourceType:s,...r}=t;return this.connection.callSpaceAPI("PATCH",`/v2/${s.toLowerCase()}/${i}/custom-attributes/${e}`,r)}deleteCustomAttributeValue(t,e,i){return this.connection.callSpaceAPI("DELETE",`/v2/${e.toLowerCase()}/${t}/custom-attributes/${i}`)}createLayout(t,e,i){return this.connection.callSpaceAPI("POST","/v2/layout",{floorId:t,layout:e,isDefault:i})}duplicateLayout(t,e){const i=N({revisionId:e});return this.connection.callSpaceAPI("POST",`/v2/layout/${t}/duplicate${i}`,{layoutId:t,revisionId:e})}getLayout(t,e){const i=N(e?{filter:e}:{});return this.connection.callSpaceAPI("GET",`/v2/layout/${t}${i}`)}getLayouts(t,e){const i=N({floorId:t,isDefault:e});return this.connection.callSpaceAPI("GET",`/v2/layout/${i}`)}updateLayout(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/layout/${t}`,e)}deleteLayout(t){return this.connection.callSpaceAPI("DELETE",`/v2/layout/${t}`)}createLayoutRevision(t,e){return this.connection.callSpaceAPI("POST",`/v2/layout/${t}/revisions`,e)}updateLayoutRevision(t,e,i){return this.connection.callSpaceAPI("PATCH",`/v2/layout/${t}/revisions/${e}`,i)}getLayoutRevisions(t,e){const i=N(e?{filter:e}:{});return this.connection.callSpaceAPI("GET",`/v2/layout/${t}/revisions${i}`)}getLayoutRevision(t,e){return this.connection.callSpaceAPI("GET",`/v2/layout/${t}/revisions/${e}`)}convertLanguageToQuery(t){return this.connection.callSpaceAPI("POST","/v2/language/graphql",t)}convertLanguageToAgentResponse(t){return this.connection.callSpaceAPI("POST","/v2/language/query-floors",t)}getDxf(t){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/dxf`)}getIfc(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/ifc`)}getGltf(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/gltf`)}getImdf(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/imdf`)}getImdfs(t){return this.connection.callSpaceAPI("POST","/v2/floor/imdf",t)}listExtensions(t){return this.connection.callSpaceAPI("GET","/v2/extensions",t)}createExtension(t){return this.connection.callSpaceAPI("POST","/v2/extensions",t)}updateExtension(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/extensions/${t}`,e)}deleteExtension(t){return this.connection.callSpaceAPI("DELETE",`/v2/extensions/${t}`)}listExtensionAccess(t){return this.connection.callSpaceAPI("GET",`/v2/extensions/${t}/access`)}grantExtensionAccess(t,e){return this.connection.callSpaceAPI("PUT",`/v2/extensions/${t}/access/${e}`)}revokeExtensionAccess(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/extensions/${t}/access/${e}`)}listBuildings(){return this.connection.callSpaceAPI("GET","/v2/buildings")}createBuilding(t){return this.connection.callSpaceAPI("POST","/v2/buildings",t)}getBuildingById(t){return this.connection.callSpaceAPI("GET",`/v2/buildings/${t}`)}updateBuilding(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/buildings/${t}`,e)}deleteBuilding(t){return this.connection.callSpaceAPI("DELETE",`/v2/buildings/${t}`)}}var G;(t=>{t.version="6.4.2.3",t.use_lines=!0;class e{m_Parent=null;m_polygon=[];m_Index=0;m_jointype=0;m_endtype=0;m_Children=[];IsOpen=!1;IsHoleNode(){for(var t=!0,e=this.m_Parent;null!==e;)t=!t,e=e.m_Parent;return t}ChildCount(){return this.m_Children.length}Contour(){return this.m_polygon}AddChild(t){var e=this.m_Children.length;this.m_Children.push(t),t.m_Parent=this,t.m_Index=e}GetNext(){return this.m_Children.length>0?this.m_Children[0]:this.GetNextSiblingUp()}GetNextSiblingUp(){return null===this.m_Parent?null:this.m_Index===this.m_Parent.m_Children.length-1?this.m_Parent.GetNextSiblingUp():this.m_Parent.m_Children[this.m_Index+1]}Children(){return this.m_Children}Parent(){return this.m_Parent}IsHole(){return this.IsHoleNode()}}t.PolyNode=e;t.PolyTree=class extends e{m_AllPolys=[];constructor(){super()}Clear(){for(var t=0,e=this.m_AllPolys.length;t<e;t++)this.m_AllPolys[t]=null;this.m_AllPolys.length=0,this.m_Children.length=0}GetFirst(){return this.m_Children.length>0?this.m_Children[0]:null}Total(){var t=this.m_AllPolys.length;return t>0&&this.m_Children[0]!==this.m_AllPolys[0]&&t--,t}},t.Clear=function(t){t.length=0},t.PI=3.141592653589793,t.PI2=6.283185307179586;t.FPoint=class{X=0;Y=0;constructor(...e){var i=e,s=e.length;if(this.X=0,this.Y=0,2===s)this.X=i[0],this.Y=i[1];else if(1===s)if(i[0]instanceof t.FPoint){var r=i[0];this.X=r.X,this.Y=r.Y}else{var n=i[0];this.X=n.X,this.Y=n.Y}else this.X=0,this.Y=0}static op_Equality(t,e){return t.X===e.X&&t.Y===e.Y}static op_Inequality(t,e){return t.X!==e.X||t.Y!==e.Y}};var i,s,r,n,o,a,l,h;t.FRect=class{left;top;right;bottom;constructor(...t){var e=t,i=t.length;if(4===i)this.left=e[0],this.top=e[1],this.right=e[2],this.bottom=e[3];else if(1===i){var s=e[0];this.left=s.left,this.top=s.top,this.right=s.right,this.bottom=s.bottom}else this.left=0,this.top=0,this.right=0,this.bottom=0}},(i=t.ClipType||(t.ClipType={}))[i.ctIntersection=0]="ctIntersection",i[i.ctUnion=1]="ctUnion",i[i.ctDifference=2]="ctDifference",i[i.ctXor=3]="ctXor",(s=t.PolyType||(t.PolyType={}))[s.ptSubject=0]="ptSubject",s[s.ptClip=1]="ptClip",(r=t.PolyFillType||(t.PolyFillType={}))[r.pftEvenOdd=0]="pftEvenOdd",r[r.pftNonZero=1]="pftNonZero",r[r.pftPositive=2]="pftPositive",r[r.pftNegative=3]="pftNegative",(n=t.JoinType||(t.JoinType={}))[n.jtSquare=0]="jtSquare",n[n.jtRound=1]="jtRound",n[n.jtMiter=2]="jtMiter",(o=t.EndType||(t.EndType={}))[o.etOpenSquare=0]="etOpenSquare",o[o.etOpenRound=1]="etOpenRound",o[o.etOpenButt=2]="etOpenButt",o[o.etClosedLine=3]="etClosedLine",o[o.etClosedPolygon=4]="etClosedPolygon",(a=t.EdgeSide||(t.EdgeSide={}))[a.esLeft=0]="esLeft",a[a.esRight=1]="esRight",(l=t.Direction||(t.Direction={}))[l.dRightToLeft=0]="dRightToLeft",l[l.dLeftToRight=1]="dLeftToRight",(h=t.NodeType||(t.NodeType={}))[h.ntAny=0]="ntAny",h[h.ntOpen=1]="ntOpen",h[h.ntClosed=2]="ntClosed";t.TEdge=class{Bot=new t.FPoint;Curr=new t.FPoint;Top=new t.FPoint;Delta=new t.FPoint;Dx=0;PolyTyp=0;Side=0;WindDelta=0;WindCnt=0;WindCnt2=0;OutIdx=0;Next=null;Prev=null;NextInLML=null;NextInAEL=null;PrevInAEL=null;NextInSEL=null;PrevInSEL=null};t.IntersectNode=class{Edge1=null;Edge2=null;Pt=new t.FPoint},t.Compare=function(t,e){var i=e.Pt.Y-t.Pt.Y;return i>0?1:i<0?-1:0};t.LocalMinima=class{Y=0;LeftBound=null;RightBound=null;Next=null};t.Scanbeam=class{Y=0;Next=null};t.Maxima=class{X=0;Next=null;Prev=null};t.OutRec=class{Idx=0;IsHole=!1;IsOpen=!1;FirstLeft=null;Pts=null;BottomPt=null;PolyNode=null};t.OutPt=class{Idx=0;Pt=new t.FPoint;Next=null;Prev=null};t.Join=class{OutPt1=null;OutPt2=null;OffPt=new t.FPoint};class u{m_MinimaList=null;m_CurrentLM=null;m_edges=new Array;m_HasOpenPaths=!1;PreserveCollinear=!1;m_Scanbeam=null;m_PolyOuts=null;m_ActiveEdges=null;static horizontal=-34e37;static Skip=-2;static Unassigned=-1;static tolerance=1e-20;static maxValue=Math.sqrt(Number.MAX_VALUE);static minValue=Math.sqrt(Number.MIN_VALUE);static near_zero(e){return e>-t.ClipperBase.tolerance&&e<t.ClipperBase.tolerance}static IsHorizontal(t){return 0===t.Delta.Y}PointIsVertex(e,i){var s=i;do{if(t.FPoint.op_Equality(s.Pt,e))return!0;s=s.Next}while(s!==i);return!1}PointOnLineSegment(t,e,i){return t.X===e.X&&t.Y===e.Y||t.X===i.X&&t.Y===i.Y||t.X>e.X==t.X<i.X&&t.Y>e.Y==t.Y<i.Y&&(t.X-e.X)*(i.Y-e.Y)===(i.X-e.X)*(t.Y-e.Y)}PointOnPolygon(t,e){for(var i=e;;){if(this.PointOnLineSegment(t,i.Pt,i.Next.Pt))return!0;if((i=i.Next)===e)break}return!1}static SlopesEqual(){var t,e,i,s,r,n,o=arguments,a=o.length;return 2===a?(e=o[1],(t=o[0]).Delta.Y*e.Delta.X===t.Delta.X*e.Delta.Y):3===a?(s=o[1],r=o[2],((i=o[0]).Y-s.Y)*(s.X-r.X)-(i.X-s.X)*(s.Y-r.Y)===0):(s=o[1],r=o[2],n=o[3],((i=o[0]).Y-s.Y)*(r.X-n.X)-(i.X-s.X)*(r.Y-n.Y)===0)}static SlopesEqual3(t,e){return t.Delta.Y*e.Delta.X===t.Delta.X*e.Delta.Y}static SlopesEqual4(t,e,i){return(t.Y-e.Y)*(e.X-i.X)-(t.X-e.X)*(e.Y-i.Y)===0}static SlopesEqual5(t,e,i,s){return(t.Y-e.Y)*(i.X-s.X)-(t.X-e.X)*(i.Y-s.Y)===0}Clear(){this.DisposeLocalMinimaList();for(var e=0,i=this.m_edges.length;e<i;++e){for(var s=0,r=this.m_edges[e].length;s<r;++s)this.m_edges[e][s]=null;t.Clear(this.m_edges[e])}t.Clear(this.m_edges),this.m_HasOpenPaths=!1}DisposeLocalMinimaList(){for(;null!==this.m_MinimaList;){var t=this.m_MinimaList.Next;this.m_MinimaList=null,this.m_MinimaList=t}this.m_CurrentLM=null}RangeTest(e){(e.X>t.ClipperBase.maxValue||e.X<-t.ClipperBase.maxValue||e.Y>t.ClipperBase.maxValue||e.Y<-t.ClipperBase.maxValue||e.X>0&&e.X<t.ClipperBase.minValue||e.Y>0&&e.Y<t.ClipperBase.minValue||e.X<0&&e.X>-t.ClipperBase.minValue||e.Y<0&&e.Y>-t.ClipperBase.minValue)&&t.Error("Coordinate outside allowed range in RangeTest().")}InitEdge(t,e,i,s){t.Next=e,t.Prev=i,t.Curr.X=s.X,t.Curr.Y=s.Y,t.OutIdx=-1}InitEdge2(t,e){t.Curr.Y>=t.Next.Curr.Y?(t.Bot.X=t.Curr.X,t.Bot.Y=t.Curr.Y,t.Top.X=t.Next.Curr.X,t.Top.Y=t.Next.Curr.Y):(t.Top.X=t.Curr.X,t.Top.Y=t.Curr.Y,t.Bot.X=t.Next.Curr.X,t.Bot.Y=t.Next.Curr.Y),this.SetDx(t),t.PolyTyp=e}FindNextLocMin(e){for(var i;;){for(;t.FPoint.op_Inequality(e.Bot,e.Prev.Bot)||t.FPoint.op_Equality(e.Curr,e.Top);)e=e.Next;if(e.Dx!==t.ClipperBase.horizontal&&e.Prev.Dx!==t.ClipperBase.horizontal)break;for(;e.Prev.Dx===t.ClipperBase.horizontal;)e=e.Prev;for(i=e;e.Dx===t.ClipperBase.horizontal;)e=e.Next;if(e.Top.Y!==e.Prev.Bot.Y){i.Prev.Bot.X<e.Bot.X&&(e=i);break}}return e}ProcessBound(e,i){var s,r,n=e;if(n.OutIdx===t.ClipperBase.Skip){if(e=n,i){for(;e.Top.Y===e.Next.Bot.Y;)e=e.Next;for(;e!==n&&e.Dx===t.ClipperBase.horizontal;)e=e.Prev}else{for(;e.Top.Y===e.Prev.Bot.Y;)e=e.Prev;for(;e!==n&&e.Dx===t.ClipperBase.horizontal;)e=e.Next}if(e===n)n=i?e.Next:e.Prev;else{e=i?n.Next:n.Prev;var o=new t.LocalMinima;o.Next=null,o.Y=e.Bot.Y,o.LeftBound=null,o.RightBound=e,e.WindDelta=0,n=this.ProcessBound(e,i),this.InsertLocalMinima(o)}return n}if(e.Dx===t.ClipperBase.horizontal&&((s=i?e.Prev:e.Next).Dx===t.ClipperBase.horizontal?s.Bot.X!==e.Bot.X&&s.Top.X!==e.Bot.X&&this.ReverseHorizontal(e):s.Bot.X!==e.Bot.X&&this.ReverseHorizontal(e)),s=e,i){for(;n.Top.Y===n.Next.Bot.Y&&n.Next.OutIdx!==t.ClipperBase.Skip;)n=n.Next;if(n.Dx===t.ClipperBase.horizontal&&n.Next.OutIdx!==t.ClipperBase.Skip){for(r=n;r.Prev.Dx===t.ClipperBase.horizontal;)r=r.Prev;r.Prev.Top.X>n.Next.Top.X&&(n=r.Prev)}for(;e!==n;)e.NextInLML=e.Next,e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Prev.Top.X&&this.ReverseHorizontal(e),e=e.Next;e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Prev.Top.X&&this.ReverseHorizontal(e),n=n.Next}else{for(;n.Top.Y===n.Prev.Bot.Y&&n.Prev.OutIdx!==t.ClipperBase.Skip;)n=n.Prev;if(n.Dx===t.ClipperBase.horizontal&&n.Prev.OutIdx!==t.ClipperBase.Skip){for(r=n;r.Next.Dx===t.ClipperBase.horizontal;)r=r.Next;(r.Next.Top.X===n.Prev.Top.X||r.Next.Top.X>n.Prev.Top.X)&&(n=r.Next)}for(;e!==n;)e.NextInLML=e.Prev,e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Next.Top.X&&this.ReverseHorizontal(e),e=e.Prev;e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Next.Top.X&&this.ReverseHorizontal(e),n=n.Prev}return n}AddPath(e,i,s){t.use_lines?s||1!==i||t.Error("AddPath: Open paths must be subject."):s||t.Error("AddPath: Open paths have been disabled.");var r=e.length-1;if(s)for(;r>0&&t.FPoint.op_Equality(e[r],e[0]);)--r;for(;r>0&&t.FPoint.op_Equality(e[r],e[r-1]);)--r;if(s&&r<2||!s&&r<1)return!1;for(var n=new Array,o=0;o<=r;o++)n.push(new t.TEdge);var a=!0;n[1].Curr.X=e[1].X,n[1].Curr.Y=e[1].Y,this.RangeTest(e[0]),this.RangeTest(e[r]),this.InitEdge(n[0],n[1],n[r],e[0]),this.InitEdge(n[r],n[0],n[r-1],e[r]);for(o=r-1;o>=1;--o)this.RangeTest(e[o]),this.InitEdge(n[o],n[o+1],n[o-1],e[o]);for(var l,h=n[0],u=h,c=h;;)if(u.Curr!==u.Next.Curr||!s&&u.Next===h){if(u.Prev===u.Next)break;if(!s||!t.ClipperBase.SlopesEqual4(u.Prev.Curr,u.Curr,u.Next.Curr)||this.PreserveCollinear&&this.Pt2IsBetweenPt1AndPt3(u.Prev.Curr,u.Curr,u.Next.Curr)){if((u=u.Next)===c||!s&&u.Next===h)break}else u===h&&(h=u.Next),c=u=(u=this.RemoveEdge(u)).Prev}else{if(u===u.Next)break;u===h&&(h=u.Next),c=u=this.RemoveEdge(u)}if(!s&&u===u.Next||s&&u.Prev===u.Next)return!1;s||(this.m_HasOpenPaths=!0,h.Prev.OutIdx=t.ClipperBase.Skip),u=h;do{this.InitEdge2(u,i),u=u.Next,a&&u.Curr.Y!==h.Curr.Y&&(a=!1)}while(u!==h);if(a){if(s)return!1;for(u.Prev.OutIdx=t.ClipperBase.Skip,(p=new t.LocalMinima).Next=null,p.Y=u.Bot.Y,p.LeftBound=null,p.RightBound=u,p.RightBound.Side=1,p.RightBound.WindDelta=0;u.Bot.X!==u.Prev.Top.X&&this.ReverseHorizontal(u),u.Next.OutIdx!==t.ClipperBase.Skip;)u.NextInLML=u.Next,u=u.Next;return this.InsertLocalMinima(p),this.m_edges.push(n),!0}this.m_edges.push(n);var d=null;for(t.FPoint.op_Equality(u.Prev.Bot,u.Prev.Top)&&(u=u.Next);(u=this.FindNextLocMin(u))!==d;){var p;null===d&&(d=u),(p=new t.LocalMinima).Next=null,p.Y=u.Bot.Y,u.Dx<u.Prev.Dx?(p.LeftBound=u.Prev,p.RightBound=u,l=!1):(p.LeftBound=u,p.RightBound=u.Prev,l=!0),p.LeftBound.Side=0,p.RightBound.Side=1,s?p.LeftBound.Next===p.RightBound?p.LeftBound.WindDelta=-1:p.LeftBound.WindDelta=1:p.LeftBound.WindDelta=0,p.RightBound.WindDelta=-p.LeftBound.WindDelta,(u=this.ProcessBound(p.LeftBound,l)).OutIdx===t.ClipperBase.Skip&&(u=this.ProcessBound(u,l));var f=this.ProcessBound(p.RightBound,!l);f.OutIdx===t.ClipperBase.Skip&&(f=this.ProcessBound(f,!l)),p.LeftBound.OutIdx===t.ClipperBase.Skip?p.LeftBound=null:p.RightBound.OutIdx===t.ClipperBase.Skip&&(p.RightBound=null),this.InsertLocalMinima(p),l||(u=f)}return!0}AddPaths(t,e,i){for(var s=!1,r=0,n=t.length;r<n;++r)this.AddPath(t[r],e,i)&&(s=!0);return s}Pt2IsBetweenPt1AndPt3(e,i,s){return!(t.FPoint.op_Equality(e,s)||t.FPoint.op_Equality(e,i)||t.FPoint.op_Equality(s,i))&&(e.X!==s.X?i.X>e.X==i.X<s.X:i.Y>e.Y==i.Y<s.Y)}RemoveEdge(t){t.Prev.Next=t.Next,t.Next.Prev=t.Prev;var e=t.Next;return t.Prev=null,e}SetDx(e){e.Delta.X=e.Top.X-e.Bot.X,e.Delta.Y=e.Top.Y-e.Bot.Y,0===e.Delta.Y?e.Dx=t.ClipperBase.horizontal:e.Dx=e.Delta.X/e.Delta.Y}InsertLocalMinima(t){if(null===this.m_MinimaList)this.m_MinimaList=t;else if(t.Y>=this.m_MinimaList.Y)t.Next=this.m_MinimaList,this.m_MinimaList=t;else{for(var e=this.m_MinimaList;null!==e.Next&&t.Y<e.Next.Y;)e=e.Next;t.Next=e.Next,e.Next=t}}PopLocalMinima(t,e){return e.v=this.m_CurrentLM,null!==this.m_CurrentLM&&this.m_CurrentLM.Y===t&&(this.m_CurrentLM=this.m_CurrentLM.Next,!0)}ReverseHorizontal(t){var e=t.Top.X;t.Top.X=t.Bot.X,t.Bot.X=e}Reset(){if(this.m_CurrentLM=this.m_MinimaList,null!==this.m_CurrentLM){this.m_Scanbeam=null;for(var e=this.m_MinimaList;null!==e;){this.InsertScanbeam(e.Y);var i=e.LeftBound;null!==i&&(i.Curr.X=i.Bot.X,i.Curr.Y=i.Bot.Y,i.OutIdx=t.ClipperBase.Unassigned),null!==(i=e.RightBound)&&(i.Curr.X=i.Bot.X,i.Curr.Y=i.Bot.Y,i.OutIdx=t.ClipperBase.Unassigned),e=e.Next}this.m_ActiveEdges=null}}InsertScanbeam(e){if(null===this.m_Scanbeam)this.m_Scanbeam=new t.Scanbeam,this.m_Scanbeam.Next=null,this.m_Scanbeam.Y=e;else if(e>this.m_Scanbeam.Y){var i=new t.Scanbeam;i.Y=e,i.Next=this.m_Scanbeam,this.m_Scanbeam=i}else{for(var s=this.m_Scanbeam;null!==s.Next&&e<=s.Next.Y;)s=s.Next;if(e===s.Y)return;var r=new t.Scanbeam;r.Y=e,r.Next=s.Next,s.Next=r}}PopScanbeam(t){return null===this.m_Scanbeam?(t.v=0,!1):(t.v=this.m_Scanbeam.Y,this.m_Scanbeam=this.m_Scanbeam.Next,!0)}LocalMinimaPending(){return null!==this.m_CurrentLM}CreateOutRec(){var e=new t.OutRec;return e.Idx=t.ClipperBase.Unassigned,e.IsHole=!1,e.IsOpen=!1,e.FirstLeft=null,e.Pts=null,e.BottomPt=null,e.PolyNode=null,this.m_PolyOuts.push(e),e.Idx=this.m_PolyOuts.length-1,e}DisposeOutRec(t){var e=this.m_PolyOuts[t];e.Pts=null,e=null,this.m_PolyOuts[t]=null}UpdateEdgeIntoAEL(e){null===e.NextInLML&&t.Error("UpdateEdgeIntoAEL: invalid call");var i=e.PrevInAEL,s=e.NextInAEL;return e.NextInLML.OutIdx=e.OutIdx,null!==i?i.NextInAEL=e.NextInLML:this.m_ActiveEdges=e.NextInLML,null!==s&&(s.PrevInAEL=e.NextInLML),e.NextInLML.Side=e.Side,e.NextInLML.WindDelta=e.WindDelta,e.NextInLML.WindCnt=e.WindCnt,e.NextInLML.WindCnt2=e.WindCnt2,(e=e.NextInLML).Curr.X=e.Bot.X,e.Curr.Y=e.Bot.Y,e.PrevInAEL=i,e.NextInAEL=s,t.ClipperBase.IsHorizontal(e)||this.InsertScanbeam(e.Top.Y),e}SwapPositionsInAEL(t,e){if(t.NextInAEL!==t.PrevInAEL&&e.NextInAEL!==e.PrevInAEL){if(t.NextInAEL===e){var i=e.NextInAEL;null!==i&&(i.PrevInAEL=t);var s=t.PrevInAEL;null!==s&&(s.NextInAEL=e),e.PrevInAEL=s,e.NextInAEL=t,t.PrevInAEL=e,t.NextInAEL=i}else if(e.NextInAEL===t){var r=t.NextInAEL;null!==r&&(r.PrevInAEL=e);var n=e.PrevInAEL;null!==n&&(n.NextInAEL=t),t.PrevInAEL=n,t.NextInAEL=e,e.PrevInAEL=t,e.NextInAEL=r}else{var o=t.NextInAEL,a=t.PrevInAEL;t.NextInAEL=e.NextInAEL,null!==t.NextInAEL&&(t.NextInAEL.PrevInAEL=t),t.PrevInAEL=e.PrevInAEL,null!==t.PrevInAEL&&(t.PrevInAEL.NextInAEL=t),e.NextInAEL=o,null!==e.NextInAEL&&(e.NextInAEL.PrevInAEL=e),e.PrevInAEL=a,null!==e.PrevInAEL&&(e.PrevInAEL.NextInAEL=e)}null===t.PrevInAEL?this.m_ActiveEdges=t:null===e.PrevInAEL&&(this.m_ActiveEdges=e)}}DeleteFromAEL(t){var e=t.PrevInAEL,i=t.NextInAEL;null===e&&null===i&&t!==this.m_ActiveEdges||(null!==e?e.NextInAEL=i:this.m_ActiveEdges=i,null!==i&&(i.PrevInAEL=e),t.NextInAEL=null,t.PrevInAEL=null)}}t.ClipperBase=u;t.Clipper=class extends u{m_SortedEdges=null;m_IntersectList=null;m_IntersectNodeComparer=null;m_ExecuteLocked=!1;m_ClipFillType=0;m_SubjFillType=0;m_Joins=null;m_GhostJoins=null;m_UsingPolyTree=!1;ReverseSolution=!1;StrictlySimple=!1;m_ClipType=0;m_Maxima=null;ZFillFunction;constructor(e){super(),void 0===e&&(e=0),this.m_PolyOuts=null,this.m_Scanbeam=null,this.m_ActiveEdges=null,this.m_Scanbeam=null,this.m_Maxima=null,this.m_ActiveEdges=null,this.m_SortedEdges=null,this.m_IntersectList=new Array,this.m_IntersectNodeComparer=t.Compare,this.m_ExecuteLocked=!1,this.m_UsingPolyTree=!1,this.m_PolyOuts=new Array,this.m_Joins=new Array,this.m_GhostJoins=new Array,this.ReverseSolution=!!(1&e),this.StrictlySimple=!!(2&e),this.PreserveCollinear=!!(4&e)}static ioReverseSolution=1;static ioStrictlySimple=2;static ioPreserveCollinear=4;Clear(){0!==this.m_edges.length&&(this.DisposeAllPolyPts(),super.Clear())}InsertMaxima(e){var i=new t.Maxima;if(i.X=e,null===this.m_Maxima)this.m_Maxima=i,this.m_Maxima.Next=null,this.m_Maxima.Prev=null;else if(e<this.m_Maxima.X)i.Next=this.m_Maxima,i.Prev=null,this.m_Maxima=i;else{for(var s=this.m_Maxima;null!==s.Next&&e>=s.Next.X;)s=s.Next;if(e===s.X)return;i.Next=s.Next,i.Prev=s,null!==s.Next&&(s.Next.Prev=i),s.Next=i}}Execute(...e){var i=e,s=i.length,r=i[1]instanceof t.PolyTree;if(4===s&&!r){var n=i[0],o=i[1],a=i[2],l=i[3];if(this.m_ExecuteLocked)return!1;this.m_HasOpenPaths&&t.Error("Error: PolyTree struct is needed for open path clipping."),this.m_ExecuteLocked=!0,t.Clear(o),this.m_SubjFillType=a,this.m_ClipFillType=l,this.m_ClipType=n,this.m_UsingPolyTree=!1;try{(u=this.ExecuteInternal())&&this.BuildResult(o)}finally{this.DisposeAllPolyPts(),this.m_ExecuteLocked=!1}return u}if(4===s&&r){n=i[0];var h=i[1];a=i[2],l=i[3];if(this.m_ExecuteLocked)return!1;this.m_ExecuteLocked=!0,this.m_SubjFillType=a,this.m_ClipFillType=l,this.m_ClipType=n,this.m_UsingPolyTree=!0;try{var u;(u=this.ExecuteInternal())&&this.BuildResult2(h)}finally{this.DisposeAllPolyPts(),this.m_ExecuteLocked=!1}return u}if(2===s&&!r){n=i[0],o=i[1];return this.Execute(n,o,0,0)}if(2===s&&r){n=i[0],h=i[1];return this.Execute(n,h,0,0)}}FixHoleLinkage(t){if(null!==t.FirstLeft&&(t.IsHole===t.FirstLeft.IsHole||null===t.FirstLeft.Pts)){for(var e=t.FirstLeft;null!==e&&(e.IsHole===t.IsHole||null===e.Pts);)e=e.FirstLeft;t.FirstLeft=e}}ExecuteInternal(){try{this.Reset(),this.m_SortedEdges=null,this.m_Maxima=null;var t,e,i,s={},r={};if(!this.PopScanbeam(s))return!1;for(this.InsertLocalMinimaIntoAEL(s.v);this.PopScanbeam(r)||this.LocalMinimaPending();){if(this.ProcessHorizontals(),this.m_GhostJoins.length=0,!this.ProcessIntersections(r.v))return!1;this.ProcessEdgesAtTopOfScanbeam(r.v),s.v=r.v,this.InsertLocalMinimaIntoAEL(s.v)}for(e=0,i=this.m_PolyOuts.length;e<i;e++)null===(t=this.m_PolyOuts[e]).Pts||t.IsOpen||(t.IsHole^this.ReverseSolution)==this.Area$1(t)>0&&this.ReversePolyPtLinks(t.Pts);for(this.JoinCommonEdges(),e=0,i=this.m_PolyOuts.length;e<i;e++)null!==(t=this.m_PolyOuts[e]).Pts&&(t.IsOpen?this.FixupOutPolyline(t):this.FixupOutPolygon(t));return this.StrictlySimple&&this.DoSimplePolygons(),!0}finally{this.m_Joins.length=0,this.m_GhostJoins.length=0}}DisposeAllPolyPts(){for(var e=0,i=this.m_PolyOuts.length;e<i;++e)this.DisposeOutRec(e);t.Clear(this.m_PolyOuts)}AddJoin(e,i,s){var r=new t.Join;r.OutPt1=e,r.OutPt2=i,r.OffPt.X=s.X,r.OffPt.Y=s.Y,this.m_Joins.push(r)}AddGhostJoin(e,i){var s=new t.Join;s.OutPt1=e,s.OffPt.X=i.X,s.OffPt.Y=i.Y,this.m_GhostJoins.push(s)}InsertLocalMinimaIntoAEL(e){for(var i,s,r={};this.PopLocalMinima(e,r);){i=r.v.LeftBound,s=r.v.RightBound;var n=null;if(null===i?(this.InsertEdgeIntoAEL(s,null),this.SetWindingCount(s),this.IsContributing(s)&&(n=this.AddOutPt(s,s.Bot))):null===s?(this.InsertEdgeIntoAEL(i,null),this.SetWindingCount(i),this.IsContributing(i)&&(n=this.AddOutPt(i,i.Bot)),this.InsertScanbeam(i.Top.Y)):(this.InsertEdgeIntoAEL(i,null),this.InsertEdgeIntoAEL(s,i),this.SetWindingCount(i),s.WindCnt=i.WindCnt,s.WindCnt2=i.WindCnt2,this.IsContributing(i)&&(n=this.AddLocalMinPoly(i,s,i.Bot)),this.InsertScanbeam(i.Top.Y)),null!==s&&(t.ClipperBase.IsHorizontal(s)?(null!==s.NextInLML&&this.InsertScanbeam(s.NextInLML.Top.Y),this.AddEdgeToSEL(s)):this.InsertScanbeam(s.Top.Y)),null!==i&&null!==s){if(null!==n&&t.ClipperBase.IsHorizontal(s)&&this.m_GhostJoins.length>0&&0!==s.WindDelta)for(var o=0,a=this.m_GhostJoins.length;o<a;o++){var l=this.m_GhostJoins[o];this.HorzSegmentsOverlap(l.OutPt1.Pt.X,l.OffPt.X,s.Bot.X,s.Top.X)&&this.AddJoin(l.OutPt1,n,l.OffPt)}if(i.OutIdx>=0&&null!==i.PrevInAEL&&i.PrevInAEL.Curr.X===i.Bot.X&&i.PrevInAEL.OutIdx>=0&&t.ClipperBase.SlopesEqual5(i.PrevInAEL.Curr,i.PrevInAEL.Top,i.Curr,i.Top)&&0!==i.WindDelta&&0!==i.PrevInAEL.WindDelta){var h=this.AddOutPt(i.PrevInAEL,i.Bot);this.AddJoin(n,h,i.Top)}if(i.NextInAEL!==s){if(s.OutIdx>=0&&s.PrevInAEL.OutIdx>=0&&t.ClipperBase.SlopesEqual5(s.PrevInAEL.Curr,s.PrevInAEL.Top,s.Curr,s.Top)&&0!==s.WindDelta&&0!==s.PrevInAEL.WindDelta){h=this.AddOutPt(s.PrevInAEL,s.Bot);this.AddJoin(n,h,s.Top)}var u=i.NextInAEL;if(null!==u)for(;u!==s;)this.IntersectEdges(s,u,i.Curr),u=u.NextInAEL}}}}InsertEdgeIntoAEL(t,e){if(null===this.m_ActiveEdges)t.PrevInAEL=null,t.NextInAEL=null,this.m_ActiveEdges=t;else if(null===e&&this.E2InsertsBeforeE1(this.m_ActiveEdges,t))t.PrevInAEL=null,t.NextInAEL=this.m_ActiveEdges,this.m_ActiveEdges.PrevInAEL=t,this.m_ActiveEdges=t;else{for(null===e&&(e=this.m_ActiveEdges);null!==e.NextInAEL&&!this.E2InsertsBeforeE1(e.NextInAEL,t);)e=e.NextInAEL;t.NextInAEL=e.NextInAEL,null!==e.NextInAEL&&(e.NextInAEL.PrevInAEL=t),t.PrevInAEL=e,e.NextInAEL=t}}E2InsertsBeforeE1(e,i){return i.Curr.X===e.Curr.X?i.Top.Y>e.Top.Y?i.Top.X<t.Clipper.TopX(e,i.Top.Y):e.Top.X>t.Clipper.TopX(i,e.Top.Y):i.Curr.X<e.Curr.X}IsEvenOddFillType(t){return 0===t.PolyTyp?0===this.m_SubjFillType:0===this.m_ClipFillType}IsEvenOddAltFillType(t){return 0===t.PolyTyp?0===this.m_ClipFillType:0===this.m_SubjFillType}IsContributing(t){var e,i;switch(0===t.PolyTyp?(e=this.m_SubjFillType,i=this.m_ClipFillType):(e=this.m_ClipFillType,i=this.m_SubjFillType),e){case 0:if(0===t.WindDelta&&1!==t.WindCnt)return!1;break;case 1:if(1!==Math.abs(t.WindCnt))return!1;break;case 2:if(1!==t.WindCnt)return!1;break;default:if(-1!==t.WindCnt)return!1}switch(this.m_ClipType){case 0:switch(i){case 0:case 1:return 0!==t.WindCnt2;case 2:return t.WindCnt2>0;default:return t.WindCnt2<0}case 1:switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}case 2:if(0===t.PolyTyp)switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}else switch(i){case 0:case 1:return 0!==t.WindCnt2;case 2:return t.WindCnt2>0;default:return t.WindCnt2<0}case 3:if(0!==t.WindDelta)return!0;switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}}return!0}SetWindingCount(t){for(var e=t.PrevInAEL;null!==e&&(e.PolyTyp!==t.PolyTyp||0===e.WindDelta);)e=e.PrevInAEL;if(null===e){var i=0===t.PolyTyp?this.m_SubjFillType:this.m_ClipFillType;0===t.WindDelta?t.WindCnt=3===i?-1:1:t.WindCnt=t.WindDelta,t.WindCnt2=0,e=this.m_ActiveEdges}else if(0===t.WindDelta&&1!==this.m_ClipType)t.WindCnt=1,t.WindCnt2=e.WindCnt2,e=e.NextInAEL;else if(this.IsEvenOddFillType(t)){if(0===t.WindDelta){for(var s=!0,r=e.PrevInAEL;null!==r;)r.PolyTyp===e.PolyTyp&&0!==r.WindDelta&&(s=!s),r=r.PrevInAEL;t.WindCnt=s?0:1}else t.WindCnt=t.WindDelta;t.WindCnt2=e.WindCnt2,e=e.NextInAEL}else e.WindCnt*e.WindDelta<0?Math.abs(e.WindCnt)>1?e.WindDelta*t.WindDelta<0?t.WindCnt=e.WindCnt:t.WindCnt=e.WindCnt+t.WindDelta:t.WindCnt=0===t.WindDelta?1:t.WindDelta:0===t.WindDelta?t.WindCnt=e.WindCnt<0?e.WindCnt-1:e.WindCnt+1:e.WindDelta*t.WindDelta<0?t.WindCnt=e.WindCnt:t.WindCnt=e.WindCnt+t.WindDelta,t.WindCnt2=e.WindCnt2,e=e.NextInAEL;if(this.IsEvenOddAltFillType(t))for(;e!==t;)0!==e.WindDelta&&(t.WindCnt2=0===t.WindCnt2?1:0),e=e.NextInAEL;else for(;e!==t;)t.WindCnt2+=e.WindDelta,e=e.NextInAEL}AddEdgeToSEL(t){null===this.m_SortedEdges?(this.m_SortedEdges=t,t.PrevInSEL=null,t.NextInSEL=null):(t.NextInSEL=this.m_SortedEdges,t.PrevInSEL=null,this.m_SortedEdges.PrevInSEL=t,this.m_SortedEdges=t)}PopEdgeFromSEL(t){if(t.v=this.m_SortedEdges,null===t.v)return!1;var e=t.v;return this.m_SortedEdges=t.v.NextInSEL,null!==this.m_SortedEdges&&(this.m_SortedEdges.PrevInSEL=null),e.NextInSEL=null,e.PrevInSEL=null,!0}CopyAELToSEL(){var t=this.m_ActiveEdges;for(this.m_SortedEdges=t;null!==t;)t.PrevInSEL=t.PrevInAEL,t.NextInSEL=t.NextInAEL,t=t.NextInAEL}SwapPositionsInSEL(t,e){if(!(null===t.NextInSEL&&null===t.PrevInSEL||null===e.NextInSEL&&null===e.PrevInSEL)){if(t.NextInSEL===e)null!==(i=e.NextInSEL)&&(i.PrevInSEL=t),null!==(s=t.PrevInSEL)&&(s.NextInSEL=e),e.PrevInSEL=s,e.NextInSEL=t,t.PrevInSEL=e,t.NextInSEL=i;else if(e.NextInSEL===t){null!==(i=t.NextInSEL)&&(i.PrevInSEL=e),null!==(s=e.PrevInSEL)&&(s.NextInSEL=t),t.PrevInSEL=s,t.NextInSEL=e,e.PrevInSEL=t,e.NextInSEL=i}else{var i=t.NextInSEL,s=t.PrevInSEL;t.NextInSEL=e.NextInSEL,null!==t.NextInSEL&&(t.NextInSEL.PrevInSEL=t),t.PrevInSEL=e.PrevInSEL,null!==t.PrevInSEL&&(t.PrevInSEL.NextInSEL=t),e.NextInSEL=i,null!==e.NextInSEL&&(e.NextInSEL.PrevInSEL=e),e.PrevInSEL=s,null!==e.PrevInSEL&&(e.PrevInSEL.NextInSEL=e)}null===t.PrevInSEL?this.m_SortedEdges=t:null===e.PrevInSEL&&(this.m_SortedEdges=e)}}AddLocalMaxPoly(t,e,i){this.AddOutPt(t,i),0===e.WindDelta&&this.AddOutPt(e,i),t.OutIdx===e.OutIdx?(t.OutIdx=-1,e.OutIdx=-1):t.OutIdx<e.OutIdx?this.AppendPolygon(t,e):this.AppendPolygon(e,t)}AddLocalMinPoly(e,i,s){var r,n,o;if(t.ClipperBase.IsHorizontal(i)||e.Dx>i.Dx?(r=this.AddOutPt(e,s),i.OutIdx=e.OutIdx,e.Side=0,i.Side=1,o=(n=e).PrevInAEL===i?i.PrevInAEL:n.PrevInAEL):(r=this.AddOutPt(i,s),e.OutIdx=i.OutIdx,e.Side=1,i.Side=0,o=(n=i).PrevInAEL===e?e.PrevInAEL:n.PrevInAEL),null!==o&&o.OutIdx>=0&&o.Top.Y<s.Y&&n.Top.Y<s.Y){var a=t.Clipper.TopX(o,s.Y),l=t.Clipper.TopX(n,s.Y);if(a===l&&0!==n.WindDelta&&0!==o.WindDelta&&t.ClipperBase.SlopesEqual5(new t.FPoint(a,s.Y),o.Top,new t.FPoint(l,s.Y),n.Top)){var h=this.AddOutPt(o,s);this.AddJoin(r,h,n.Top)}}return r}AddOutPt(e,i){if(e.OutIdx<0){let r=this.CreateOutRec();r.IsOpen=0===e.WindDelta;var s=new t.OutPt;return r.Pts=s,s.Idx=r.Idx,s.Pt.X=i.X,s.Pt.Y=i.Y,s.Next=s,s.Prev=s,r.IsOpen||this.SetHoleState(e,r),e.OutIdx=r.Idx,s}{let o=this.m_PolyOuts[e.OutIdx];var r=o.Pts,n=0===e.Side;return n&&t.FPoint.op_Equality(i,r.Pt)?r:!n&&t.FPoint.op_Equality(i,r.Prev.Pt)?r.Prev:((s=new t.OutPt).Idx=o.Idx,s.Pt.X=i.X,s.Pt.Y=i.Y,s.Next=r,s.Prev=r.Prev,s.Prev.Next=s,r.Prev=s,n&&(o.Pts=s),s)}}GetLastOutPt(t){var e=this.m_PolyOuts[t.OutIdx];return 0===t.Side?e.Pts:e.Pts.Prev}SwapPoints(e,i){var s=new t.FPoint(e.Value);e.Value.X=i.Value.X,e.Value.Y=i.Value.Y,i.Value.X=s.X,i.Value.Y=s.Y}HorzSegmentsOverlap(t,e,i,s){var r;return t>e&&(r=t,t=e,e=r),i>s&&(r=i,i=s,s=r),t<s&&i<e}SetHoleState(t,e){for(var i=t.PrevInAEL,s=null;null!==i;)i.OutIdx>=0&&0!==i.WindDelta&&(null===s?s=i:s.OutIdx===i.OutIdx&&(s=null)),i=i.PrevInAEL;null===s?(e.FirstLeft=null,e.IsHole=!1):(e.FirstLeft=this.m_PolyOuts[s.OutIdx],e.IsHole=!e.FirstLeft.IsHole)}GetDx(e,i){return e.Y===i.Y?t.ClipperBase.horizontal:(i.X-e.X)/(i.Y-e.Y)}FirstIsBottomPt(e,i){for(var s=e.Prev;t.FPoint.op_Equality(s.Pt,e.Pt)&&s!==e;)s=s.Prev;var r=Math.abs(this.GetDx(e.Pt,s.Pt));for(s=e.Next;t.FPoint.op_Equality(s.Pt,e.Pt)&&s!==e;)s=s.Next;var n=Math.abs(this.GetDx(e.Pt,s.Pt));for(s=i.Prev;t.FPoint.op_Equality(s.Pt,i.Pt)&&s!==i;)s=s.Prev;var o=Math.abs(this.GetDx(i.Pt,s.Pt));for(s=i.Next;t.FPoint.op_Equality(s.Pt,i.Pt)&&s!==i;)s=s.Next;var a=Math.abs(this.GetDx(i.Pt,s.Pt));return Math.max(r,n)===Math.max(o,a)&&Math.min(r,n)===Math.min(o,a)?this.Area(e)>0:r>=o&&r>=a||n>=o&&n>=a}GetBottomPt(e){for(var i=null,s=e.Next;s!==e;)s.Pt.Y>e.Pt.Y?(e=s,i=null):s.Pt.Y===e.Pt.Y&&s.Pt.X<=e.Pt.X&&(s.Pt.X<e.Pt.X?(i=null,e=s):s.Next!==e&&s.Prev!==e&&(i=s)),s=s.Next;if(null!==i)for(;i!==s;)for(this.FirstIsBottomPt(s,i)||(e=i),i=i.Next;t.FPoint.op_Inequality(i.Pt,e.Pt);)i=i.Next;return e}GetLowermostRec(t,e){null===t.BottomPt&&(t.BottomPt=this.GetBottomPt(t.Pts)),null===e.BottomPt&&(e.BottomPt=this.GetBottomPt(e.Pts));var i=t.BottomPt,s=e.BottomPt;return i.Pt.Y>s.Pt.Y?t:i.Pt.Y<s.Pt.Y?e:i.Pt.X<s.Pt.X?t:i.Pt.X>s.Pt.X||i.Next===i?e:s.Next===s||this.FirstIsBottomPt(i,s)?t:e}OutRec1RightOfOutRec2(t,e){do{if((t=t.FirstLeft)===e)return!0}while(null!==t);return!1}GetOutRec(t){for(var e=this.m_PolyOuts[t];e!==this.m_PolyOuts[e.Idx];)e=this.m_PolyOuts[e.Idx];return e}AppendPolygon(t,e){var i,s=this.m_PolyOuts[t.OutIdx],r=this.m_PolyOuts[e.OutIdx];i=this.OutRec1RightOfOutRec2(s,r)?r:this.OutRec1RightOfOutRec2(r,s)?s:this.GetLowermostRec(s,r);var n=s.Pts,o=n.Prev,a=r.Pts,l=a.Prev;0===t.Side?0===e.Side?(this.ReversePolyPtLinks(a),a.Next=n,n.Prev=a,o.Next=l,l.Prev=o,s.Pts=l):(l.Next=n,n.Prev=l,a.Prev=o,o.Next=a,s.Pts=a):1===e.Side?(this.ReversePolyPtLinks(a),o.Next=l,l.Prev=o,a.Next=n,n.Prev=a):(o.Next=a,a.Prev=o,n.Prev=l,l.Next=n),s.BottomPt=null,i===r&&(r.FirstLeft!==s&&(s.FirstLeft=r.FirstLeft),s.IsHole=r.IsHole),r.Pts=null,r.BottomPt=null,r.FirstLeft=s;var h=t.OutIdx,u=e.OutIdx;t.OutIdx=-1,e.OutIdx=-1;for(var c=this.m_ActiveEdges;null!==c;){if(c.OutIdx===u){c.OutIdx=h,c.Side=t.Side;break}c=c.NextInAEL}r.Idx=s.Idx}ReversePolyPtLinks(t){if(null!==t){var e,i;e=t;do{i=e.Next,e.Next=e.Prev,e.Prev=i,e=i}while(e!==t)}}static SwapSides(t,e){var i=t.Side;t.Side=e.Side,e.Side=i}static SwapPolyIndexes(t,e){var i=t.OutIdx;t.OutIdx=e.OutIdx,e.OutIdx=i}IntersectEdges(e,i,s){var r=e.OutIdx>=0,n=i.OutIdx>=0;if(!t.use_lines||0!==e.WindDelta&&0!==i.WindDelta){if(e.PolyTyp===i.PolyTyp)if(this.IsEvenOddFillType(e)){var o=e.WindCnt;e.WindCnt=i.WindCnt,i.WindCnt=o}else e.WindCnt+i.WindDelta===0?e.WindCnt=-e.WindCnt:e.WindCnt+=i.WindDelta,i.WindCnt-e.WindDelta===0?i.WindCnt=-i.WindCnt:i.WindCnt-=e.WindDelta;else this.IsEvenOddFillType(i)?e.WindCnt2=0===e.WindCnt2?1:0:e.WindCnt2+=i.WindDelta,this.IsEvenOddFillType(e)?i.WindCnt2=0===i.WindCnt2?1:0:i.WindCnt2-=e.WindDelta;var a,l,h,u,c,d;switch(0===e.PolyTyp?(a=this.m_SubjFillType,h=this.m_ClipFillType):(a=this.m_ClipFillType,h=this.m_SubjFillType),0===i.PolyTyp?(l=this.m_SubjFillType,u=this.m_ClipFillType):(l=this.m_ClipFillType,u=this.m_SubjFillType),a){case 2:c=e.WindCnt;break;case 3:c=-e.WindCnt;break;default:c=Math.abs(e.WindCnt)}switch(l){case 2:d=i.WindCnt;break;case 3:d=-i.WindCnt;break;default:d=Math.abs(i.WindCnt)}if(r&&n)0!==c&&1!==c||0!==d&&1!==d||e.PolyTyp!==i.PolyTyp&&3!==this.m_ClipType?this.AddLocalMaxPoly(e,i,s):(this.AddOutPt(e,s),this.AddOutPt(i,s),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(r)0!==d&&1!==d||(this.AddOutPt(e,s),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(n)0!==c&&1!==c||(this.AddOutPt(i,s),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(!(0!==c&&1!==c||0!==d&&1!==d)){var p,f;switch(h){case 2:p=e.WindCnt2;break;case 3:p=-e.WindCnt2;break;default:p=Math.abs(e.WindCnt2)}switch(u){case 2:f=i.WindCnt2;break;case 3:f=-i.WindCnt2;break;default:f=Math.abs(i.WindCnt2)}if(e.PolyTyp!==i.PolyTyp)this.AddLocalMinPoly(e,i,s);else if(1===c&&1===d)switch(this.m_ClipType){case 0:p>0&&f>0&&this.AddLocalMinPoly(e,i,s);break;case 1:p<=0&&f<=0&&this.AddLocalMinPoly(e,i,s);break;case 2:(1===e.PolyTyp&&p>0&&f>0||0===e.PolyTyp&&p<=0&&f<=0)&&this.AddLocalMinPoly(e,i,s);break;case 3:this.AddLocalMinPoly(e,i,s)}else t.Clipper.SwapSides(e,i)}}else{if(0===e.WindDelta&&0===i.WindDelta)return;e.PolyTyp===i.PolyTyp&&e.WindDelta!==i.WindDelta&&1===this.m_ClipType?0===e.WindDelta?n&&(this.AddOutPt(e,s),r&&(e.OutIdx=-1)):r&&(this.AddOutPt(i,s),n&&(i.OutIdx=-1)):e.PolyTyp!==i.PolyTyp&&(0!==e.WindDelta||1!==Math.abs(i.WindCnt)||1===this.m_ClipType&&0!==i.WindCnt2?0!==i.WindDelta||1!==Math.abs(e.WindCnt)||1===this.m_ClipType&&0!==e.WindCnt2||(this.AddOutPt(i,s),n&&(i.OutIdx=-1)):(this.AddOutPt(e,s),r&&(e.OutIdx=-1)))}}DeleteFromSEL(t){var e=t.PrevInSEL,i=t.NextInSEL;null===e&&null===i&&t!==this.m_SortedEdges||(null!==e?e.NextInSEL=i:this.m_SortedEdges=i,null!==i&&(i.PrevInSEL=e),t.NextInSEL=null,t.PrevInSEL=null)}ProcessHorizontals(){for(var t={};this.PopEdgeFromSEL(t);)this.ProcessHorizontal(t.v)}GetHorzDirection(t,e){t.Bot.X<t.Top.X?(e.Left=t.Bot.X,e.Right=t.Top.X,e.Dir=1):(e.Left=t.Top.X,e.Right=t.Bot.X,e.Dir=0)}ProcessHorizontal(e){var i={Dir:null,Left:null,Right:null};this.GetHorzDirection(e,i);for(var s=i.Dir,r=i.Left,n=i.Right,o=0===e.WindDelta,a=e,l=null;null!==a.NextInLML&&t.ClipperBase.IsHorizontal(a.NextInLML);)a=a.NextInLML;null===a.NextInLML&&(l=this.GetMaximaPair(a));var h=this.m_Maxima;if(null!==h)if(1===s){for(;null!==h&&h.X<=e.Bot.X;)h=h.Next;null!==h&&h.X>=a.Top.X&&(h=null)}else{for(;null!==h.Next&&h.Next.X<e.Bot.X;)h=h.Next;h.X<=a.Top.X&&(h=null)}for(var u=null;;){for(var c=e===a,d=this.GetNextInAEL(e,s);null!==d;){if(null!==h)if(1===s)for(;null!==h&&h.X<d.Curr.X;)e.OutIdx>=0&&!o&&this.AddOutPt(e,new t.FPoint(h.X,e.Bot.Y)),h=h.Next;else for(;null!==h&&h.X>d.Curr.X;)e.OutIdx>=0&&!o&&this.AddOutPt(e,new t.FPoint(h.X,e.Bot.Y)),h=h.Prev;if(1===s&&d.Curr.X>n||0===s&&d.Curr.X<r)break;if(d.Curr.X===e.Top.X&&null!==e.NextInLML&&d.Dx<e.NextInLML.Dx)break;if(e.OutIdx>=0&&!o){u=this.AddOutPt(e,d.Curr);for(var p=this.m_SortedEdges;null!==p;){if(p.OutIdx>=0&&this.HorzSegmentsOverlap(e.Bot.X,e.Top.X,p.Bot.X,p.Top.X)){var f=this.GetLastOutPt(p);this.AddJoin(f,u,p.Top)}p=p.NextInSEL}this.AddGhostJoin(u,e.Bot)}if(d===l&&c)return e.OutIdx>=0&&this.AddLocalMaxPoly(e,l,e.Top),this.DeleteFromAEL(e),void this.DeleteFromAEL(l);if(1===s){var m=new t.FPoint(d.Curr.X,e.Curr.Y);this.IntersectEdges(e,d,m)}else{m=new t.FPoint(d.Curr.X,e.Curr.Y);this.IntersectEdges(d,e,m)}var g=this.GetNextInAEL(d,s);this.SwapPositionsInAEL(e,d),d=g}if(null===e.NextInLML||!t.ClipperBase.IsHorizontal(e.NextInLML))break;(e=this.UpdateEdgeIntoAEL(e)).OutIdx>=0&&this.AddOutPt(e,e.Bot),i={Dir:s,Left:r,Right:n},this.GetHorzDirection(e,i),s=i.Dir,r=i.Left,n=i.Right}if(e.OutIdx>=0&&null===u){u=this.GetLastOutPt(e);for(p=this.m_SortedEdges;null!==p;){if(p.OutIdx>=0&&this.HorzSegmentsOverlap(e.Bot.X,e.Top.X,p.Bot.X,p.Top.X)){f=this.GetLastOutPt(p);this.AddJoin(f,u,p.Top)}p=p.NextInSEL}this.AddGhostJoin(u,e.Top)}if(null!==e.NextInLML)if(e.OutIdx>=0){if(u=this.AddOutPt(e,e.Top),0===(e=this.UpdateEdgeIntoAEL(e)).WindDelta)return;var y=e.PrevInAEL;g=e.NextInAEL;if(null!==y&&y.Curr.X===e.Bot.X&&y.Curr.Y===e.Bot.Y&&0===y.WindDelta&&y.OutIdx>=0&&y.Curr.Y>y.Top.Y&&t.ClipperBase.SlopesEqual3(e,y)){let t=this.AddOutPt(y,e.Bot);this.AddJoin(u,t,e.Top)}else if(null!==g&&g.Curr.X===e.Bot.X&&g.Curr.Y===e.Bot.Y&&0!==g.WindDelta&&g.OutIdx>=0&&g.Curr.Y>g.Top.Y&&t.ClipperBase.SlopesEqual3(e,g)){let t=this.AddOutPt(g,e.Bot);this.AddJoin(u,t,e.Top)}}else e=this.UpdateEdgeIntoAEL(e);else e.OutIdx>=0&&this.AddOutPt(e,e.Top),this.DeleteFromAEL(e)}GetNextInAEL(t,e){return 1===e?t.NextInAEL:t.PrevInAEL}IsMinima(t){return null!==t&&t.Prev.NextInLML!==t&&t.Next.NextInLML!==t}IsMaxima(t,e){return null!==t&&t.Top.Y===e&&null===t.NextInLML}IsIntermediate(t,e){return t.Top.Y===e&&null!==t.NextInLML}GetMaximaPair(e){return t.FPoint.op_Equality(e.Next.Top,e.Top)&&null===e.Next.NextInLML?e.Next:t.FPoint.op_Equality(e.Prev.Top,e.Top)&&null===e.Prev.NextInLML?e.Prev:null}GetMaximaPairEx(e){var i=this.GetMaximaPair(e);return null===i||i.OutIdx===t.ClipperBase.Skip||i.NextInAEL===i.PrevInAEL&&!t.ClipperBase.IsHorizontal(i)?null:i}ProcessIntersections(e){if(null===this.m_ActiveEdges)return!0;try{if(this.BuildIntersectList(e),0===this.m_IntersectList.length)return!0;if(1!==this.m_IntersectList.length&&!this.FixupIntersectionOrder())return!1;this.ProcessIntersectList()}catch(i){this.m_SortedEdges=null,this.m_IntersectList.length=0,t.Error("ProcessIntersections error")}return this.m_SortedEdges=null,!0}BuildIntersectList(e){if(null!==this.m_ActiveEdges){var i=this.m_ActiveEdges;for(this.m_SortedEdges=i;null!==i;)i.PrevInSEL=i.PrevInAEL,i.NextInSEL=i.NextInAEL,i.Curr.X=t.Clipper.TopX(i,e),i=i.NextInAEL;for(var s=!0;s&&null!==this.m_SortedEdges;){for(s=!1,i=this.m_SortedEdges;null!==i.NextInSEL;){var r=i.NextInSEL,n=new t.FPoint;if(i.Curr.X>r.Curr.X){this.IntersectPoint(i,r,n),n.Y<e&&(n=new t.FPoint(t.Clipper.TopX(i,e),e));var o=new t.IntersectNode;o.Edge1=i,o.Edge2=r,o.Pt.X=n.X,o.Pt.Y=n.Y,this.m_IntersectList.push(o),this.SwapPositionsInSEL(i,r),s=!0}else i=r}if(null===i.PrevInSEL)break;i.PrevInSEL.NextInSEL=null}this.m_SortedEdges=null}}EdgesAdjacent(t){return t.Edge1.NextInSEL===t.Edge2||t.Edge1.PrevInSEL===t.Edge2}static IntersectNodeSort(t,e){return e.Pt.Y-t.Pt.Y}FixupIntersectionOrder(){this.m_IntersectList.sort(this.m_IntersectNodeComparer),this.CopyAELToSEL();for(var t=this.m_IntersectList.length,e=0;e<t;e++){if(!this.EdgesAdjacent(this.m_IntersectList[e])){for(var i=e+1;i<t&&!this.EdgesAdjacent(this.m_IntersectList[i]);)i++;if(i===t)return!1;var s=this.m_IntersectList[e];this.m_IntersectList[e]=this.m_IntersectList[i],this.m_IntersectList[i]=s}this.SwapPositionsInSEL(this.m_IntersectList[e].Edge1,this.m_IntersectList[e].Edge2)}return!0}ProcessIntersectList(){for(var t=0,e=this.m_IntersectList.length;t<e;t++){var i=this.m_IntersectList[t];this.IntersectEdges(i.Edge1,i.Edge2,i.Pt),this.SwapPositionsInAEL(i.Edge1,i.Edge2)}this.m_IntersectList.length=0}static TopX(t,e){return e===t.Top.Y?t.Top.X:t.Bot.X+t.Dx*(e-t.Bot.Y)}IntersectPoint(e,i,s){var r,n;if(s.X=0,s.Y=0,e.Dx===i.Dx)return s.Y=e.Curr.Y,void(s.X=t.Clipper.TopX(e,s.Y));if(0===e.Delta.X)s.X=e.Bot.X,t.ClipperBase.IsHorizontal(i)?s.Y=i.Bot.Y:(n=i.Bot.Y-i.Bot.X/i.Dx,s.Y=s.X/i.Dx+n);else if(0===i.Delta.X)s.X=i.Bot.X,t.ClipperBase.IsHorizontal(e)?s.Y=e.Bot.Y:(r=e.Bot.Y-e.Bot.X/e.Dx,s.Y=s.X/e.Dx+r);else{r=e.Bot.X-e.Bot.Y*e.Dx;var o=((n=i.Bot.X-i.Bot.Y*i.Dx)-r)/(e.Dx-i.Dx);s.Y=o,Math.abs(e.Dx)<Math.abs(i.Dx)?s.X=e.Dx*o+r:s.X=i.Dx*o+n}if(s.Y<e.Top.Y||s.Y<i.Top.Y){if(e.Top.Y>i.Top.Y)return s.Y=e.Top.Y,s.X=t.Clipper.TopX(i,e.Top.Y),s.X<e.Top.X;s.Y=i.Top.Y,Math.abs(e.Dx)<Math.abs(i.Dx)?s.X=t.Clipper.TopX(e,s.Y):s.X=t.Clipper.TopX(i,s.Y)}s.Y>e.Curr.Y&&(s.Y=e.Curr.Y,Math.abs(e.Dx)>Math.abs(i.Dx)?s.X=t.Clipper.TopX(i,s.Y):s.X=t.Clipper.TopX(e,s.Y))}ProcessEdgesAtTopOfScanbeam(e){for(var i=this.m_ActiveEdges;null!==i;){var s=this.IsMaxima(i,e);if(s){var r=this.GetMaximaPairEx(i);s=null===r||!t.ClipperBase.IsHorizontal(r)}if(s){this.StrictlySimple&&this.InsertMaxima(i.Top.X);var n=i.PrevInAEL;this.DoMaxima(i),i=null===n?this.m_ActiveEdges:n.NextInAEL}else{if(this.IsIntermediate(i,e)&&t.ClipperBase.IsHorizontal(i.NextInLML)?((i=this.UpdateEdgeIntoAEL(i)).OutIdx>=0&&this.AddOutPt(i,i.Bot),this.AddEdgeToSEL(i)):(i.Curr.X=t.Clipper.TopX(i,e),i.Curr.Y=e),this.StrictlySimple){n=i.PrevInAEL;if(i.OutIdx>=0&&0!==i.WindDelta&&null!==n&&n.OutIdx>=0&&n.Curr.X===i.Curr.X&&0!==n.WindDelta){var o=new t.FPoint(i.Curr),a=this.AddOutPt(n,o),l=this.AddOutPt(i,o);this.AddJoin(a,l,o)}}i=i.NextInAEL}}for(this.ProcessHorizontals(),this.m_Maxima=null,i=this.m_ActiveEdges;null!==i;){if(this.IsIntermediate(i,e)){a=null;i.OutIdx>=0&&(a=this.AddOutPt(i,i.Top));n=(i=this.UpdateEdgeIntoAEL(i)).PrevInAEL;var h=i.NextInAEL;if(null!==n&&n.Curr.X===i.Bot.X&&n.Curr.Y===i.Bot.Y&&null!==a&&n.OutIdx>=0&&n.Curr.Y===n.Top.Y&&t.ClipperBase.SlopesEqual5(i.Curr,i.Top,n.Curr,n.Top)&&0!==i.WindDelta&&0!==n.WindDelta){l=this.AddOutPt(n,i.Bot);this.AddJoin(a,l,i.Top)}else if(null!==h&&h.Curr.X===i.Bot.X&&h.Curr.Y===i.Bot.Y&&null!==a&&h.OutIdx>=0&&h.Curr.Y===h.Top.Y&&t.ClipperBase.SlopesEqual5(i.Curr,i.Top,h.Curr,h.Top)&&0!==i.WindDelta&&0!==h.WindDelta){l=this.AddOutPt(h,i.Bot);this.AddJoin(a,l,i.Top)}}i=i.NextInAEL}}DoMaxima(e){var i=this.GetMaximaPairEx(e);if(null===i)return e.OutIdx>=0&&this.AddOutPt(e,e.Top),void this.DeleteFromAEL(e);for(var s=e.NextInAEL;null!==s&&s!==i;)this.IntersectEdges(e,s,e.Top),this.SwapPositionsInAEL(e,s),s=e.NextInAEL;-1===e.OutIdx&&-1===i.OutIdx?(this.DeleteFromAEL(e),this.DeleteFromAEL(i)):e.OutIdx>=0&&i.OutIdx>=0?(e.OutIdx>=0&&this.AddLocalMaxPoly(e,i,e.Top),this.DeleteFromAEL(e),this.DeleteFromAEL(i)):t.use_lines&&0===e.WindDelta?(e.OutIdx>=0&&(this.AddOutPt(e,e.Top),e.OutIdx=t.ClipperBase.Unassigned),this.DeleteFromAEL(e),i.OutIdx>=0&&(this.AddOutPt(i,e.Top),i.OutIdx=t.ClipperBase.Unassigned),this.DeleteFromAEL(i)):t.Error("DoMaxima error")}static ReversePaths(t){for(var e=0,i=t.length;e<i;e++)t[e].reverse()}static Orientation(e){return t.Clipper.Area(e)>=0}PointCount(t){if(null===t)return 0;var e=0,i=t;do{e++,i=i.Next}while(i!==t);return e}BuildResult(e){t.Clear(e);for(var i=0,s=this.m_PolyOuts.length;i<s;i++){var r=this.m_PolyOuts[i];if(null!==r.Pts){var n=r.Pts.Prev,o=this.PointCount(n);if(!(o<2)){for(var a=new Array(o),l=0;l<o;l++)a[l]=n.Pt,n=n.Prev;e.push(a)}}}}BuildResult2(e){e.Clear();for(var i=0,s=this.m_PolyOuts.length;i<s;i++){var r=this.m_PolyOuts[i],n=this.PointCount(r.Pts);if(!(r.IsOpen&&n<2||!r.IsOpen&&n<3)){this.FixHoleLinkage(r);var o=new t.PolyNode;e.m_AllPolys.push(o),r.PolyNode=o,o.m_polygon.length=n;for(var a=r.Pts.Prev,l=0;l<n;l++)o.m_polygon[l]=a.Pt,a=a.Prev}}for(i=0,s=this.m_PolyOuts.length;i<s;i++){null!==(r=this.m_PolyOuts[i]).PolyNode&&(r.IsOpen?(r.PolyNode.IsOpen=!0,e.AddChild(r.PolyNode)):null!==r.FirstLeft&&null!==r.FirstLeft.PolyNode?r.FirstLeft.PolyNode.AddChild(r.PolyNode):e.AddChild(r.PolyNode))}}FixupOutPolyline(e){for(var i=e.Pts,s=i.Prev;i!==s;)if(i=i.Next,t.FPoint.op_Equality(i.Pt,i.Prev.Pt)){i===s&&(s=i.Prev);var r=i.Prev;r.Next=i.Next,i.Next.Prev=r,i=r}i===i.Prev&&(e.Pts=null)}FixupOutPolygon(e){var i=null;e.BottomPt=null;for(var s=e.Pts,r=this.PreserveCollinear||this.StrictlySimple;;){if(s.Prev===s||s.Prev===s.Next)return void(e.Pts=null);if(t.FPoint.op_Equality(s.Pt,s.Next.Pt)||t.FPoint.op_Equality(s.Pt,s.Prev.Pt)||t.ClipperBase.SlopesEqual4(s.Prev.Pt,s.Pt,s.Next.Pt)&&(!r||!this.Pt2IsBetweenPt1AndPt3(s.Prev.Pt,s.Pt,s.Next.Pt)))i=null,s.Prev.Next=s.Next,s.Next.Prev=s.Prev,s=s.Prev;else{if(s===i)break;null===i&&(i=s),s=s.Next}}e.Pts=s}DupOutPt(e,i){var s=new t.OutPt;return s.Pt.X=e.Pt.X,s.Pt.Y=e.Pt.Y,s.Idx=e.Idx,i?(s.Next=e.Next,s.Prev=e,e.Next.Prev=s,e.Next=s):(s.Prev=e.Prev,s.Next=e,e.Prev.Next=s,e.Prev=s),s}GetOverlap(t,e,i,s,r){return t<e?i<s?(r.Left=Math.max(t,i),r.Right=Math.min(e,s)):(r.Left=Math.max(t,s),r.Right=Math.min(e,i)):i<s?(r.Left=Math.max(e,i),r.Right=Math.min(t,s)):(r.Left=Math.max(e,s),r.Right=Math.min(t,i)),r.Left<r.Right}JoinHorz(e,i,s,r,n,o){var a=e.Pt.X>i.Pt.X?0:1,l=s.Pt.X>r.Pt.X?0:1;if(a===l)return!1;if(1===a){for(;e.Next.Pt.X<=n.X&&e.Next.Pt.X>=e.Pt.X&&e.Next.Pt.Y===n.Y;)e=e.Next;o&&e.Pt.X!==n.X&&(e=e.Next),i=this.DupOutPt(e,!o),t.FPoint.op_Inequality(i.Pt,n)&&((e=i).Pt.X=n.X,e.Pt.Y=n.Y,i=this.DupOutPt(e,!o))}else{for(;e.Next.Pt.X>=n.X&&e.Next.Pt.X<=e.Pt.X&&e.Next.Pt.Y===n.Y;)e=e.Next;o||e.Pt.X===n.X||(e=e.Next),i=this.DupOutPt(e,o),t.FPoint.op_Inequality(i.Pt,n)&&((e=i).Pt.X=n.X,e.Pt.Y=n.Y,i=this.DupOutPt(e,o))}if(1===l){for(;s.Next.Pt.X<=n.X&&s.Next.Pt.X>=s.Pt.X&&s.Next.Pt.Y===n.Y;)s=s.Next;o&&s.Pt.X!==n.X&&(s=s.Next),r=this.DupOutPt(s,!o),t.FPoint.op_Inequality(r.Pt,n)&&((s=r).Pt.X=n.X,s.Pt.Y=n.Y,r=this.DupOutPt(s,!o))}else{for(;s.Next.Pt.X>=n.X&&s.Next.Pt.X<=s.Pt.X&&s.Next.Pt.Y===n.Y;)s=s.Next;o||s.Pt.X===n.X||(s=s.Next),r=this.DupOutPt(s,o),t.FPoint.op_Inequality(r.Pt,n)&&((s=r).Pt.X=n.X,s.Pt.Y=n.Y,r=this.DupOutPt(s,o))}return 1===a===o?(e.Prev=s,s.Next=e,i.Next=r,r.Prev=i):(e.Next=s,s.Prev=e,i.Prev=r,r.Next=i),!0}JoinPoints(e,i,s){var r=e.OutPt1,n=new t.OutPt,o=e.OutPt2,a=new t.OutPt,l=e.OutPt1.Pt.Y===e.OffPt.Y;if(l&&t.FPoint.op_Equality(e.OffPt,e.OutPt1.Pt)&&t.FPoint.op_Equality(e.OffPt,e.OutPt2.Pt)){if(i!==s)return!1;for(n=e.OutPt1.Next;n!==r&&t.FPoint.op_Equality(n.Pt,e.OffPt);)n=n.Next;var h=n.Pt.Y>e.OffPt.Y;for(a=e.OutPt2.Next;a!==o&&t.FPoint.op_Equality(a.Pt,e.OffPt);)a=a.Next;return h!==a.Pt.Y>e.OffPt.Y&&(h?(n=this.DupOutPt(r,!1),a=this.DupOutPt(o,!0),r.Prev=o,o.Next=r,n.Next=a,a.Prev=n,e.OutPt1=r,e.OutPt2=n,!0):(n=this.DupOutPt(r,!0),a=this.DupOutPt(o,!1),r.Next=o,o.Prev=r,n.Prev=a,a.Next=n,e.OutPt1=r,e.OutPt2=n,!0))}if(l){for(n=r;r.Prev.Pt.Y===r.Pt.Y&&r.Prev!==n&&r.Prev!==o;)r=r.Prev;for(;n.Next.Pt.Y===n.Pt.Y&&n.Next!==r&&n.Next!==o;)n=n.Next;if(n.Next===r||n.Next===o)return!1;for(a=o;o.Prev.Pt.Y===o.Pt.Y&&o.Prev!==a&&o.Prev!==n;)o=o.Prev;for(;a.Next.Pt.Y===a.Pt.Y&&a.Next!==o&&a.Next!==r;)a=a.Next;if(a.Next===o||a.Next===r)return!1;var u={Left:null,Right:null};if(!this.GetOverlap(r.Pt.X,n.Pt.X,o.Pt.X,a.Pt.X,u))return!1;var c,d=u.Left,p=u.Right,f=new t.FPoint;return r.Pt.X>=d&&r.Pt.X<=p?(f.X=r.Pt.X,f.Y=r.Pt.Y,c=r.Pt.X>n.Pt.X):o.Pt.X>=d&&o.Pt.X<=p?(f.X=o.Pt.X,f.Y=o.Pt.Y,c=o.Pt.X>a.Pt.X):n.Pt.X>=d&&n.Pt.X<=p?(f.X=n.Pt.X,f.Y=n.Pt.Y,c=n.Pt.X>r.Pt.X):(f.X=a.Pt.X,f.Y=a.Pt.Y,c=a.Pt.X>o.Pt.X),e.OutPt1=r,e.OutPt2=o,this.JoinHorz(r,n,o,a,f,c)}for(n=r.Next;t.FPoint.op_Equality(n.Pt,r.Pt)&&n!==r;)n=n.Next;var m=n.Pt.Y>r.Pt.Y||!t.ClipperBase.SlopesEqual4(r.Pt,n.Pt,e.OffPt);if(m){for(n=r.Prev;t.FPoint.op_Equality(n.Pt,r.Pt)&&n!==r;)n=n.Prev;if(n.Pt.Y>r.Pt.Y||!t.ClipperBase.SlopesEqual4(r.Pt,n.Pt,e.OffPt))return!1}for(a=o.Next;t.FPoint.op_Equality(a.Pt,o.Pt)&&a!==o;)a=a.Next;var g=a.Pt.Y>o.Pt.Y||!t.ClipperBase.SlopesEqual4(o.Pt,a.Pt,e.OffPt);if(g){for(a=o.Prev;t.FPoint.op_Equality(a.Pt,o.Pt)&&a!==o;)a=a.Prev;if(a.Pt.Y>o.Pt.Y||!t.ClipperBase.SlopesEqual4(o.Pt,a.Pt,e.OffPt))return!1}return n!==r&&a!==o&&n!==a&&(i!==s||m!==g)&&(m?(n=this.DupOutPt(r,!1),a=this.DupOutPt(o,!0),r.Prev=o,o.Next=r,n.Next=a,a.Prev=n,e.OutPt1=r,e.OutPt2=n,!0):(n=this.DupOutPt(r,!0),a=this.DupOutPt(o,!1),r.Next=o,o.Prev=r,n.Prev=a,a.Next=n,e.OutPt1=r,e.OutPt2=n,!0))}static GetBounds(e){for(var i=0,s=e.length;i<s&&0===e[i].length;)i++;if(i===s)return new t.FRect(0,0,0,0);var r=new t.FRect;for(r.left=e[i][0].X,r.right=r.left,r.top=e[i][0].Y,r.bottom=r.top;i<s;i++)for(var n=0,o=e[i].length;n<o;n++)e[i][n].X<r.left?r.left=e[i][n].X:e[i][n].X>r.right&&(r.right=e[i][n].X),e[i][n].Y<r.top?r.top=e[i][n].Y:e[i][n].Y>r.bottom&&(r.bottom=e[i][n].Y);return r}GetBounds2(e){var i=e,s=new t.FRect;for(s.left=e.Pt.X,s.right=e.Pt.X,s.top=e.Pt.Y,s.bottom=e.Pt.Y,e=e.Next;e!==i;)e.Pt.X<s.left&&(s.left=e.Pt.X),e.Pt.X>s.right&&(s.right=e.Pt.X),e.Pt.Y<s.top&&(s.top=e.Pt.Y),e.Pt.Y>s.bottom&&(s.bottom=e.Pt.Y),e=e.Next;return s}static PointInPolygon(t,e){var i=0,s=e.length;if(s<3)return 0;for(var r=e[0],n=1;n<=s;++n){var o=n===s?e[0]:e[n];if(o.Y===t.Y&&(o.X===t.X||r.Y===t.Y&&o.X>t.X==r.X<t.X))return-1;if(r.Y<t.Y!=o.Y<t.Y)if(r.X>=t.X)if(o.X>t.X)i=1-i;else{if(0===(a=(r.X-t.X)*(o.Y-t.Y)-(o.X-t.X)*(r.Y-t.Y)))return-1;a>0==o.Y>r.Y&&(i=1-i)}else if(o.X>t.X){var a;if(0===(a=(r.X-t.X)*(o.Y-t.Y)-(o.X-t.X)*(r.Y-t.Y)))return-1;a>0==o.Y>r.Y&&(i=1-i)}r=o}return i}PointInPolygon(t,e){var i=0,s=e,r=t.X,n=t.Y,o=e.Pt.X,a=e.Pt.Y;do{var l=(e=e.Next).Pt.X,h=e.Pt.Y;if(h===n&&(l===r||a===n&&l>r==o<r))return-1;if(a<n!=h<n)if(o>=r)if(l>r)i=1-i;else{if(0===(u=(o-r)*(h-n)-(l-r)*(a-n)))return-1;u>0==h>a&&(i=1-i)}else if(l>r){var u;if(0===(u=(o-r)*(h-n)-(l-r)*(a-n)))return-1;u>0==h>a&&(i=1-i)}o=l,a=h}while(s!==e);return i}Poly2ContainsPoly1(t,e){var i=t;do{var s=this.PointInPolygon(i.Pt,e);if(s>=0)return s>0;i=i.Next}while(i!==t);return!0}FixupFirstLefts1(e,i){for(var s,r,n=0,o=this.m_PolyOuts.length;n<o;n++)s=this.m_PolyOuts[n],r=t.Clipper.ParseFirstLeft(s.FirstLeft),null!==s.Pts&&r===e&&this.Poly2ContainsPoly1(s.Pts,i.Pts)&&(s.FirstLeft=i)}FixupFirstLefts2(e,i){for(var s,r,n=i.FirstLeft,o=0,a=this.m_PolyOuts.length;o<a;o++)null!==(s=this.m_PolyOuts[o]).Pts&&s!==i&&s!==e&&((r=t.Clipper.ParseFirstLeft(s.FirstLeft))!==n&&r!==e&&r!==i||(this.Poly2ContainsPoly1(s.Pts,e.Pts)?s.FirstLeft=e:this.Poly2ContainsPoly1(s.Pts,i.Pts)?s.FirstLeft=i:s.FirstLeft!==e&&s.FirstLeft!==i||(s.FirstLeft=n)))}FixupFirstLefts3(e,i){for(var s,r,n=0,o=this.m_PolyOuts.length;n<o;n++)s=this.m_PolyOuts[n],r=t.Clipper.ParseFirstLeft(s.FirstLeft),null!==s.Pts&&r===e&&(s.FirstLeft=i)}static ParseFirstLeft(t){for(;null!==t&&null===t.Pts;)t=t.FirstLeft;return t}JoinCommonEdges(){for(var t=0,e=this.m_Joins.length;t<e;t++){var i,s=this.m_Joins[t],r=this.GetOutRec(s.OutPt1.Idx),n=this.GetOutRec(s.OutPt2.Idx);if(null!==r.Pts&&null!==n.Pts)if(!r.IsOpen&&!n.IsOpen)i=r===n?r:this.OutRec1RightOfOutRec2(r,n)?n:this.OutRec1RightOfOutRec2(n,r)?r:this.GetLowermostRec(r,n),this.JoinPoints(s,r,n)&&(r===n?(r.Pts=s.OutPt1,r.BottomPt=null,(n=this.CreateOutRec()).Pts=s.OutPt2,this.UpdateOutPtIdxs(n),this.Poly2ContainsPoly1(n.Pts,r.Pts)?(n.IsHole=!r.IsHole,n.FirstLeft=r,this.m_UsingPolyTree&&this.FixupFirstLefts2(n,r),(n.IsHole^this.ReverseSolution)==this.Area$1(n)>0&&this.ReversePolyPtLinks(n.Pts)):this.Poly2ContainsPoly1(r.Pts,n.Pts)?(n.IsHole=r.IsHole,r.IsHole=!n.IsHole,n.FirstLeft=r.FirstLeft,r.FirstLeft=n,this.m_UsingPolyTree&&this.FixupFirstLefts2(r,n),(r.IsHole^this.ReverseSolution)==this.Area$1(r)>0&&this.ReversePolyPtLinks(r.Pts)):(n.IsHole=r.IsHole,n.FirstLeft=r.FirstLeft,this.m_UsingPolyTree&&this.FixupFirstLefts1(r,n))):(n.Pts=null,n.BottomPt=null,n.Idx=r.Idx,r.IsHole=i.IsHole,i===n&&(r.FirstLeft=n.FirstLeft),n.FirstLeft=r,this.m_UsingPolyTree&&this.FixupFirstLefts3(n,r)))}}UpdateOutPtIdxs(t){var e=t.Pts;do{e.Idx=t.Idx,e=e.Prev}while(e!==t.Pts)}DoSimplePolygons(){for(var e=0;e<this.m_PolyOuts.length;){var i=this.m_PolyOuts[e++],s=i.Pts;if(null!==s&&!i.IsOpen)do{for(var r=s.Next;r!==i.Pts;){if(t.FPoint.op_Equality(s.Pt,r.Pt)&&r.Next!==s&&r.Prev!==s){var n=s.Prev,o=r.Prev;s.Prev=o,o.Next=s,r.Prev=n,n.Next=r,i.Pts=s;var a=this.CreateOutRec();a.Pts=r,this.UpdateOutPtIdxs(a),this.Poly2ContainsPoly1(a.Pts,i.Pts)?(a.IsHole=!i.IsHole,a.FirstLeft=i,this.m_UsingPolyTree&&this.FixupFirstLefts2(a,i)):this.Poly2ContainsPoly1(i.Pts,a.Pts)?(a.IsHole=i.IsHole,i.IsHole=!a.IsHole,a.FirstLeft=i.FirstLeft,i.FirstLeft=a,this.m_UsingPolyTree&&this.FixupFirstLefts2(i,a)):(a.IsHole=i.IsHole,a.FirstLeft=i.FirstLeft,this.m_UsingPolyTree&&this.FixupFirstLefts1(i,a)),r=s}r=r.Next}s=s.Next}while(s!==i.Pts)}}static Area(t){if(!Array.isArray(t))return 0;var e=t.length;if(e<3)return 0;for(var i=0,s=0,r=e-1;s<e;++s)i+=(t[r].X+t[s].X)*(t[r].Y-t[s].Y),r=s;return.5*-i}Area(t){var e=t;if(null===t)return 0;var i=0;do{i+=(t.Prev.Pt.X+t.Pt.X)*(t.Prev.Pt.Y-t.Pt.Y),t=t.Next}while(t!==e);return.5*i}Area$1(t){return this.Area(t.Pts)}static SimplifyPolygon(e,i){var s=new Array,r=new t.Clipper(0);return r.StrictlySimple=!0,r.AddPath(e,0,!0),r.Execute(1,s,i,i),s}static SimplifyPolygons(e,i){void 0===i&&(i=0);var s=new Array,r=new t.Clipper(0);return r.StrictlySimple=!0,r.AddPaths(e,0,!0),r.Execute(1,s,i,i),s}static DistanceSqrd(t,e){var i=t.X-e.X,s=t.Y-e.Y;return i*i+s*s}static DistanceFromLineSqrd(t,e,i){var s=e.Y-i.Y,r=i.X-e.X,n=s*e.X+r*e.Y;return(n=s*t.X+r*t.Y-n)*n/(s*s+r*r)}static SlopesNearCollinear(e,i,s,r){return Math.abs(e.X-i.X)>Math.abs(e.Y-i.Y)?e.X>i.X==e.X<s.X?t.Clipper.DistanceFromLineSqrd(e,i,s)<r:i.X>e.X==i.X<s.X?t.Clipper.DistanceFromLineSqrd(i,e,s)<r:t.Clipper.DistanceFromLineSqrd(s,e,i)<r:e.Y>i.Y==e.Y<s.Y?t.Clipper.DistanceFromLineSqrd(e,i,s)<r:i.Y>e.Y==i.Y<s.Y?t.Clipper.DistanceFromLineSqrd(i,e,s)<r:t.Clipper.DistanceFromLineSqrd(s,e,i)<r}static PointsAreClose(t,e,i){var s=t.X-e.X,r=t.Y-e.Y;return s*s+r*r<=i}static ExcludeOp(t){var e=t.Prev;return e.Next=t.Next,t.Next.Prev=e,e.Idx=0,e}static CleanPolygon(e,i){void 0===i&&(i=1.415);var s=e.length;if(0===s)return new Array;for(var r=new Array(s),n=0;n<s;++n)r[n]=new t.OutPt;for(n=0;n<s;++n)r[n].Pt=e[n],r[n].Next=r[(n+1)%s],r[n].Next.Prev=r[n],r[n].Idx=0;for(var o=i*i,a=r[0];0===a.Idx&&a.Next!==a.Prev;)t.Clipper.PointsAreClose(a.Pt,a.Prev.Pt,o)?(a=t.Clipper.ExcludeOp(a),s--):t.Clipper.PointsAreClose(a.Prev.Pt,a.Next.Pt,o)?(t.Clipper.ExcludeOp(a.Next),a=t.Clipper.ExcludeOp(a),s-=2):t.Clipper.SlopesNearCollinear(a.Prev.Pt,a.Pt,a.Next.Pt,o)?(a=t.Clipper.ExcludeOp(a),s--):(a.Idx=1,a=a.Next);s<3&&(s=0);var l=new Array(s);for(n=0;n<s;++n)l[n]=new t.FPoint(a.Pt),a=a.Next;return r=null,l}static CleanPolygons(e,i){for(var s=new Array(e.length),r=0,n=e.length;r<n;r++)s[r]=t.Clipper.CleanPolygon(e[r],i);return s}static Minkowski(e,i,s,r){var n=r?1:0,o=e.length,a=i.length,l=new Array;if(s)for(var h=0;h<a;h++){for(var u=new Array(o),c=0,d=e.length,p=e[c];c<d;p=e[++c])u[c]=new t.FPoint(i[h].X+p.X,i[h].Y+p.Y);l.push(u)}else for(h=0;h<a;h++){for(u=new Array(o),c=0,d=e.length,p=e[c];c<d;p=e[++c])u[c]=new t.FPoint(i[h].X-p.X,i[h].Y-p.Y);l.push(u)}var f=new Array;for(h=0;h<a-1+n;h++)for(c=0;c<o;c++){var m=new Array;m.push(l[h%a][c%o]),m.push(l[(h+1)%a][c%o]),m.push(l[(h+1)%a][(c+1)%o]),m.push(l[h%a][(c+1)%o]),t.Clipper.Orientation(m)||m.reverse(),f.push(m)}return f}static MinkowskiSum(e,i,s){if(i[0]instanceof Array){let l=i;for(var r=[],n=(a=new t.Clipper,0);n<l.length;++n){var o=t.Clipper.Minkowski(e,l[n],!0,s);if(a.AddPaths(o,0,!0),s){let i=t.Clipper.TranslatePath(l[n],e[0]);a.AddPath(i,1,!0)}}return a.Execute(1,r,1,1),r}{let r=i,n=t.Clipper.Minkowski(e,r,!0,s);var a;return(a=new t.Clipper).AddPaths(n,0,!0),a.Execute(1,n,1,1),n}}static TranslatePath(e,i){for(var s=[],r=0;r<e.length;r++)s.push(new t.FPoint(e[r].X+i.X,e[r].Y+i.Y));return s}static MinkowskiDiff(e,i){var s=t.Clipper.Minkowski(e,i,!1,!0),r=new t.Clipper;return r.AddPaths(s,0,!0),r.Execute(1,s,1,1),s}static PolyTreeToPaths(e){var i=new Array;return t.Clipper.AddPolyNodeToPaths(e,0,i),i}static AddPolyNodeToPaths(e,i,s){var r=!0;switch(i){case 1:return;case 2:r=!e.IsOpen}e.m_polygon.length>0&&r&&s.push(e.m_polygon);for(var n=0,o=e.Children(),a=o.length,l=o[n];n<a;l=o[++n])t.Clipper.AddPolyNodeToPaths(l,i,s)}static OpenPathsFromPolyTree(t){for(var e=[],i=0,s=t.ChildCount();i<s;i++)t.Children()[i].IsOpen&&e.push(t.Children()[i].m_polygon);return e}static ClosedPathsFromPolyTree(e){var i=[];return t.Clipper.AddPolyNodeToPaths(e,2,i),i}};t.ClipperOffset=class{m_destPolys=[];m_srcPoly=[];m_destPoly=[];m_normals=new Array;m_delta=0;m_sinA=0;m_sin=0;m_cos=0;m_miterLim=0;m_StepsPerRad=0;m_lowest=new t.FPoint;m_polyNodes=new t.PolyNode;MiterLimit;ArcTolerance;constructor(e,i){void 0===e&&(e=2),void 0===i&&(i=t.ClipperOffset.def_arc_tolerance),this.MiterLimit=e,this.ArcTolerance=i,this.m_lowest.X=-1}static two_pi=6.28318530717959;static def_arc_tolerance=.25;Clear(){t.Clear(this.m_polyNodes.Children()),this.m_lowest.X=-1}AddPath(e,i,s){var r=e.length-1;if(!(r<0)){var n=new t.PolyNode;if(n.m_jointype=i,n.m_endtype=s,3===s||4===s)for(;r>0&&t.FPoint.op_Equality(e[0],e[r]);)r--;n.m_polygon.push(e[0]);for(var o=0,a=0,l=1;l<=r;l++)t.FPoint.op_Inequality(n.m_polygon[o],e[l])&&(o++,n.m_polygon.push(e[l]),(e[l].Y>n.m_polygon[a].Y||e[l].Y===n.m_polygon[a].Y&&e[l].X<n.m_polygon[a].X)&&(a=o));if(!(4===s&&o<2)&&(this.m_polyNodes.AddChild(n),4===s))if(this.m_lowest.X<0)this.m_lowest=new t.FPoint(this.m_polyNodes.ChildCount()-1,a);else{var h=this.m_polyNodes.Children()[this.m_lowest.X].m_polygon[this.m_lowest.Y];(n.m_polygon[a].Y>h.Y||n.m_polygon[a].Y===h.Y&&n.m_polygon[a].X<h.X)&&(this.m_lowest=new t.FPoint(this.m_polyNodes.ChildCount()-1,a))}}}AddPaths(t,e,i){for(var s=0,r=t.length;s<r;s++)this.AddPath(t[s],e,i)}FixOrientations(){if(this.m_lowest.X>=0&&!t.Clipper.Orientation(this.m_polyNodes.Children()[this.m_lowest.X].m_polygon))for(var e=0;e<this.m_polyNodes.ChildCount();e++){(4===(i=this.m_polyNodes.Children()[e]).m_endtype||3===i.m_endtype&&t.Clipper.Orientation(i.m_polygon))&&i.m_polygon.reverse()}else for(e=0;e<this.m_polyNodes.ChildCount();e++){var i;3!==(i=this.m_polyNodes.Children()[e]).m_endtype||t.Clipper.Orientation(i.m_polygon)||i.m_polygon.reverse()}}static GetUnitNormal(e,i){var s=i.X-e.X,r=i.Y-e.Y;if(0===s&&0===r)return new t.FPoint(0,0);var n=1/Math.sqrt(s*s+r*r);return s*=n,r*=n,new t.FPoint(r,-s)}DoOffset(e){if(this.m_destPolys=new Array,this.m_delta=e,t.ClipperBase.near_zero(e))for(var i=0;i<this.m_polyNodes.ChildCount();i++){4===(n=this.m_polyNodes.Children()[i]).m_endtype&&this.m_destPolys.push(n.m_polygon)}else{var s;this.MiterLimit>2?this.m_miterLim=2/(this.MiterLimit*this.MiterLimit):this.m_miterLim=.5,s=this.ArcTolerance<=0?t.ClipperOffset.def_arc_tolerance:this.ArcTolerance>Math.abs(e)*t.ClipperOffset.def_arc_tolerance?Math.abs(e)*t.ClipperOffset.def_arc_tolerance:this.ArcTolerance;var r=3.14159265358979/Math.acos(1-s/Math.abs(e));this.m_sin=Math.sin(t.ClipperOffset.two_pi/r),this.m_cos=Math.cos(t.ClipperOffset.two_pi/r),this.m_StepsPerRad=r/t.ClipperOffset.two_pi,e<0&&(this.m_sin=-this.m_sin);for(i=0;i<this.m_polyNodes.ChildCount();i++){var n=this.m_polyNodes.Children()[i];this.m_srcPoly=n.m_polygon;var o=this.m_srcPoly.length;if(!(0===o||e<=0&&(o<3||4!==n.m_endtype)))if(this.m_destPoly=new Array,1!==o){this.m_normals.length=0;for(d=0;d<o-1;d++)this.m_normals.push(t.ClipperOffset.GetUnitNormal(this.m_srcPoly[d],this.m_srcPoly[d+1]));if(3===n.m_endtype||4===n.m_endtype?this.m_normals.push(t.ClipperOffset.GetUnitNormal(this.m_srcPoly[o-1],this.m_srcPoly[0])):this.m_normals.push(new t.FPoint(this.m_normals[o-2])),4===n.m_endtype){var a=o-1;for(d=0;d<o;d++)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly)}else if(3===n.m_endtype){for(a=o-1,d=0;d<o;d++)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly),this.m_destPoly=new Array;var l=this.m_normals[o-1];for(d=o-1;d>0;d--)this.m_normals[d]=new t.FPoint(-this.m_normals[d-1].X,-this.m_normals[d-1].Y);this.m_normals[0]=new t.FPoint(-l.X,-l.Y),a=0;for(d=o-1;d>=0;d--)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly)}else{var h;for(a=0,d=1;d<o-1;++d)a=this.OffsetPoint(d,a,n.m_jointype);if(2===n.m_endtype){d=o-1;h=new t.FPoint(this.m_srcPoly[d].X+this.m_normals[d].X*e,this.m_srcPoly[d].Y+this.m_normals[d].Y*e),this.m_destPoly.push(h),h=new t.FPoint(this.m_srcPoly[d].X-this.m_normals[d].X*e,this.m_srcPoly[d].Y-this.m_normals[d].Y*e),this.m_destPoly.push(h)}else{d=o-1;a=o-2,this.m_sinA=0,this.m_normals[d]=new t.FPoint(-this.m_normals[d].X,-this.m_normals[d].Y),0===n.m_endtype?this.DoSquare(d,a):this.DoRound(d,a)}for(d=o-1;d>0;d--)this.m_normals[d]=new t.FPoint(-this.m_normals[d-1].X,-this.m_normals[d-1].Y);this.m_normals[0]=new t.FPoint(-this.m_normals[1].X,-this.m_normals[1].Y);for(d=(a=o-1)-1;d>0;--d)a=this.OffsetPoint(d,a,n.m_jointype);2===n.m_endtype?(h=new t.FPoint(this.m_srcPoly[0].X-this.m_normals[0].X*e,this.m_srcPoly[0].Y-this.m_normals[0].Y*e),this.m_destPoly.push(h),h=new t.FPoint(this.m_srcPoly[0].X+this.m_normals[0].X*e,this.m_srcPoly[0].Y+this.m_normals[0].Y*e),this.m_destPoly.push(h)):(a=1,this.m_sinA=0,0===n.m_endtype?this.DoSquare(0,1):this.DoRound(0,1)),this.m_destPolys.push(this.m_destPoly)}}else{if(1===n.m_jointype)for(var u=1,c=0,d=1;d<=r;d++){this.m_destPoly.push(new t.FPoint(this.m_srcPoly[0].X+u*e,this.m_srcPoly[0].Y+c*e));var p=u;u=u*this.m_cos-this.m_sin*c,c=p*this.m_sin+c*this.m_cos}else{u=-1,c=-1;for(var d=0;d<4;++d)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[0].X+u*e,this.m_srcPoly[0].Y+c*e)),u<0?u=1:c<0?c=1:u=-1}this.m_destPolys.push(this.m_destPoly)}}}}Execute(...e){var i=e;if(i[0]instanceof t.PolyTree){o=i[0],a=i[1];if(o.Clear(),this.FixOrientations(),this.DoOffset(a),(n=new t.Clipper(0)).AddPaths(this.m_destPolys,0,!0),a>0)n.Execute(1,o,2,2);else{h=t.Clipper.GetBounds(this.m_destPolys);if((l=[]).push(new t.FPoint(h.left-10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.top-10)),l.push(new t.FPoint(h.left-10,h.top-10)),n.AddPath(l,0,!0),n.ReverseSolution=!0,n.Execute(1,o,3,3),1===o.ChildCount()&&o.Children()[0].ChildCount()>0){var s=o.Children()[0];o.Children()[0]=s.Children()[0],o.Children()[0].m_Parent=o;for(var r=1;r<s.ChildCount();r++)o.AddChild(s.Children()[r])}else o.Clear()}}else{var n,o=i[0],a=i[1];if(t.Clear(o),this.FixOrientations(),this.DoOffset(a),(n=new t.Clipper(0)).AddPaths(this.m_destPolys,0,!0),a>0)n.Execute(1,o,2,2);else{var l,h=t.Clipper.GetBounds(this.m_destPolys);(l=[]).push(new t.FPoint(h.left-10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.top-10)),l.push(new t.FPoint(h.left-10,h.top-10)),n.AddPath(l,0,!0),n.ReverseSolution=!0,n.Execute(1,o,3,3),o.length>0&&o.splice(0,1)}}}OffsetPoint(e,i,s){if(this.m_sinA=this.m_normals[i].X*this.m_normals[e].Y-this.m_normals[e].X*this.m_normals[i].Y,0===this.m_sinA)return i;if(this.m_sinA>1?this.m_sinA=1:this.m_sinA<-1&&(this.m_sinA=-1),this.m_sinA*this.m_delta<0)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[i].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[i].Y*this.m_delta)),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e])),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[e].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[e].Y*this.m_delta));else switch(s){case 2:var r=this.m_normals[e].X*this.m_normals[i].X+this.m_normals[e].Y*this.m_normals[i].Y+1;r>=this.m_miterLim?this.DoMiter(e,i,r):this.DoSquare(e,i);break;case 0:this.DoSquare(e,i);break;case 1:this.DoRound(e,i)}return i=e}DoSquare(e,i){var s=Math.tan(Math.atan2(this.m_sinA,this.m_normals[i].X*this.m_normals[e].X+this.m_normals[i].Y*this.m_normals[e].Y)/4);this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_delta*(this.m_normals[i].X-this.m_normals[i].Y*s),this.m_srcPoly[e].Y+this.m_delta*(this.m_normals[i].Y+this.m_normals[i].X*s))),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_delta*(this.m_normals[e].X+this.m_normals[e].Y*s),this.m_srcPoly[e].Y+this.m_delta*(this.m_normals[e].Y-this.m_normals[e].X*s)))}DoMiter(e,i,s){var r=this.m_delta/s;this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+(this.m_normals[i].X+this.m_normals[e].X)*r,this.m_srcPoly[e].Y+(this.m_normals[i].Y+this.m_normals[e].Y)*r))}DoRound(e,i){for(var s,r=Math.atan2(this.m_sinA,this.m_normals[i].X*this.m_normals[e].X+this.m_normals[i].Y*this.m_normals[e].Y),n=Math.max(Math.round(this.m_StepsPerRad*Math.abs(r)),1),o=this.m_normals[i].X,a=this.m_normals[i].Y,l=0;l<n;++l)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+o*this.m_delta,this.m_srcPoly[e].Y+a*this.m_delta)),s=o,o=o*this.m_cos-this.m_sin*a,a=s*this.m_sin+a*this.m_cos;this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[e].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[e].Y*this.m_delta))}},t.Error=function(e){throw new t.Error(e)}})(G||(G={}));const X=G;function W(t){let e=et(t),i=X.Clipper.GetBounds(e);return{min:[i.left,-i.bottom],max:[i.right,-i.top]}}function Y(t){if(!t.length)return[];let e=t.filter(t=>t&&t.length>0);if(!e.length)return[];if(1===e.length)return[e[0]];let i=et(e);if(!i.length)return[];let s=[i[0]],r=i.slice(1),n=new X.Clipper;n.AddPaths(s,X.PolyType.ptSubject,!0),n.AddPaths(r,X.PolyType.ptClip,!0);let o=[];return n.Execute(X.ClipType.ctUnion,o,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),it(o)}function H(t,e=0,i=[],s=[],r=[]){for(let n of t.m_Children){if(!n.m_polygon.length)continue;let t=e%2!=0,o=it([n.m_polygon])[0],a={polygon:o,children:[]};i.push(a),t?r.push(o):(r=[o],s.push(r)),H(n,e+1,a.children,s,r)}return s.sort((t,e)=>K(t[0])>K(e[0])?-1:1),{polyTree:i,polygons:s}}function $(t,e=.1,i,s){if(!t.length||!t[0])return[];void 0===i&&(i=X.EndType.etClosedPolygon),e=e&&"number"==typeof e?e:.1;let r=et(t=s?t:Q(t)),n=new X.ClipperOffset(2),o=[];return n.AddPaths(r,X.JoinType.jtMiter,i),n.Execute(o,e),it(o)}function j(t,e=.1,i=X.EndType.etClosedPolygon){if(!t.length||!t[0])return{polygons:[],polyTree:[]};let s=[];for(let o of t)s.push(...et(o));let r=new X.ClipperOffset(2);r.AddPaths(s,X.JoinType.jtMiter,i);let n=new X.PolyTree;return r.Execute(n,e),H(n)}function z(t,e,i){if(!t.length||!t[0])return[];if(!e.length)return t;let s=et(t),r=et(e),n=new X.Clipper;n.AddPaths(s,X.PolyType.ptSubject,!0),n.AddPaths(r,X.PolyType.ptClip,!0);let o=[];return new X.PolyTree,n.Execute(X.ClipType.ctDifference,o,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),it(o)}function V(t,e){if(!t.length||!t[0])return{polygons:[],polyTree:[]};if(!e.length){let e=t.map(t=>[...t]),i=e.map(t=>({polygon:t[0],children:[]}));return{polygons:e,polyTree:i}}let i=[];for(let o=0;o<t.length;o++)i.push(...et(t[o]));let s=[];for(let o=0;o<e.length;o++)s.push(...et(e[o]));let r=new X.Clipper;r.AddPaths(i,X.PolyType.ptSubject,!0),r.AddPaths(s,X.PolyType.ptClip,!0);let n=new X.PolyTree;return r.Execute(X.ClipType.ctDifference,n,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),H(n)}function q(t,e,i=[]){let s=new X.FPoint(t[0],-t[1]),r=et([e])[0],n=X.Clipper.PointInPolygon(s,r);for(let o of i){let e=q(t,o);1===e?n=0:-1===e&&(n=-1)}return n}function J(t){let e=et([t]);return X.Clipper.Area(e[0])}function K(t){return Math.abs(J(t))}function Z(t){let e=Math.abs(J(t[0]));for(let i of t.slice(1))e-=Math.abs(J(i));return e}function Q(t,e=.01){let i=et(t);return it(X.Clipper.CleanPolygons(i,e))}function tt(t,e=.01){return Q([t],e)[0]}function et(t=[]){let e=[],i=0;for(let s=0;s<t.length;s++){let r=t[s];if(!r?.length)continue;let n=new Array(r.length);for(let t=0;t<r.length;t++){let e=r[t];n[t]={X:e[0],Y:-e[1]}}e[i]=n,i++}return e}function it(t){let e=new Array(t.length);for(let i=0;i<t.length;i++){let s=t[i]||[],r=new Array(s.length);for(let t=0;t<s.length;t++){let e=s[t];r[t]=[e.X,-e.Y]}e[i]=r}return e}var st=1e-6,rt="undefined"!=typeof Float32Array?Float32Array:Array;function nt(){var t=new rt(16);return rt!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function ot(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function at(t,e){if(t===e){var i=e[1],s=e[2],r=e[3],n=e[6],o=e[7],a=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=i,t[6]=e[9],t[7]=e[13],t[8]=s,t[9]=n,t[11]=e[14],t[12]=r,t[13]=o,t[14]=a}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function lt(t,e){var i=e[0],s=e[1],r=e[2],n=e[3],o=e[4],a=e[5],l=e[6],h=e[7],u=e[8],c=e[9],d=e[10],p=e[11],f=e[12],m=e[13],g=e[14],y=e[15],v=i*a-s*o,x=i*l-r*o,b=i*h-n*o,w=s*l-r*a,_=s*h-n*a,P=r*h-n*l,E=u*m-c*f,T=u*g-d*f,A=u*y-p*f,I=c*g-d*m,S=c*y-p*m,C=d*y-p*g,M=v*C-x*S+b*I+w*A-_*T+P*E;return M?(M=1/M,t[0]=(a*C-l*S+h*I)*M,t[1]=(r*S-s*C-n*I)*M,t[2]=(m*P-g*_+y*w)*M,t[3]=(d*_-c*P-p*w)*M,t[4]=(l*A-o*C-h*T)*M,t[5]=(i*C-r*A+n*T)*M,t[6]=(g*b-f*P-y*x)*M,t[7]=(u*P-d*b+p*x)*M,t[8]=(o*S-a*A+h*E)*M,t[9]=(s*A-i*S-n*E)*M,t[10]=(f*_-m*b+y*v)*M,t[11]=(c*b-u*_-p*v)*M,t[12]=(a*T-o*I-l*E)*M,t[13]=(i*I-s*T+r*E)*M,t[14]=(m*x-f*w-g*v)*M,t[15]=(u*w-c*x+d*v)*M,t):null}function ht(t,e,i){var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],l=e[5],h=e[6],u=e[7],c=e[8],d=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],v=e[15],x=i[0],b=i[1],w=i[2],_=i[3];return t[0]=x*s+b*a+w*c+_*m,t[1]=x*r+b*l+w*d+_*g,t[2]=x*n+b*h+w*p+_*y,t[3]=x*o+b*u+w*f+_*v,x=i[4],b=i[5],w=i[6],_=i[7],t[4]=x*s+b*a+w*c+_*m,t[5]=x*r+b*l+w*d+_*g,t[6]=x*n+b*h+w*p+_*y,t[7]=x*o+b*u+w*f+_*v,x=i[8],b=i[9],w=i[10],_=i[11],t[8]=x*s+b*a+w*c+_*m,t[9]=x*r+b*l+w*d+_*g,t[10]=x*n+b*h+w*p+_*y,t[11]=x*o+b*u+w*f+_*v,x=i[12],b=i[13],w=i[14],_=i[15],t[12]=x*s+b*a+w*c+_*m,t[13]=x*r+b*l+w*d+_*g,t[14]=x*n+b*h+w*p+_*y,t[15]=x*o+b*u+w*f+_*v,t}function ut(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t}function ct(t,e){var i=new rt(3);!function(t,e){var i=e[0],s=e[1],r=e[2],n=e[4],o=e[5],a=e[6],l=e[8],h=e[9],u=e[10];t[0]=Math.sqrt(i*i+s*s+r*r),t[1]=Math.sqrt(n*n+o*o+a*a),t[2]=Math.sqrt(l*l+h*h+u*u)}(i,e);var s=1/i[0],r=1/i[1],n=1/i[2],o=e[0]*s,a=e[1]*r,l=e[2]*n,h=e[4]*s,u=e[5]*r,c=e[6]*n,d=e[8]*s,p=e[9]*r,f=e[10]*n,m=o+u+f,g=0;return m>0?(g=2*Math.sqrt(m+1),t[3]=.25*g,t[0]=(c-p)/g,t[1]=(d-l)/g,t[2]=(a-h)/g):o>u&&o>f?(g=2*Math.sqrt(1+o-u-f),t[3]=(c-p)/g,t[0]=.25*g,t[1]=(a+h)/g,t[2]=(d+l)/g):u>f?(g=2*Math.sqrt(1+u-o-f),t[3]=(d-l)/g,t[0]=(a+h)/g,t[1]=.25*g,t[2]=(c+p)/g):(g=2*Math.sqrt(1+f-o-u),t[3]=(a-h)/g,t[0]=(d+l)/g,t[1]=(c+p)/g,t[2]=.25*g),t}function dt(){var t=new rt(3);return rt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function pt(t){var e=new rt(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function ft(t,e,i){var s=new rt(3);return s[0]=t,s[1]=e,s[2]=i,s}function mt(t,e,i,s){return t[0]=e,t[1]=i,t[2]=s,t}function gt(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t[2]=e[2]+i[2],t}function yt(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t[2]=e[2]-i[2],t}function vt(t,e){var i=e[0],s=e[1],r=e[2],n=i*i+s*s+r*r;return n>0&&(n=1/Math.sqrt(n)),t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t}function xt(t,e,i){var s=e[0],r=e[1],n=e[2],o=i[0],a=i[1],l=i[2];return t[0]=r*l-n*a,t[1]=n*o-s*l,t[2]=s*a-r*o,t}function bt(t,e,i){var s=e[0],r=e[1],n=e[2],o=i[3]*s+i[7]*r+i[11]*n+i[15];return o=o||1,t[0]=(i[0]*s+i[4]*r+i[8]*n+i[12])/o,t[1]=(i[1]*s+i[5]*r+i[9]*n+i[13])/o,t[2]=(i[2]*s+i[6]*r+i[10]*n+i[14])/o,t}var wt=yt;function _t(){var t=new rt(4);return rt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function Pt(t,e,i){i*=.5;var s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t}dt(),function(){var t,e=(t=new rt(4),rt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t)}();var Et;function Tt(){var t=new rt(2);return rt!=Float32Array&&(t[0]=0,t[1]=0),t}dt(),ft(1,0,0),ft(0,1,0),_t(),_t(),Et=new rt(9),rt!=Float32Array&&(Et[1]=0,Et[2]=0,Et[3]=0,Et[5]=0,Et[6]=0,Et[7]=0),Et[0]=1,Et[4]=1,Et[8]=1,function(){var t=Tt()}();var At="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function It(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function St(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var i=function t(){var i=!1;try{i=this instanceof t}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};i.prototype=e.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(i,e,s.get?s:{enumerable:!0,get:function(){return t[e]}})}),i}var Ct,Mt={exports:{}};var Ot=function(){if(Ct)return Mt.exports;function t(t,i,r){r=r||2;var n,o,a,u,c,p,f,m=i&&i.length,g=m?i[0]*r:t.length,y=e(t,0,g,r,!0),v=[];if(!y||y.next===y.prev)return v;if(m&&(y=function(t,i,s,r){var n,o,a,u=[];for(n=0,o=i.length;n<o;n++)(a=e(t,i[n]*r,n<o-1?i[n+1]*r:t.length,r,!1))===a.next&&(a.steiner=!0),u.push(d(a));for(u.sort(l),n=0;n<u.length;n++)s=h(u[n],s);return s}(t,i,y,r)),t.length>80*r){n=a=t[0],o=u=t[1];for(var x=r;x<g;x+=r)(c=t[x])<n&&(n=c),(p=t[x+1])<o&&(o=p),c>a&&(a=c),p>u&&(u=p);f=0!==(f=Math.max(a-n,u-o))?32767/f:0}return s(y,v,r,n,o,f,0),v}function e(t,e,i,s,r){var n,o;if(r===T(t,e,i,s)>0)for(n=e;n<i;n+=s)o=_(n,t[n],t[n+1],o);else for(n=i-s;n>=e;n-=s)o=_(n,t[n],t[n+1],o);return o&&g(o,o.next)&&(P(o),o=o.next),o}function i(t,e){if(!t)return t;e||(e=t);var i,s=t;do{if(i=!1,s.steiner||!g(s,s.next)&&0!==m(s.prev,s,s.next))s=s.next;else{if(P(s),(s=e=s.prev)===s.next)break;i=!0}}while(i||s!==e);return e}function s(t,e,l,h,u,d,p){if(t){!p&&d&&function(t,e,i,s){var r=t;do{0===r.z&&(r.z=c(r.x,r.y,e,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){var e,i,s,r,n,o,a,l,h=1;do{for(i=t,t=null,n=null,o=0;i;){for(o++,s=i,a=0,e=0;e<h&&(a++,s=s.nextZ);e++);for(l=h;a>0||l>0&&s;)0!==a&&(0===l||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,l--),n?n.nextZ=r:t=r,r.prevZ=n,n=r;i=s}n.nextZ=null,h*=2}while(o>1)}(r)}(t,h,u,d);for(var f,m,g=t;t.prev!==t.next;)if(f=t.prev,m=t.next,d?n(t,h,u,d):r(t))e.push(f.i/l|0),e.push(t.i/l|0),e.push(m.i/l|0),P(t),t=m.next,g=m.next;else if((t=m)===g){p?1===p?s(t=o(i(t),e,l),e,l,h,u,d,2):2===p&&a(t,e,l,h,u,d):s(i(t),e,l,h,u,d,1);break}}}function r(t){var e=t.prev,i=t,s=t.next;if(m(e,i,s)>=0)return!1;for(var r=e.x,n=i.x,o=s.x,a=e.y,l=i.y,h=s.y,u=r<n?r<o?r:o:n<o?n:o,c=a<l?a<h?a:h:l<h?l:h,d=r>n?r>o?r:o:n>o?n:o,f=a>l?a>h?a:h:l>h?l:h,g=s.next;g!==e;){if(g.x>=u&&g.x<=d&&g.y>=c&&g.y<=f&&p(r,a,n,l,o,h,g.x,g.y)&&m(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function n(t,e,i,s){var r=t.prev,n=t,o=t.next;if(m(r,n,o)>=0)return!1;for(var a=r.x,l=n.x,h=o.x,u=r.y,d=n.y,f=o.y,g=a<l?a<h?a:h:l<h?l:h,y=u<d?u<f?u:f:d<f?d:f,v=a>l?a>h?a:h:l>h?l:h,x=u>d?u>f?u:f:d>f?d:f,b=c(g,y,e,i,s),w=c(v,x,e,i,s),_=t.prevZ,P=t.nextZ;_&&_.z>=b&&P&&P.z<=w;){if(_.x>=g&&_.x<=v&&_.y>=y&&_.y<=x&&_!==r&&_!==o&&p(a,u,l,d,h,f,_.x,_.y)&&m(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,P.x>=g&&P.x<=v&&P.y>=y&&P.y<=x&&P!==r&&P!==o&&p(a,u,l,d,h,f,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;P=P.nextZ}for(;_&&_.z>=b;){if(_.x>=g&&_.x<=v&&_.y>=y&&_.y<=x&&_!==r&&_!==o&&p(a,u,l,d,h,f,_.x,_.y)&&m(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;P&&P.z<=w;){if(P.x>=g&&P.x<=v&&P.y>=y&&P.y<=x&&P!==r&&P!==o&&p(a,u,l,d,h,f,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;P=P.nextZ}return!0}function o(t,e,s){var r=t;do{var n=r.prev,o=r.next.next;!g(n,o)&&y(n,r,r.next,o)&&b(n,o)&&b(o,n)&&(e.push(n.i/s|0),e.push(r.i/s|0),e.push(o.i/s|0),P(r),P(r.next),r=t=o),r=r.next}while(r!==t);return i(r)}function a(t,e,r,n,o,a){var l=t;do{for(var h=l.next.next;h!==l.prev;){if(l.i!==h.i&&f(l,h)){var u=w(l,h);return l=i(l,l.next),u=i(u,u.next),s(l,e,r,n,o,a,0),void s(u,e,r,n,o,a,0)}h=h.next}l=l.next}while(l!==t)}function l(t,e){return t.x-e.x}function h(t,e){var s=function(t,e){var i,s=e,r=t.x,n=t.y,o=-1/0;do{if(n<=s.y&&n>=s.next.y&&s.next.y!==s.y){var a=s.x+(n-s.y)*(s.next.x-s.x)/(s.next.y-s.y);if(a<=r&&a>o&&(o=a,i=s.x<s.next.x?s:s.next,a===r))return i}s=s.next}while(s!==e);if(!i)return null;var l,h=i,c=i.x,d=i.y,f=1/0;s=i;do{r>=s.x&&s.x>=c&&r!==s.x&&p(n<d?r:o,n,c,d,n<d?o:r,n,s.x,s.y)&&(l=Math.abs(n-s.y)/(r-s.x),b(s,t)&&(l<f||l===f&&(s.x>i.x||s.x===i.x&&u(i,s)))&&(i=s,f=l)),s=s.next}while(s!==h);return i}(t,e);if(!s)return e;var r=w(s,t);return i(r,r.next),i(s,s.next)}function u(t,e){return m(t.prev,t,e.prev)<0&&m(e.next,t,t.next)<0}function c(t,e,i,s,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function d(t){var e=t,i=t;do{(e.x<i.x||e.x===i.x&&e.y<i.y)&&(i=e),e=e.next}while(e!==t);return i}function p(t,e,i,s,r,n,o,a){return(r-o)*(e-a)>=(t-o)*(n-a)&&(t-o)*(s-a)>=(i-o)*(e-a)&&(i-o)*(n-a)>=(r-o)*(s-a)}function f(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&y(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(b(t,e)&&b(e,t)&&function(t,e){var i=t,s=!1,r=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s}(t,e)&&(m(t.prev,t,e.prev)||m(t,e.prev,e))||g(t,e)&&m(t.prev,t,t.next)>0&&m(e.prev,e,e.next)>0)}function m(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function g(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,i,s){var r=x(m(t,e,i)),n=x(m(t,e,s)),o=x(m(i,s,t)),a=x(m(i,s,e));return r!==n&&o!==a||(!(0!==r||!v(t,i,e))||(!(0!==n||!v(t,s,e))||(!(0!==o||!v(i,t,s))||!(0!==a||!v(i,e,s)))))}function v(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function x(t){return t>0?1:t<0?-1:0}function b(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function w(t,e){var i=new E(t.i,t.x,t.y),s=new E(e.i,e.x,e.y),r=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=r,r.prev=i,s.next=i,i.prev=s,n.next=s,s.prev=n,s}function _(t,e,i,s){var r=new E(t,e,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function P(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function E(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function T(t,e,i,s){for(var r=0,n=e,o=i-s;n<i;n+=s)r+=(t[o]-t[n])*(t[n+1]+t[o+1]),o=n;return r}return Ct=1,Mt.exports=t,Mt.exports.default=t,t.deviation=function(t,e,i,s){var r=e&&e.length,n=r?e[0]*i:t.length,o=Math.abs(T(t,0,n,i));if(r)for(var a=0,l=e.length;a<l;a++){var h=e[a]*i,u=a<l-1?e[a+1]*i:t.length;o-=Math.abs(T(t,h,u,i))}var c=0;for(a=0;a<s.length;a+=3){var d=s[a]*i,p=s[a+1]*i,f=s[a+2]*i;c+=Math.abs((t[d]-t[f])*(t[p+1]-t[d+1])-(t[d]-t[p])*(t[f+1]-t[d+1]))}return 0===o&&0===c?0:Math.abs((c-o)/o)},t.flatten=function(t){for(var e=t[0][0].length,i={vertices:[],holes:[],dimensions:e},s=0,r=0;r<t.length;r++){for(var n=0;n<t[r].length;n++)for(var o=0;o<e;o++)i.vertices.push(t[r][n][o]);r>0&&(s+=t[r-1].length,i.holes.push(s))}return i},Mt.exports}();const Nt=/* @__PURE__ */It(Ot);for(var Lt,Rt=[],Bt=0;Bt<256;++Bt)Rt.push((Bt+256).toString(16).slice(1));var kt=new Uint8Array(16);function Ft(){if(!Lt&&!(Lt="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lt(kt)}const Dt={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Ut(t,e,i){if(Dt.randomUUID&&!t)return Dt.randomUUID();var s=(t=t||{}).random||(t.rng||Ft)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(t,e=0){return(Rt[t[e+0]]+Rt[t[e+1]]+Rt[t[e+2]]+Rt[t[e+3]]+"-"+Rt[t[e+4]]+Rt[t[e+5]]+"-"+Rt[t[e+6]]+Rt[t[e+7]]+"-"+Rt[t[e+8]]+Rt[t[e+9]]+"-"+Rt[t[e+10]]+Rt[t[e+11]]+Rt[t[e+12]]+Rt[t[e+13]]+Rt[t[e+14]]+Rt[t[e+15]]).toLowerCase()}(s)}function Gt(t,e,i,s,r){Xt(t,e,i||0,s||t.length-1,r||Yt)}function Xt(t,e,i,s,r){for(;s>i;){if(s-i>600){var n=s-i+1,o=e-i+1,a=Math.log(n),l=.5*Math.exp(2*a/3),h=.5*Math.sqrt(a*l*(n-l)/n)*(o-n/2<0?-1:1);Xt(t,e,Math.max(i,Math.floor(e-o*l/n+h)),Math.min(s,Math.floor(e+(n-o)*l/n+h)),r)}var u=t[e],c=i,d=s;for(Wt(t,i,e),r(t[s],u)>0&&Wt(t,i,s);c<d;){for(Wt(t,c,d),c++,d--;r(t[c],u)<0;)c++;for(;r(t[d],u)>0;)d--}0===r(t[i],u)?Wt(t,i,d):Wt(t,++d,s),d<=e&&(i=d+1),e<=d&&(s=d-1)}}function Wt(t,e,i){var s=t[e];t[e]=t[i],t[i]=s}function Yt(t,e){return t<e?-1:t>e?1:0}class Ht{constructor(t=9){this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(t){let e=this.data;const i=[];if(!ie(t,e))return i;const s=this.toBBox,r=[];for(;e;){for(let n=0;n<e.children.length;n++){const o=e.children[n],a=e.leaf?s(o):o;ie(t,a)&&(e.leaf?i.push(o):ee(t,a)?this._all(o,i):r.push(o))}e=r.pop()}return i}collides(t){let e=this.data;if(!ie(t,e))return!1;const i=[];for(;e;){for(let s=0;s<e.children.length;s++){const r=e.children[s],n=e.leaf?this.toBBox(r):r;if(ie(t,n)){if(e.leaf||ee(t,n))return!0;i.push(r)}}e=i.pop()}return!1}load(t){if(!t||!t.length)return this;if(t.length<this._minEntries){for(let e=0;e<t.length;e++)this.insert(t[e]);return this}let e=this._build(t.slice(),0,t.length-1,0);if(this.data.children.length)if(this.data.height===e.height)this._splitRoot(this.data,e);else{if(this.data.height<e.height){const t=this.data;this.data=e,e=t}this._insert(e,this.data.height-e.height-1,!0)}else this.data=e;return this}insert(t){return t&&this._insert(t,this.data.height-1),this}clear(){return this.data=se([]),this}remove(t,e){if(!t)return this;let i=this.data;const s=this.toBBox(t),r=[],n=[];let o,a,l;for(;i||r.length;){if(i||(i=r.pop(),a=r[r.length-1],o=n.pop(),l=!0),i.leaf){const s=$t(t,i.children,e);if(-1!==s)return i.children.splice(s,1),r.push(i),this._condense(r),this}l||i.leaf||!ee(i,s)?a?(o++,i=a.children[o],l=!1):i=null:(r.push(i),n.push(o),o=0,a=i,i=i.children[0])}return this}toBBox(t){return t}compareMinX(t,e){return t.minX-e.minX}compareMinY(t,e){return t.minY-e.minY}toJSON(){return this.data}fromJSON(t){return this.data=t,this}_all(t,e){const i=[];for(;t;)t.leaf?e.push(...t.children):i.push(...t.children),t=i.pop();return e}_build(t,e,i,s){const r=i-e+1;let n,o=this._maxEntries;if(r<=o)return n=se(t.slice(e,i+1)),jt(n,this.toBBox),n;s||(s=Math.ceil(Math.log(r)/Math.log(o)),o=Math.ceil(r/Math.pow(o,s-1))),n=se([]),n.leaf=!1,n.height=s;const a=Math.ceil(r/o),l=a*Math.ceil(Math.sqrt(o));re(t,e,i,l,this.compareMinX);for(let h=e;h<=i;h+=l){const e=Math.min(h+l-1,i);re(t,h,e,a,this.compareMinY);for(let i=h;i<=e;i+=a){const r=Math.min(i+a-1,e);n.children.push(this._build(t,i,r,s-1))}}return jt(n,this.toBBox),n}_chooseSubtree(t,e,i,s){for(;s.push(e),!e.leaf&&s.length-1!==i;){let i,s=1/0,r=1/0;for(let n=0;n<e.children.length;n++){const o=e.children[n],a=Kt(o),l=Qt(t,o)-a;l<r?(r=l,s=a<s?a:s,i=o):l===r&&a<s&&(s=a,i=o)}e=i||e.children[0]}return e}_insert(t,e,i){const s=i?t:this.toBBox(t),r=[],n=this._chooseSubtree(s,this.data,e,r);for(n.children.push(t),Vt(n,s);e>=0&&r[e].children.length>this._maxEntries;)this._split(r,e),e--;this._adjustParentBBoxes(s,r,e)}_split(t,e){const i=t[e],s=i.children.length,r=this._minEntries;this._chooseSplitAxis(i,r,s);const n=this._chooseSplitIndex(i,r,s),o=se(i.children.splice(n,i.children.length-n));o.height=i.height,o.leaf=i.leaf,jt(i,this.toBBox),jt(o,this.toBBox),e?t[e-1].children.push(o):this._splitRoot(i,o)}_splitRoot(t,e){this.data=se([t,e]),this.data.height=t.height+1,this.data.leaf=!1,jt(this.data,this.toBBox)}_chooseSplitIndex(t,e,i){let s,r=1/0,n=1/0;for(let o=e;o<=i-e;o++){const e=zt(t,0,o,this.toBBox),a=zt(t,o,i,this.toBBox),l=te(e,a),h=Kt(e)+Kt(a);l<r?(r=l,s=o,n=h<n?h:n):l===r&&h<n&&(n=h,s=o)}return s||i-e}_chooseSplitAxis(t,e,i){const s=t.leaf?this.compareMinX:qt,r=t.leaf?this.compareMinY:Jt;this._allDistMargin(t,e,i,s)<this._allDistMargin(t,e,i,r)&&t.children.sort(s)}_allDistMargin(t,e,i,s){t.children.sort(s);const r=this.toBBox,n=zt(t,0,e,r),o=zt(t,i-e,i,r);let a=Zt(n)+Zt(o);for(let l=e;l<i-e;l++){const e=t.children[l];Vt(n,t.leaf?r(e):e),a+=Zt(n)}for(let l=i-e-1;l>=e;l--){const e=t.children[l];Vt(o,t.leaf?r(e):e),a+=Zt(o)}return a}_adjustParentBBoxes(t,e,i){for(let s=i;s>=0;s--)Vt(e[s],t)}_condense(t){for(let e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children,e.splice(e.indexOf(t[i]),1)):this.clear():jt(t[i],this.toBBox)}}function $t(t,e,i){if(!i)return e.indexOf(t);for(let s=0;s<e.length;s++)if(i(t,e[s]))return s;return-1}function jt(t,e){zt(t,0,t.children.length,e,t)}function zt(t,e,i,s,r){r||(r=se(null)),r.minX=1/0,r.minY=1/0,r.maxX=-1/0,r.maxY=-1/0;for(let n=e;n<i;n++){const e=t.children[n];Vt(r,t.leaf?s(e):e)}return r}function Vt(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function qt(t,e){return t.minX-e.minX}function Jt(t,e){return t.minY-e.minY}function Kt(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function Zt(t){return t.maxX-t.minX+(t.maxY-t.minY)}function Qt(t,e){return(Math.max(e.maxX,t.maxX)-Math.min(e.minX,t.minX))*(Math.max(e.maxY,t.maxY)-Math.min(e.minY,t.minY))}function te(t,e){const i=Math.max(t.minX,e.minX),s=Math.max(t.minY,e.minY),r=Math.min(t.maxX,e.maxX),n=Math.min(t.maxY,e.maxY);return Math.max(0,r-i)*Math.max(0,n-s)}function ee(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function ie(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function se(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function re(t,e,i,s,r){const n=[e,i];for(;n.length;){if((i=n.pop())-(e=n.pop())<=s)continue;const o=e+Math.ceil((i-e)/s/2)*s;Gt(t,o,e,i,r),n.push(e,o,o,i)}}var ne,oe={exports:{}};var ae,le,he,ue,ce=function(){if(ne)return oe.exports;function t(){}return ne=1,t.prototype={on:function(t,e,i){var s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var s=this;function r(){s.off(t,r),e.apply(i,arguments)}return r._=e,this.on(t,r,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),s=0,r=i.length;s<r;s++)i[s].fn.apply(i[s].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),s=i[t],r=[];if(s&&e)for(var n=0,o=s.length;n<o;n++)s[n].fn!==e&&s[n].fn._!==e&&r.push(s[n]);return r.length?i[t]=r:delete i[t],this}},oe.exports=t,oe.exports.TinyEmitter=t,oe.exports}(),de=t=>{throw TypeError(t)},pe=(t,e,i)=>e.has(t)||de("Cannot "+i),fe=(t,e,i)=>(pe(t,e,"read from private field"),i?i.call(t):e.get(t)),me=(t,e,i)=>e.has(t)?de("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),ge=(t,e,i,s)=>(pe(t,e,"write to private field"),e.set(t,i),i),ye=(t,e,i)=>(pe(t,e,"access private method"),i);let ve=new class extends E{error(...t){this.levels.includes("errors")&&(t.length>0&&(t[0]="Internal error: "+t[0]),console.error(...t),this.emit("error",...t))}}(["info","warnings","errors"]);class xe{constructor(t){this.spaceGraph=null,this.type=t}}class be extends xe{constructor(t,e){super(e),this.name="",this.customId="",this.id=t}copyForClone(t){this.name=t.name,this.customId=t.customId}setName(t){this.name=t,this.emit("node-property-change",this,"name")}setCustomId(t){this.customId=t,this.emit("node-property-change",this,"customId")}emit(t,...e){this.spaceGraph&&this.spaceGraph.emit(t,...e)}toJSON(){return{type:this.type,id:this.id,name:""===this.name?void 0:this.name,customId:""===this.customId?void 0:this.customId}}}const we="material:color";class _e extends be{constructor(t,e=[1,1,1],i=1){super(t,we),this.color=[...e],this.opacity=i}toJSON(){let t;return t=1===this.opacity?[...this.color]:[this.color[0],this.color[1],this.color[2],this.opacity],{...super.toJSON(),value:t}}}const Pe="material:standard";class Ee extends be{constructor(t,e){super(t,Pe),this.reference=e}toJSON(){return{...super.toJSON(),reference:this.reference}}}const Te="material:embedded";class Ae extends be{constructor(t,e,i){super(t,Ie),this.reference=e,this.format=i}toJSON(){return ve.warn("Embedded material not supported in materials section."),{...super.toJSON(),type:"material:color",value:[1,1,1,1]}}}const Ie="material:basic";class Se extends be{constructor(t){super(t,Ie),this.colorDiffuse=[1,1,1],this.colorSpecular=[1,1,1],this.specularCoefficient=1,this.opacity=1}copyForClone(t){super.copyForClone(t),this.colorDiffuse=[...t.colorDiffuse],this.colorSpecular=[...t.colorSpecular],this.specularCoefficient=t.specularCoefficient,this.opacity=t.opacity}toJSON(){return{...super.toJSON(),colorDiffuse:[...this.colorDiffuse],colorSpecular:[...this.colorSpecular],specularCoefficient:this.specularCoefficient,opacity:this.opacity}}}const Ce="default",Me=[1,1,1],Oe=[1,1,1],Ne=[...Me,1];function Le(t,e){return Number.isFinite(t)?!(t<0||t>1)||(ve.warn(`Value out of range (0 to 1) in color literal: '${e}'.`),!1):(ve.warn(`Invalid float value in color literal: '${e}'.`),!1)}function Re(t,e){return Number.isInteger(t)?!(t<0||t>255)||(ve.warn(`Value out of range (0 to 255) in color literal: '${e}'.`),!1):(ve.warn(`Invalid byte value in color literal: '${e}'.`),!1)}function Be(t){if(t.length<3||t.length>4)return ve.warn(`Invalid number of components in color literal: '${t}'.`),Ne;let e=t.toString(),i=[0,0,0,0];for(let s=0;s<t.length;s++){let r=t[s];if(!Le(r,e))return Ne;i[s]=r}return 3===t.length&&(i[3]=Ne[3]),i}function ke(t){let e,i,s,r,n=t.substring(1),o=parseInt(n,16);if(isNaN(o))return ve.warn(`Invalid hexadecimal color literal: '${t}'.`),Ne;if(3===n.length?o=o<<4|15:6===n.length&&(o=o<<8|255),3===n.length||4===n.length)e=(o>>12&15)/15,i=(o>>8&15)/15,s=(o>>4&15)/15,r=(15&o)/15;else{if(6!==n.length&&8!==n.length)return ve.warn(`Invalid hexademical color literal length: '${t}'.`),Ne;e=(o>>24&255)/255,i=(o>>16&255)/255,s=(o>>8&255)/255,r=(255&o)/255}return[e,i,s,r]}function Fe(t,e){if(!t.endsWith(")"))return ve.warn(`Missing closing parenthesis: '${t}'.`),Ne;let i=e?5:4,s=t.substring(i,t.length-1).split(",");if(s.length<3||s.length>4||3===s.length&&e||4===s.length&&!e)return ve.warn(`Invalid number of components in color literal: '${t}'.`),Ne;let r=[0,0,0,0];for(let n=0;n<3;n++){let e=s[n],i=parseFloat(e);if(!Re(i,t))return Ne;r[n]=i/255}if(4===s.length){let e=parseFloat(s[3]);if(!Le(e,t))return Ne;r[3]=e}else r[3]=Ne[3];return r}function De([t,e,i]){return"#"+Math.round(255*t).toString(16).padStart(2,"0")+Math.round(255*e).toString(16).padStart(2,"0")+Math.round(255*i).toString(16).padStart(2,"0")}function Ue({name:t=Ce,color:e=Me,specularColor:i=Oe,specularCoefficient:s=1,opacity:r=1,reference:n}={}){return n?{name:t,reference:n}:{name:t,color:[...e],specularColor:[...i],specularCoefficient:s,opacity:r}}function Ge(t,e={}){if(Array.isArray(t)){let[e,i,s,r]=Be(t);return Ue({name:t.toString(),color:[e,i,s],opacity:r})}if("string"==typeof t){let i,s,r,n;if(""===t)return ve.warn("Empty string not a valid color value."),Ue({name:t});if(t===Ce)return Ue();if("#"===t.charAt(0))[i,s,r,n]=ke(t);else if(t.startsWith("rgb("))[i,s,r,n]=Fe(t,!1);else{if(!t.startsWith("rgba(")){if(t.startsWith("asm:")){let e=t.substring(4,t.length);return Ue({name:t,reference:e})}if(t.startsWith("data3d:")){let e=t.substring(7,t.length);return Ue({name:t,reference:e})}{let i=e[t];if(void 0===i)return ve.warn(`Unknown material: '${t}'.`),Ue();{let e;switch(i.type){case we:e=Ue({name:t,color:i.color,specularColor:i.color});break;case Pe:e=Ue({name:t,reference:i.reference});break;case Te:ve.warn("Embedded material not supported in materials section."),e=Ue();break;case Ie:e=Ue({name:t,color:i.colorDiffuse,specularColor:i.colorSpecular,specularCoefficient:i.specularCoefficient,opacity:i.opacity});break;default:ve.warn(`Unknown material type ${i.type}.`),e=Ue()}return e}}}[i,s,r,n]=Fe(t,!0)}return Ue({name:t,color:[i,s,r],opacity:n})}return ve.warn(`Material can only be an array or a string: '${t}'.`),Ue()}const Xe="default";function We(t,e){return new Array(e-t).fill(void 0).map((e,i)=>t+i)}function Ye(t,e){let i=new Array(3*e.length),s=0;for(let r=0;r<e.length;r++){let n=3*e[r];i[s++]=t[n],i[s++]=t[n+1],i[s++]=t[n+2]}return i}function He(t,e,i){let s=3*e,r=new Array(s*i.length),n=0;for(let o=0;o<i.length;o++){let e=s*i[o];for(let i=0;i<s;i++)r[n++]=t[e++]}return r}function $e(t,e,i){let s=[],r=e.faces,{surfaces:n,materials:o}=function(t){let e=t.surfaces??{[Xe]:"all"},i=t.materials??{[Xe]:"default"};if(e&&0===Object.keys(e).length)ve.warn("Empty 'surfaces' field not allowed.");else if(i&&0===Object.keys(i).length)ve.warn("Empty 'materials' field not allowed.");else if(t.material)t.materials?ve.warn("Cannot use 'material' and 'materials' at the same time."):i={[Xe]:t.material};else if(i[Xe])Object.keys(i).length>1&&ve.warn("Extraneous material assignments ignored.");else{let t=Object.keys(e);for(let e of t)i[e]||ve.warn(`Surface '${e}' not assigned a material, using default.`);let s=Object.keys(i);for(let i of s)e[i]||ve.warn(`Surface '${i}' not found.`)}return{surfaces:e,materials:i}}(t);for(let[a,l]of Object.entries(n)){if("all"!==l&&!Array.isArray(l)&&"object"!=typeof l){ve.warn(`Unknown face indices type, skipping surface '${a}'.`);continue}let n=[];if("geometry:mesh"===t.type)if("all"===l){let t=e.indices.length/3;n.push(...We(0,t))}else if(Array.isArray(l))n.push(...l);else{let{start:t,end:e}=l;n.push(...We(t,e))}else if("all"===l)for(let t of r){let{index:e,count:i}=t;n.push(...We(e,e+i))}else if(Array.isArray(l))for(let t=0;t<l.length;t++){let e=r[l[t]],{index:i,count:s}=e;n.push(...We(i,i+s))}else{let{start:t,end:e}=l;for(let i=t;i<e;i++){let t=r[i],{index:e,count:s}=t;n.push(...We(e,e+s))}}let h,{vertices:u,indices:c,normals:d,uvs:p}=e;h=o[Xe]?o[Xe]:o[a]??"default";let f=Ge(h,i),m={name:a,vertices:u,indices:Ye(c,n),material:f};d&&(m.normals=He(d,3,n)),p&&(m.uvs=He(p,2,n)),s.push(m)}return s}function je(t,e){let i=function(t){if(Array.isArray(t))return[t];if("vector3:list"===t.type)return t.list;if("vector3:range"===t.type){let{start:e,step:i,count:s}=t.range;return function(t,e,i){let s=[];for(let r=0;r<i;r++){let i=t[0]+r*e[0],n=t[1]+r*e[1],o=t[2]+r*e[2];s.push([i,n,o])}return s}(e,i,s)}return ve.warn(`Unknown position type: ${t}`),[[0,0,0]]}(t),s=function(t){if("number"==typeof t)return[t];if("number:list"===t.type)return t.list;if("number:range"===t.type){let{start:e,step:i,count:s}=t.range;return function(t,e,i){let s=[];for(let r=0;r<i;r++){let i=t+r*e;s.push(i)}return s}(e,i,s)}return ve.warn(`Unknown rotation type: ${t}`),[0]}(e),r=Math.max(i.length,s.length),n=[];for(let o=0;o<r;o++){let t=i[Math.min(o,i.length-1)],e=s[Math.min(o,s.length-1)];void 0!==t&&void 0!==e&&n.push({position:t,rotation:e})}return n}function ze(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Ve(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var i=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};i.prototype=e.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(i,e,s.get?s:{enumerable:!0,get:function(){return t[e]}})}),i}var qe={exports:{}};function Je(t,e){return t<e?-1:t>e?1:0}const Ke=/* @__PURE__ */Ve(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:class{constructor(t=[],e=Je){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(t){this.data.push(t),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:i}=this,s=e[t];for(;t>0;){const r=t-1>>1,n=e[r];if(i(s,n)>=0)break;e[t]=n,t=r}e[t]=s}_down(t){const{data:e,compare:i}=this,s=this.length>>1,r=e[t];for(;t<s;){let s=1+(t<<1),n=e[s];const o=s+1;if(o<this.length&&i(e[o],n)<0&&(s=o,n=e[o]),i(n,r)>=0)break;e[t]=n,t=s}e[t]=r}}},Symbol.toStringTag,{value:"Module"})));var Ze;const Qe=/* @__PURE__ */ze(function(){if(Ze)return qe.exports;Ze=1;var t=Ke;function e(e,r,n){var o,a,l,h;r=r||1;for(var u=0;u<e[0].length;u++){var c=e[0][u];(!u||c[0]<o)&&(o=c[0]),(!u||c[1]<a)&&(a=c[1]),(!u||c[0]>l)&&(l=c[0]),(!u||c[1]>h)&&(h=c[1])}var d=l-o,p=h-a,f=Math.min(d,p),m=f/2;if(0===f){var g=[o,a];return g.distance=0,g}for(var y=new t(void 0,i),v=o;v<l;v+=f)for(var x=a;x<h;x+=f)y.push(new s(v+m,x+m,m,e));var b=function(t){for(var e=0,i=0,r=0,n=t[0],o=0,a=n.length,l=a-1;o<a;l=o++){var h=n[o],u=n[l],c=h[0]*u[1]-u[0]*h[1];i+=(h[0]+u[0])*c,r+=(h[1]+u[1])*c,e+=3*c}return 0===e?new s(n[0][0],n[0][1],0,t):new s(i/e,r/e,0,t)}(e),w=new s(o+d/2,a+p/2,0,e);w.d>b.d&&(b=w);for(var _=y.length;y.length;){var P=y.pop();P.d>b.d&&(b=P,n&&console.log("found best %d after %d probes",Math.round(1e4*P.d)/1e4,_)),P.max-b.d<=r||(m=P.h/2,y.push(new s(P.x-m,P.y-m,m,e)),y.push(new s(P.x+m,P.y-m,m,e)),y.push(new s(P.x-m,P.y+m,m,e)),y.push(new s(P.x+m,P.y+m,m,e)),_+=4)}n&&(console.log("num probes: "+_),console.log("best distance: "+b.d));var E=[b.x,b.y];return E.distance=b.d,E}function i(t,e){return e.max-t.max}function s(t,e,i,s){this.x=t,this.y=e,this.h=i,this.d=function(t,e,i){for(var s=!1,n=1/0,o=0;o<i.length;o++)for(var a=i[o],l=0,h=a.length,u=h-1;l<h;u=l++){var c=a[l],d=a[u];c[1]>e!=d[1]>e&&t<(d[0]-c[0])*(e-c[1])/(d[1]-c[1])+c[0]&&(s=!s),n=Math.min(n,r(t,e,c,d))}return 0===n?0:(s?1:-1)*Math.sqrt(n)}(t,e,s),this.max=this.d+this.h*Math.SQRT2}function r(t,e,i,s){var r=i[0],n=i[1],o=s[0]-r,a=s[1]-n;if(0!==o||0!==a){var l=((t-r)*o+(e-n)*a)/(o*o+a*a);l>1?(r=s[0],n=s[1]):l>0&&(r+=o*l,n+=a*l)}return(o=t-r)*o+(a=e-n)*a}return t.default&&(t=t.default),qe.exports=e,qe.exports.default=e,qe.exports}());function ti(t,e){return[t[0]+e[0],t[1]+e[1]]}function ei(t){let e;return 0===t[0]?e=t[1]>0?Math.PI/2:t[1]<0?3*Math.PI/2:0:(e=Math.atan2(t[1],t[0]),e<0&&(e+=2*Math.PI)),e}function ii(t,e){return t[0]*e[1]-t[1]*e[0]}function si(t,e,i){return Math.abs(t[0]-e[0])<=i&&Math.abs(t[1]-e[1])<=i}function ri(t){return Math.sqrt(function(t){return t[0]*t[0]+t[1]*t[1]}(t))}function ni(t,e){return ri(ui(e,t))}function oi(t,e,i){return[t[0]+i*(e[0]-t[0]),t[1]+i*(e[1]-t[1])]}function ai(t){let e=ri(t);return[t[0]/e,t[1]/e]}function li(t){return[-t[1],t[0]]}function hi(t,e){return[t[0]*e,t[1]*e]}function ui(t,e){return[t[0]-e[0],t[1]-e[1]]}function ci(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}function di(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function pi(t,e){return function(t){return Math.hypot(t[0],t[1],t[2])}(di(e,t))}function fi(t,e,i){return[t[0]+i*(e[0]-t[0]),t[1]+i*(e[1]-t[1]),t[2]+i*(e[2]-t[2])]}function mi(t,e,i){let s=ii(ui(e,t),ui(i,t));return s>1e-7?1:s<-1e-7?-1:0}function gi(t,e){return ei([e[0]-t[0],e[1]-t[1]])}function yi(t,e,i,s){let r=ui(e,t),n=ui(s,i),o=function(t,e){return t[0]*e[0]+t[1]*e[1]}(r,n),a=ii(r,n);return Math.atan2(Math.abs(a),o)}function vi(t,e){let i=!1;const s=t[0],r=t[1];for(let n=0;n<e.length;n++){const t=e[n],o=n===e.length-1?e[0]:e[n+1];if(t[1]<r&&o[1]>=r||o[1]<r&&t[1]>=r){const e=o[0]-t[0],n=o[1]-t[1];Math.abs(n)>=1e-9&&t[0]+(r-t[1])/n*e<s&&(i=!i)}}return i}function xi(t,e){if(!vi(t,e[0]))return!1;for(let i=1;i<e.length;i++){if(vi(t,e[i]))return!1}return!0}function bi(t,e,i){return function(t,e,i){const s=ui(i,e),r=s[0]*s[0]+s[1]*s[1];let n;if(r<1e-9)n=e;else{const o=((t[0]-e[0])*s[0]+(t[1]-e[1])*s[1])/r;n=o<0?e:o>1?i:oi(e,i,o)}const o=ui(n,t);return o[0]*o[0]+o[1]*o[1]}(t,e,i)**.5}function wi(t){let e=0;for(let i=0;i<t.length;i++){let s=i,r=i<t.length-1?i+1:0,n=t[s],o=t[r];e+=n[0]*o[1]-o[0]*n[1]}return.5*e}function _i(t){return Math.abs(wi(t))}function Pi(t,e=.1){let i;if(function(t){if(0===t.length)return 0;let e=_i(t[0]);for(let i=1;i<t.length;i++)e-=_i(t[i]);return e}(t)<.1)i=function(t){const{min:e,max:i}=W([t]);return[e[0]+(i[0]-e[0])/2,e[1]+(i[1]-e[1])/2]}(t[0]);else{const s=Qe(t,e);i=[s[0],s[1]]}return i}function Ei(t){return wi(t)>0}function Ti(t,e,i){if(0!==t[0]||0!==t[1]||0!==t[2]||0!==e){let s=nt(),r=ft(t[0],t[1],t[2]),n=function(t=0,e=[0,1,0]){let i=t*Math.PI/180,s=_t();return Pt(s,e,i),s}(e,i);return function(t,e,i){var s=e[0],r=e[1],n=e[2],o=e[3],a=s+s,l=r+r,h=n+n,u=s*a,c=s*l,d=s*h,p=r*l,f=r*h,m=n*h,g=o*a,y=o*l,v=o*h;t[0]=1-(p+m),t[1]=c+v,t[2]=d-y,t[3]=0,t[4]=c-v,t[5]=1-(u+m),t[6]=f+g,t[7]=0,t[8]=d+y,t[9]=f-g,t[10]=1-(u+p),t[11]=0,t[12]=i[0],t[13]=i[1],t[14]=i[2],t[15]=1}(s,n,r),s}return nt()}function Ai(t){let e=dt(),i=_t();ut(e,t),ct(i,t);let s=dt(),r=(n=s,o=i,a=2*Math.acos(o[3]),(l=Math.sin(a/2))>st?(n[0]=o[0]/l,n[1]=o[1]/l,n[2]=o[2]/l):(n[0]=1,n[1]=0,n[2]=0),a);var n,o,a,l;return 0===r&&(s=[0,1,0]),{position:[e[0],e[1],e[2]],rotation:180*r/Math.PI,rotationAxis:[s[0],s[1],s[2]]}}function Ii(t,e){let i=dt();for(let s=0;s<t.length;s+=3)i[0]=t[s],i[1]=t[s+1],i[2]=t[s+2],bt(i,i,e),t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2]}function Si(t){let e=function(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=e[0],t[5]=e[1],t}(function(){var t=new rt(6);return rt!=Float32Array&&(t[1]=0,t[2]=0,t[4]=0,t[5]=0),t[0]=1,t[3]=1,t}(),t.position);return function(t,e,i){var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],l=e[5],h=Math.sin(i),u=Math.cos(i);t[0]=s*u+n*h,t[1]=r*u+o*h,t[2]=s*-h+n*u,t[3]=r*-h+o*u,t[4]=a,t[5]=l}(e,e,-t.rotation*Math.PI/180),e}function Ci(t,e){return function(t,e){let i=function(t,e,i){var s=e[0],r=e[1];return t[0]=i[0]*s+i[2]*r+i[4],t[1]=i[1]*s+i[3]*r+i[5],t}(Tt(),t.position,e),s=t.rotation+Math.atan2(-e[1],e[0])*(180/Math.PI);return{position:[i[0],i[1]],rotation:(r=s,n=360,(r%n+n)%n)};var r,n}(t,Si(e))}function Mi(t,e){return t.map(t=>{let{position:i}=Ci({position:t,rotation:0},e);return i})}function Oi({position:t=[0,0,0],rotation:e=0,rotationAxis:i=[0,1,0],name:s,vertices:r,indices:n,normals:o,uvs:a,material:l}){let h=je(t,e),u=[],c=[],d=[],p=[],f=nt();for(let g=0;g<h.length;g++){let t=h[g],{position:e,rotation:s}=t,l=Ti(e,s,i),m=r.slice();Ii(m,l);let y=u.length/3;for(const i of m)u.push(i);for(const i of n)c.push(y+i);if(Array.isArray(o)){ot(f,l),f[12]=0,f[13]=0,f[14]=0,at(f,f),lt(f,f);let t=o.slice();Ii(t,f),d.push(...t)}Array.isArray(a)&&p.push(...a)}let m={name:s,vertices:u,indices:c,material:l};return Array.isArray(o)&&(m.normals=d),Array.isArray(a)&&(m.uvs=p),m}class Ni{constructor(){this.polygons=[]}clone(){const t=new Ni;for(const e of this.polygons)t.polygons.push(e.clone());return t}toPolygons(){return this.polygons}union(t){var e=new Ni.Node(this.clone().polygons),i=new Ni.Node(t.clone().polygons);return e.clipTo(i),i.clipTo(e),i.invert(),i.clipTo(e),i.invert(),e.build(i.allPolygons()),Ni.fromPolygons(e.allPolygons())}subtract(t){var e=new Ni.Node(this.polygons),i=new Ni.Node(t.polygons);return e.invert(),e.clipTo(i),i.clipTo(e),i.invert(),i.clipTo(e),i.invert(),e.build(i.allPolygons()),e.invert(),Ni.fromPolygons(e.allPolygons())}intersect(t){var e=new Ni.Node(this.clone().polygons),i=new Ni.Node(t.clone().polygons);return e.invert(),i.clipTo(e),i.invert(),e.clipTo(i),i.clipTo(e),e.build(i.allPolygons()),e.invert(),Ni.fromPolygons(e.allPolygons())}inverse(){var t=this.clone();return t.polygons.forEach(function(t){t.flip()}),t}}(t=>{function e(t){return[-t[0],-t[1],-t[2]]}function i(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function s(t){const e=function(t){return Math.sqrt(i(t,t))}(t);return[t[0]/e,t[1]/e,t[2]/e]}t.fromPolygons=function(e){var i=new t;return i.polygons=e,i};t.Vertex=class{constructor(t,e){this.pos=t,this.normal=e}clone(){return new t.Vertex([...this.pos],this.normal?[...this.normal]:void 0)}flip(){this.normal&&(this.normal=e(this.normal))}interpolate(e,i){return new t.Vertex(fi(this.pos,e.pos,i),this.normal&&e.normal?fi(this.normal,e.normal,i):void 0)}};const r=class{constructor(t,e){this.normal=t,this.w=e}clone(){return new t.Plane([...this.normal],this.w)}flip(){this.normal=e(this.normal),this.w=-this.w}splitPolygon(e,s,r,n,o){for(var a=0,l=[],h=0;h<e.vertices.length;h++){var u=(v=i(this.normal,e.vertices[h].pos)-this.w)<-t.Plane.EPSILON?2:v>t.Plane.EPSILON?1:0;a|=u,l.push(u)}switch(a){case 0:(i(this.normal,e.plane.normal)>0?s:r).push(e);break;case 1:n.push(e);break;case 2:o.push(e);break;case 3:var c=[],d=[];for(h=0;h<e.vertices.length;h++){var p=(h+1)%e.vertices.length,f=l[h],m=l[p],g=e.vertices[h],y=e.vertices[p];if(2!=f&&c.push(g),1!=f&&d.push(2!=f?g.clone():g),3==(f|m)){var v=(this.w-i(this.normal,g.pos))/i(this.normal,di(y.pos,g.pos)),x=g.interpolate(y,v);c.push(x),d.push(x.clone())}}c.length>=3&&n.push(new t.Polygon(c,e.shared)),d.length>=3&&o.push(new t.Polygon(d,e.shared))}}};r.EPSILON=1e-5,r.fromPoints=function(e,r,n){var o,a,l=s((o=di(r,e),a=di(n,e),[o[1]*a[2]-o[2]*a[1],o[2]*a[0]-o[0]*a[2],o[0]*a[1]-o[1]*a[0]]));return new t.Plane(l,i(l,e))};let n=r;t.Plane=n;t.Polygon=class{constructor(e,i){this.vertices=e,this.shared=i,this.plane=t.Plane.fromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=[];for(const t of this.vertices)e.push(t.clone());return new t.Polygon(e,this.shared)}flip(){this.vertices.reverse();for(const t of this.vertices)t.flip();this.plane.flip()}};t.Node=class{constructor(t){this.plane=null,this.front=null,this.back=null,this.polygons=[],t&&this.build(t)}clone(){var e=new t.Node;e.plane=this.plane&&this.plane.clone(),e.front=this.front&&this.front.clone(),e.back=this.back&&this.back.clone();for(const t of this.polygons)e.polygons.push(t.clone());return e}invert(){var t;for(let i=0;i<this.polygons.length;i++)this.polygons[i].flip();null==(t=this.plane)||t.flip(),this.front&&this.front.invert(),this.back&&this.back.invert();const e=this.front;this.front=this.back,this.back=e}clipPolygons(t){if(!this.plane)return t.slice();for(var e=[],i=[],s=0;s<t.length;s++)this.plane.splitPolygon(t[s],e,i,e,i);this.front&&(e=this.front.clipPolygons(e)),i=this.back?this.back.clipPolygons(i):[];const r=new Array(e.length+i.length);for(let n=0;n<e.length;n++)r[n]=e[n];for(let n=0;n<i.length;n++)r[e.length+n]=i[n];return r}clipTo(t){this.polygons=t.clipPolygons(this.polygons),this.front&&this.front.clipTo(t),this.back&&this.back.clipTo(t)}allPolygons(t=!0){var e=t?this.polygons.slice():this.polygons;return this.front&&(e=e.concat(this.front.allPolygons(!1))),this.back&&(e=e.concat(this.back.allPolygons(!1))),e}build(e){if(e.length){this.plane||(this.plane=e[0].plane.clone());for(var i=[],s=[],r=0;r<e.length;r++)this.plane.splitPolygon(e[r],this.polygons,this.polygons,i,s);i.length&&(this.front||(this.front=new t.Node),this.front.build(i)),s.length&&(this.back||(this.back=new t.Node),this.back.build(s))}}}})(Ni||(Ni={}));const Li=Ni;function Ri(t,e,i){let s=.5*i,r=[[-s,-s,0],[s,-s,0],[s,s,0],[-s,s,0]],{u:n,v:o,n:a}=function(t){const e=1/Math.sqrt(2);let i=[0,0,0],s=[0,0,0],r=[0,0,0];return vt(r,t),xt(i,Math.abs(r[1])<e?ft(0,1,0):ft(1,0,0),t),xt(s,t,i),vt(i,i),vt(s,s),{u:i,v:s,n:r}}(e),l=t,h=function(t,e,i,s,r,n,o,a,l,h,u,c,d,p,f,m){var g=new rt(16);return g[0]=t,g[1]=e,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=u,g[11]=c,g[12]=d,g[13]=p,g[14]=f,g[15]=m,g}(n[0],n[1],n[2],0,o[0],o[1],o[2],0,a[0],a[1],a[2],0,l[0],l[1],l[2],1);for(let u of r)bt(u,u,h);return r}function Bi(t,e){const i=[],s=t.nextId++,{name:r,vertices:n,indices:o,material:a}=e;for(let l=0;l<o.length;l+=3){const t=3*o[l],e=3*o[l+1],h=3*o[l+2],u=[n[t],n[t+1],n[t+2]],c=[n[e],n[e+1],n[e+2]],d=[n[h],n[h+1],n[h+2]],p=[new Li.Vertex(u),new Li.Vertex(c),new Li.Vertex(d)];i.push(new Li.Polygon(p,{id:s,name:r,material:a}))}return i}function ki(){let t=Math.random(),e=Math.random(),i=Math.random();return Ue({name:De([t,e,i]),color:[t,e,i],opacity:1})}function Fi(t,e){const i=[],s=[],r={};for(let n=0;n<e.length;n++){const o=3*e[n],a=t[o],l=t[o+1],h=t[o+2],u=73856093*a^19349663*l^83492791*h;let c=r[u];void 0===c&&(c=i.push(a,l,h)/3-1,r[u]=c),s.push(c)}return{vertices:i,indices:s}}function Di(t,e){const i=[];for(const s of e){const e=Bi(t,s);for(const t of e)i.push(t)}return Li.fromPolygons(i)}function Ui(t,{debugMode:e=!1,sharedVertices:i=!0}={}){const s={},{polygons:r}=t;for(let n=0;n<r.length;n++){const t=r[n],i=t.vertices.length;if(i<3){ve.warn(`Skipping CSG polygon with '${i}' '${1===i?"vertex":"vertices"}.`);continue}const o=[];o.length=3*i;for(let e=0;e<i;e++){const i=t.vertices[e];o[3*e]=i.pos[0],o[3*e+1]=i.pos[1],o[3*e+2]=i.pos[2]}let a;if(3===i)a=[0,1,2];else{a=[];for(let t=1;t<i-1;t++)a.push(0,t,t+1)}if(e){const t=ki();s[n]={name:t.name,vertices:o,indices:a,material:t}}else{const{id:e,name:i,material:r}=t.shared,n=s[e];if(n){const t=n.vertices.length;n.vertices.length=t+o.length;for(let s=0;s<o.length;s++)n.vertices[t+s]=o[s];const e=n.indices.length;n.indices.length=e+a.length;const i=t/3;for(let s=0;s<a.length;s++)n.indices[e+s]=a[s]+i}else s[e]={name:i,vertices:o,indices:a,material:r}}}if(i)for(const n of Object.values(s)){const{vertices:t,indices:e}=n,i=Fi(t,e);n.vertices=i.vertices,n.indices=i.indices}return Object.values(s)}function Gi(t,e,i,s){let r,n,o,a,l;if("string"==typeof t){if(r=t,l=e[r],!l)return ve.warn(`Geometry '${r}' not found.`),[];n=[0,0,0],o=0,a=[0,1,0]}else{let i=t;if("string"==typeof i.geometry){if(r=i.geometry,l=e[r],!l)return ve.warn(`Geometry '${r}' not found.`),[]}else l=i.geometry;n=i.position??[0,0,0],o=i.rotation??0,a=i.rotationAxis??[0,1,0]}if(s.indexOf(l)>-1)return ve.warn(`Cycle detected while resolving geometry '${l.id}'.`),[];let h=os(l,e,i,s);"string"!=typeof t&&"csg:clip"!==t.type&&function(t,e,i,s){let r;if(t.material?t.materials?ve.warn("Cannot use 'material' and 'materials' at the same time."):r={[Xe]:t.material}:t.materials&&(0===Object.keys(t.materials).length?ve.warn("Empty 'materials' field not allowed."):r=t.materials),r)if(r[Xe]){let t=Ge(r[Xe],i);for(let i of e)i.material=t;Object.keys(r).length>1&&ve.warn(`Extraneous material assignments to '${s}' ignored.`)}else for(let[n,o]of Object.entries(r)){let t=e.find(t=>t.name===n);if(t){let e=Ge(o,i);t.material=e}else ve.warn(`Surface '${n}' not found in geometry '${s}', skipping material assignment.`)}}(t,h,i,l.id);let u=[];for(let c of h){let{name:t,vertices:e,indices:i,normals:s,uvs:r,material:l}=c,h=Oi({position:n,rotation:o,rotationAxis:a,name:t,vertices:e,indices:i,normals:s,uvs:r,material:l});u.push(h)}return u}function Xi(t,e,i,s,r){return[...t,...Gi(e,i,s,r)]}function Wi(t,e,i,s){let{plane:r,material:n}=i,o=Di(t,e);{let e=function(t,e,i,s,r=100){let n=t.nextId++,{position:o,normal:a}=e,l=Ge(i,s),h=[0,0,0],u=[0,0,0];vt(h,a),function(t,e,i,s){t[0]=e[0]+i[0]*s,t[1]=e[1]+i[1]*s,t[2]=e[2]+i[2]*s}(u,o,h,r);let c=Ri(o,h,r),d=Ri(u,h,r),p=c.concat(d),f=[[0,1,2,3],[4,5,6,7],[0,4,5,1],[1,5,6,2],[2,6,7,3],[3,7,4,0]],m=[];for(let g of f){let t=[];for(let i of g)t.push(new Li.Vertex(p[i]));let e=new Li.Polygon(t,{id:n,name:"",material:l});m.push(e)}return Li.fromPolygons(m)}(t,r,n,s);o.polygons.length>0&&(o=o.subtract(e))}return Ui(o,{debugMode:!1})}function Yi(t,e,i,s,r,n){const o=Gi(i,s,r,n),a=Di(t,e),l=Di(t,o);let h=[];if(a.polygons.length&&l.polygons.length){let t;switch(i.type){case"csg:subtract":t=a.subtract(l);break;case"csg:union":t=a.union(l);break;case"csg:intersect":t=a.intersect(l);break;default:t=a}h=Ui(t,{debugMode:!1})}return h}function Hi(t,e,i){e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2]}function $i(t,e,i){t[i+0]=e[0],t[i+1]=e[1],t[i+2]=e[2]}function ji(t,e){let i=new Array(3*e.length),s=dt(),r=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=0;for(let u=0;u<e.length;u+=3){let c=e[u],d=e[u+1],p=e[u+2];Hi(t,s,3*c),Hi(t,r,3*d),Hi(t,n,3*p),wt(o,r,s),wt(a,n,s),xt(l,o,a),vt(l,l),$i(i,l,h+0),$i(i,l,h+3),$i(i,l,h+6),h+=9}return i}function zi(t,e){let i=new Array(3*e.length),s=dt(),r=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=e.length/3,u=new Array(h),c=0;for(let f=0;f<e.length;f+=3){let i=e[f],h=e[f+1],d=e[f+2];Hi(t,s,3*i),Hi(t,r,3*h),Hi(t,n,3*d),wt(o,r,s),wt(a,n,s),xt(l,o,a),vt(l,l),u[c++]={index1:i,index2:h,index3:d,normal1:pt(l),normal2:pt(l),normal3:pt(l)}}let d=[];for(let f=0;f<t.length;f++)d[f]={normals:[],normal:dt()};for(let f=0;f<u.length;f++){let t=u[f],{index1:e,index2:i,index3:s}=t;d[e].normals.push(t.normal1),d[i].normals.push(t.normal2),d[s].normals.push(t.normal3)}for(let f=0;f<d.length;f++){let t=d[f],e=t.normals.length;if(e>0){let i=t.normal;mt(i,0,0,0);for(let s=0;s<e;s++)gt(i,i,t.normals[s]);vt(i,i)}}let p=0;for(let f=0;f<e.length;f+=3){let t=e[f],s=e[f+1],r=e[f+2],n=d[t].normal,o=d[s].normal,a=d[r].normal;$i(i,n,p+0),$i(i,o,p+3),$i(i,a,p+6),p+=9}return i}function Vi(t,e,i){e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2]}function qi(t,e){let i=new Array(2*e.length),s=dt(),r=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=0;for(let u=0;u<e.length;u+=3){let c,d,p=e[u],f=e[u+1],m=e[u+2];Vi(t,s,3*p),Vi(t,r,3*f),Vi(t,n,3*m),wt(o,r,s),wt(a,n,s),xt(l,o,a),vt(l,l),l[0]=Math.abs(l[0]),l[1]=Math.abs(l[1]),l[2]=Math.abs(l[2]),l[0]>=l[1]&&l[0]>=l[2]?(c=2,d=1):l[1]>=l[0]&&l[1]>=l[2]?(c=0,d=2):(c=0,d=1),i[h++]=s[c],i[h++]=s[d],i[h++]=r[c],i[h++]=r[d],i[h++]=n[c],i[h++]=n[d]}return i}function Ji(t,e){let i=new Array(2*e.length),s=0;for(let r=0;r<e.length;r++){let n=3*e[r],o=t[n],a=t[n+1],l=t[n+2],h=.5+Math.atan2(o,l)/(2*Math.PI),u=.5+Math.asin(a)/Math.PI;i[s++]=h,i[s++]=u}return i}function Ki(t,e,i){let s=Math.cos(e),r=Math.sin(e);return[t*r*Math.cos(i),t*s,t*r*Math.sin(i)]}const Zi=48,Qi=12;function ts(t,e){return[e*Math.cos(t),-e*Math.sin(t)]}function es(t,e,i,s=!0){let r=[],n=e-t,o=function(t,e){let i=Math.ceil(Zi/(2*Math.PI)*t*e);const s=Math.ceil(Qi/(2*Math.PI)*t);return Math.max(s,i)}(Math.abs(n),i),a=n/o;for(let l=0;l<o;l++){let e=ts(t+l*a,i);r.push(e)}if(s){let t=ts(e,i);r.push(t)}return r}function is(t){let e=[];switch(t.type){case"curve:line":e.push(t.start,t.end);break;case"curve:arc":e=es(Math.PI*t.startAngle/180,Math.PI*t.endAngle/180,t.radius);break;case"curve:polyline":e=t.points}return e}function ss(t){let e=[],i=[],s=[];switch(t.type){case"curve:circle":e=es(0,2*Math.PI,t.radius,!1),i.push({index:0,count:e.length});break;case"curve:polygon":e=t.points;for(let t=0;t<e.length;t++)i.push({index:t,count:1});break;case"curve:polygonWithHoles":e=t.polygons[0];for(let t=0;t<e.length;t++)i.push({index:t,count:1});const r=t.polygons.slice(1);if(r.length>=1){const t=r.length>1?Y(r):r;for(let e of t)s.push(ss({type:"curve:polygon",points:e}))}break;case"curve:rectangle":let{dimensions:n}=t,o=n[0],a=n[1];e=[[0,0],[0,a],[o,a],[o,0]];for(let t=0;t<e.length;t++)i.push({index:t,count:1});break;case"curve:composite":const l=1e-7;let h,u,c=t.segments;for(let t=0;t<c.length;t++){let s=is(c[t]),r=s[0],n=s[s.length-1];0===t||si(r,u,l)||ve.warn(`Composite curve segments ${t} and ${t+1} are not continuous.`),0===t&&(h=r),u=n,i.push({index:e.length,count:s.length-1}),e.push(...s.slice(0,s.length-1))}c.length>0&&!si(u,h,l)&&ve.warn("Composite curve not closed.")}return{points:e,segmentRanges:i,holes:s}}function rs(t,e,i){let s,r=i.holes??[],n=i.y??0,o=i.flipSide??!1,a=t,l=[];if(8===a.length&&0===r.length){s=(e?o:!o)?[3,0,1,1,2,3]:[1,0,3,3,2,1]}else{if(r.length>0){let t=new Array(r.length);for(let e=0;e<r.length;e++)t[e]=a.length/2,a=a.concat(r[e]);s=Nt(a,t)}else s=Nt(a);if(!o)for(let t=0;t<s.length;t+=3){let e=s[t];s[t]=s[t+2],s[t+2]=e}}let h=0;for(let u=0;u<a.length;u+=2)l[h++]=a[u],l[h++]=n,l[h++]=a[u+1];return{vertices:l,indices:s}}function ns(t,e,i=0,s=!1){let r=new Array(2*t*3),n=0;for(let o=0;o<t;o++){o===t-1?s?(r[n++]=o+i,r[n++]=i,r[n++]=e+i,r[n++]=o+i,r[n++]=e+i,r[n++]=o+e+i):(r[n++]=e+i,r[n++]=i,r[n++]=o+i,r[n++]=o+e+i,r[n++]=e+i,r[n++]=o+i):s?(r[n++]=o+i,r[n++]=o+1+i,r[n++]=o+e+1+i,r[n++]=o+i,r[n++]=o+e+1+i,r[n++]=o+e+i):(r[n++]=o+e+1+i,r[n++]=o+1+i,r[n++]=o+i,r[n++]=o+e+i,r[n++]=o+e+1+i,r[n++]=o+i)}return r}function os(t,e,i,s=[]){var r;let n,o=[];switch(t.type){case"geometry:plane":n=function(t){let{normal:e,size:i,doubleSided:s}=t,r=Ri([0,0,0],e,i).flat(),n=[0,1,2,0,2,3],o=[{index:0,count:2}];return s&&(n=n.concat([0,2,1,0,3,2]),o.push({index:2,count:2})),{vertices:r,indices:n,faces:o}}(t);break;case"geometry:cuboid":n=function(t){let{dimensions:e}=t,i=e[0],s=e[1],r=e[2],n=[0,s,r,i,s,r,i,s,0,0,s,0,0,0,r,i,0,r,i,0,0,0,0,0],o=[];for(let a=0;a<6;a++)o.push({index:2*a,count:2});return{vertices:n,indices:[0,1,2,0,2,3,4,7,6,4,6,5,0,4,5,0,5,1,1,5,6,1,6,2,2,6,7,2,7,3,3,7,4,3,4,0],faces:o}}(t);break;case"geometry:sphere":n=function(t){const e=16,i=16;let s,r,n=t.radius,o=[],a=[],l="generator"===t.uvs?[]:void 0;o.push(0,n,0);for(let u=1;u<i;u++){let t=Math.PI*u/i;for(let i=0;i<e;i++){let s=Ki(n,t,2*Math.PI*i/e);o.push(s[0],s[1],s[2])}}let h=o.push(0,-n,0)/3-1;s=1,r=.9375;for(let u=0;u<e;u++){let t=1+u,i=1+(u+1)%e;if(a.push(0,i,t),l){let t=1-u/e,i=1-(u+1)/e,n=.5*(t+i);l.push(n,s,i,r,t,r)}}for(let u=0;u<14;u++)for(let t=0;t<e;t++){let s=1+u*e+t,r=1+u*e+(t+1)%e,n=1+(u+1)*e+(t+1)%e,o=1+(u+1)*e+t;if(a.push(s,r,n),a.push(s,n,o),l){let s=1-t/e,r=1-(u+1)/i,n=1-(t+1)/e,o=1-(u+2)/i;l.push(s,r,n,r,n,o),l.push(s,r,n,o,s,o)}}s=.0625,r=0;for(let u=0;u<e;u++){let t=225+u,i=225+(u+1)%e;if(a.push(t,i,h),l){let t=1-u/e,i=1-(u+1)/e,n=.5*(t+i);l.push(t,s,i,s,n,r)}}return{vertices:o,indices:a,uvs:l,faces:[{index:0,count:a.length/3}]}}(t);break;case"geometry:extrusion":n=function(t){let{profile:e,height:i}=t,s=ss(e),{points:r,segmentRanges:n,holes:o}=s,a=r.flat(),l=[],h=r.length,u=[{points:r,segmentRanges:n}];for(let _ of o)l.push(_.points.flat()),u.push(_),h+=_.points.length;let c=Ei(r),d=rs(a,c,{y:i,flipSide:!1,holes:l}),p=rs(a,c,{y:0,flipSide:!0,holes:l}),f=[];f.push(...d.vertices),f.push(...p.vertices);let m=d.indices,g=p.indices.map(t=>t+h),y=[];y.push(...m),y.push(...g);let v=m.length/3,x=[];x[0]={index:0,count:v},x[1]={index:v,count:v};let b=2*v,w=0;for(let _=0;_<u.length;_++){let{points:t,segmentRanges:e}=u[_],i=0===_?Ei(t):!Ei(t),s=ns(t.length,d.vertices.length/3,w,i);w=t.length,y.push(...s);for(let r of e){let t=b+2*r.index,e=2*r.count;x.push({index:t,count:e})}b+=2*t.length}return{vertices:f,indices:y,faces:x}}(t);break;case"geometry:mesh":n=function(t){let{vertices:e,indices:i,normals:s,uvs:r}=t,n={vertices:e,indices:i,faces:[]};return Array.isArray(s)&&(n.normals=s),Array.isArray(r)&&(n.uvs=r),n}(t);break;default:return ve.warn(`Invalid geometry type ${t.type}.`),o}o=$e(t,n,i),"geometry:plane"!==t.type&&"geometry:cuboid"!==t.type&&"geometry:sphere"!==t.type&&"geometry:extrusion"!==t.type||(null==(r=t.geometries)?void 0:r.length)&&(s.push(t),o=function(t,e,i,s,r){let n={nextId:0},o=t.geometries??[];for(let a of o)e="string"==typeof a||"reference:geometry"===a.type?Xi(e,a,i,s,r):"csg:clip"===a.type?Wi(n,e,a,s):Yi(n,e,a,i,s,r);return e}(t,o,e,i,s),s.pop());let a=[];for(let u of o){let{name:e,vertices:i,indices:s,normals:r,uvs:n,material:o}=u,{position:l,rotation:h,rotationAxis:c}=t,d=Oi({position:l,rotation:h,rotationAxis:c,name:e,vertices:i,indices:s,normals:r,uvs:n,material:o});a.push(d)}o=a;let l=t.normals??"flat";if("flat"===l||"smooth"===l)for(let u of o){let{vertices:t,indices:e}=u;u.normals="flat"===l?ji(t,e):zi(t,e)}let h=t.uvs??"automatic";if("automatic"==h||"spherical"===h)for(let u of o){let{vertices:t,indices:e}=u;u.uvs="automatic"===h?qi(t,e):Ji(t,e)}return o}function as(t){let e,i,s,r={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]};for(let n=0;n<t.length;n+=3)e=t[n],i=t[n+1],s=t[n+2],r.min[0]=Math.min(r.min[0],e),r.max[0]=Math.max(r.max[0],e),r.min[1]=Math.min(r.min[1],i),r.max[1]=Math.max(r.max[1],i),r.min[2]=Math.min(r.min[2],s),r.max[2]=Math.max(r.max[2],s);return r}function ls({min:t,max:e,transform:i}){if(0===i.rotation)return{min:ci(t,i.position),max:ci(e,i.position)};{let s=Ti(i.position,i.rotation,i.rotationAxis);const r=[[...t],[...e],[t[0],t[1],e[2]],[e[0],e[1],t[2]]];for(const t of r)bt(t,t,s);return as(r.flat())}}class hs{constructor(){this.vertices=[],this.edges=[],this.geometryProfile=[]}toJSON(){return{edges:this.edges.map(t=>t.id)}}}function us(t,e){return"integer"===e.type?"number"==typeof t&&Number.isInteger(t):typeof t===e.type&&(!("enum"in e)||e.enum.includes(t))}const cs={"spatialStructure:layout":"layout","layout:space":"space","product:static":"product","product:component":"product","spatialStructure:building":"building","spatialStructure:floor":"floor","element:asset":"element","element:beam":"element","element:casework":"element","element:column":"element","element:door":"element","element:kitchen":"element","element:railing":"element","element:ramp":"element","element:roof":"element","element:slab":"element","element:stairs":"element","element:stairFlight":"element","element:window":"element","element:generic":"element","element:floor":"element","element:ceiling":"element","element:boundaryWall":"element","element:curtainWall":"element","element:opening":"element","element:spaceDivider":"element","element:wall":"element"},ds=(t,e)=>{const i=cs[e];return i||ve.error(`Missing custom attribute resource type for node type: "${e}"`),`${t}:${i}`};function ps(t,e){if("boolean"===e.type&&"string"==typeof t){if("true"===t.toLowerCase())return!0;if("false"===t.toLowerCase())return!1}if("number"===e.type&&"string"==typeof t){const e=Number(t);if(!isNaN(e))return e}return null}class fs extends be{constructor(t,e){super(t,"customAttribute:definition"),this.attributes={resourceType:"space",schema:{type:"string"}},e&&this.setAttributes(e)}getInputType(){return function(t){switch(t.type){case"integer":return"Integer";case"boolean":return"Boolean";case"number":return"Number";case"string":return"enum"in t?"Select":"Text"}}(this.attributes.schema)}setAttributes(t){let e=this.attributes;e.resourceType=t.resourceType??e.resourceType,e.updatedAt=t.updatedAt??e.updatedAt,e.description=t.description??e.description,e.schema=function(t){return t.schema?JSON.parse(JSON.stringify(t.schema)):"Text"===t.valueType?{type:"string"}:"Number"===t.valueType?{type:"number"}:"Boolean"===t.valueType?{type:"boolean"}:void 0}(t)}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes))}toJSON(){const t=super.toJSON();let e={resourceType:this.attributes.resourceType,schema:JSON.parse(JSON.stringify(this.attributes.schema))};return void 0!==this.attributes.updatedAt&&(e.updatedAt=this.attributes.updatedAt),void 0!==this.attributes.description&&(e.description=this.attributes.description),t.attributes=e,t}}const ms={"customAttribute:definition":fs};class gs extends be{constructor(t,e){super(t,e),this.customAttributes={}}setCustomAttributes(t,e){let i=null,s=!1;if(null===t&&(this.customAttributes={},s=!0),t&&e)for(const r in t){let n=t[r];if(null===n){delete this.customAttributes[r],s=!0;continue}const o=ds(r,this.type),a=e[o];if(a){if(!us(n,a.attributes.schema)){let t=ps(n,a.attributes.schema);if(null===t){ve.error(`Value type mismatch for custom attribute. Received value: "${n}". Expected type: ${a.attributes.schema.type}`),i=`Value type mismatch for custom attribute. Received value: "${n}". Expected type: ${a.attributes.schema.type}`;continue}n=t}this.customAttributes[r]!==n&&(this.customAttributes[r]=n,s=!0)}else i=`Missing custom attribute definition for node key: "${r}", node type: "${this.type}" and definition id: ${o}`}s&&this.emit("node-custom-attributes-change",this),i&&ve.error(i)}toJSON(){const t=super.toJSON();return Object.keys(this.customAttributes).length>0&&(t.customAttributes=JSON.parse(JSON.stringify(this.customAttributes))),t}copyForClone(t){super.copyForClone(t),this.customAttributes=JSON.parse(JSON.stringify(t.customAttributes))}}class ys extends gs{constructor(t,e){super(t,e),this.layout=null}}class vs extends ys{constructor(){super(...arguments),this.axisAlignedBoundingBox=null,this.objectAlignedBoundingBox=null,this.boundingBoxContour=null,this.transform=null,this.worldTransform=null}calculateTransform(){return{position:[0,0,0],rotation:0,rotationAxis:[0,1,0]}}getTransform(){return this.transform||(this.transform=this.calculateTransform()),this.transform}calculateWorldTransform(){return this.getTransform()}getWorldTransform(){return this.worldTransform||(this.worldTransform=this.calculateWorldTransform()),this.worldTransform}resetTransform(t=!1){var e;this.transform=null,this.worldTransform=null,this.axisAlignedBoundingBox=null,this.boundingBoxContour=null,t&&(null==(e=this.layout)||e.spatialIndex.addNode(this))}resetBoundingBox(t=!1){var e;this.objectAlignedBoundingBox=null,this.axisAlignedBoundingBox=null,this.boundingBoxContour=null,t&&(null==(e=this.layout)||e.spatialIndex.addNode(this))}resetSpatialIndexing(){this.resetTransform(),this.resetBoundingBox(!0)}calculateBoundingBox(){return{min:[0,0,0],max:[0,0,0]}}getBoundingBox(t=!1){this.objectAlignedBoundingBox||(this.objectAlignedBoundingBox=this.calculateBoundingBox());const{min:e,max:i}=this.objectAlignedBoundingBox;return{min:e,max:i,transform:t?this.getTransform():this.getWorldTransform()}}getAxisAlignedBoundingBox(){return this.axisAlignedBoundingBox||(this.axisAlignedBoundingBox=ls(this.getBoundingBox())),this.axisAlignedBoundingBox}calculateBoundingBoxContour(t=!1){const{min:[e,,i],max:[s,,r],transform:n}=this.getBoundingBox(t),{position:[o,,a],rotation:l}=n;let h=[[e,i],[s,i],[s,r],[e,r]];return(o||a||l)&&(h=Mi(h,{position:[o,a],rotation:l})),h}getBoundingBoxContour(){return this.boundingBoxContour||(this.boundingBoxContour=this.calculateBoundingBoxContour()),this.boundingBoxContour}}class xs extends vs{}class bs extends xs{constructor(t,e,i){super(t,"spatialGraph:vertex"),this.position=[0,0],this.edges=[],this.position[0]=e,this.position[1]=i}sortVertexEdges(){let t=[];for(let e of this.edges){let i=this===e.vertices[0]?e.vertices[1]:e.vertices[0],s=ei([i.position[0]-this.position[0],i.position[1]-this.position[1]]);t.push({edge:e,edgeAngle:s})}t.sort((t,e)=>t.edgeAngle-e.edgeAngle),this.edges=t.map(t=>t.edge)}calculateTransform(){return{position:[this.position[0],0,this.position[1]],rotation:0,rotationAxis:[0,1,0]}}addEdge(t){this.edges.push(t),this.sortVertexEdges(),this.emit("vertex-add-edge",this,t)}removeEdge(t){let e=this.edges.indexOf(t);if(e>-1){let t=this.edges.splice(e,1)[0];this.emit("vertex-remove-edge",this,t)}else ve.error(`Vertex does not reference edge ${t.id}.`)}setPosition(t,e){this.position[0]=t,this.position[1]=e,this.edges.length>0&&(this.layout.spatialGraph.graphChanged=!0),this.resetSpatialIndexing(),this.emit("vertex-set-position",this)}resetSpatialIndexing(){super.resetSpatialIndexing();const t=/* @__PURE__ */new Set;for(const e of this.edges){e.resetSpatialIndexing();for(const i of e.spaces)i&&t.add(i)}for(const e of t)e.resetSpatialIndexing()}toJSON(){return{...super.toJSON(),position:[...this.position]}}}function ws(t,e,i,s,r=!1){if(e.layout)return ve.warn(`${s} ${e.id} already part of layout ${e.layout.id}.`),!1;if(i[e.id])return ve.error(`${s} ${e.id} already registered in layout.`),!1;let n=t.spaceGraph;if(n&&n.nodesById[e.id])return ve.error(`${s} ${e.id} already registered in space graph.`),!1;if(e.type.startsWith("space:")){let t=e;if(t.slabs.length>0)return ve.warn(`Detached space ${t.id} references boundary slab elements.`),!1}else if(e.type.startsWith("element:")){let n=e;if(r&&n.parent)return ve.warn(`${s} ${n.id} already a child of ${s} ${n.parent.id}.`),!1;for(let e of n.elements)if(!ws(t,e,i,s,!1))return!1}return!0}function _s(t,e){if(e.layout=t,t.elementsById[e.id])return void ve.error(`Element ${e.id} already registered.`);t.elementsById[e.id]=e;const i=t.elementsByType[e.type];i||(ve.warn(`unrecognized layout element type: ${e.type}`),t.elementsByType[e.type]=[]),i.push(e);let s=t.spaceGraph;s&&("element:asset"===e.type&&e.product&&!s.productsById[e.product.id]&&s.insertProduct(e.product),s.registerNode(e),s.emit("element-create",e));for(let r of e.elements)_s(t,r)}function Ps(t,e,i){for(let o of e.elements)Ps(t,o,e);if(t.elementsById[e.id]!==e)return void ve.error(`Entry ${e.id} in 'elements stored by ID' record does not contain this object.`);delete t.elementsById[e.id];const s=t.elementsByType[e.type],r=null==s?void 0:s.indexOf(e);if(!s||-1===r)return void ve.error(`element ${e.id} not found in 'elements stored by type' record.`);s.splice(r,1);let n=t.spaceGraph;n&&(n.unregisterNode(e),n.emit("element-delete",e,i)),e.layout=null}function Es(t){return"object"==typeof t&&null!==t}function Ts(t){return Es(t)&&!function(t){return Array.isArray(t)||ArrayBuffer.isView(t)}(t)}function As(t,e,i,s){Ts(t)&&Ts(e)||ve.error("Both arguments must be objects.");let{onNewKeys:r,copyScopes:n,cloneObjects:o}=s,a=Object.keys(e);for(let l of a){if(r){let{allow:e,excludedScopes:s}=r;if(e===(!!s&&s.includes(i))&&!(l in t)){ve.warn(`Key '${l}' not found in scope ${i}, skipped.`);continue}}let a=e[l],h=t[l];if(Es(a)){let e=`${i}.${l}`;!(null==n?void 0:n.includes(e))&&Ts(h)?As(h,a,e,s):t[l]=o?JSON.parse(JSON.stringify(a)):a}else t[l]=a}}function Is(t,e,i={onNewKeys:{allow:!1,excludedScopes:[]},copyScopes:[],cloneObjects:!0}){let s;i.onNewKeys?(s=i.onNewKeys,s.allow=i.onNewKeys.allow??!1,s.excludedScopes=i.onNewKeys.excludedScopes??[]):s={allow:!1,excludedScopes:[]},As(t,e,"",{onNewKeys:s,copyScopes:i.copyScopes??[],cloneObjects:i.cloneObjects??!0})}function Ss(t,e){t.name=e.name??t.name,t.customId=e.customId??t.customId}function Cs(t,e,i){t.setCustomAttributes(e.customAttributes,i)}function Ms(t){let e=t.getEdges();return 1===e.length?e[0].id:e.map(t=>t.id)}function Os(t){let e;switch(t.type){case"element:ceiling":case"element:floor":e=function(t){let e=[];for(let i of t.boundaries){let t=i.toJSON();e.push(t)}return{id:t.id,type:t.type,boundaries:e,parameters:{height:t.parameters.height,elevation:t.parameters.elevation,materials:{...t.parameters.materials}}}}(t);break;case"element:boundaryWall":e=function(t){let e=[];for(let s of t.boundaries){let t=s.toJSON();e.push(t)}let i=JSON.parse(JSON.stringify(t.parameters.surfaces));return{id:t.id,type:t.type,boundaries:e,parameters:{height:t.parameters.height,elevation:t.parameters.elevation,surfaces:i,materials:{...t.parameters.materials}}}}(t);break;case"element:curtainWall":e={id:(n=t).id,type:n.type,edge:Ms(n)};break;case"element:spaceDivider":e={id:(r=t).id,type:r.type,edge:Ms(r)};break;case"element:wall":e=function(t){let{width:e,height:i,offset:s,elevation:r,materials:n}=t.parameters;return{id:t.id,type:t.type,parameters:{width:e,height:i,offset:s,elevation:r,materials:{...n}},edge:Ms(t)}}(t);break;case"element:opening":e=function(t){let{position:e,dimensions:i,materials:s}=t.parameters;return{id:t.id,type:t.type,parameters:{position:[...e],dimensions:[...i],materials:{...s}}}}(t);break;case"element:asset":e={id:(i=t).id,type:i.type,position:[...i.position],rotation:i.rotation,rotationAxis:i.rotationAxis,product:null==(s=i.product)?void 0:s.id,geometries:JSON.parse(JSON.stringify(i.geometries))};break;case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:kitchen":case"element:railing":case"element:ramp":case"element:roof":case"element:slab":case"element:stairs":case"element:stairFlight":case"element:window":e=function(t){let e={id:t.id,type:t.type,position:[...t.position],parameters:JSON.parse(JSON.stringify(t.parameters)),rotation:t.rotation,rotationAxis:t.rotationAxis};return"element:generic"!==t.type&&"element:asset"!==t.type||(e.geometries=JSON.parse(JSON.stringify(t.geometries))),e}(t);break;default:return void ve.warn(`Unknown element type '${t.type}, skipping element.`)}var i,s,r,n,o,a;if(o=e,""!==(a=t).name&&(o.name=a.name),""!==a.customId&&(o.customId=a.customId),function(t,e){e.customAttributes===Object(e.customAttributes)&&Object.keys(e.customAttributes).length>0&&(t.customAttributes=e.customAttributes)}(e,t),t.elements.length){e.elements=[];for(let i of t.elements){let t=Os(i);t&&e.elements.push(t)}}return e}class Ns extends vs{constructor(){super(...arguments),this.parent=null,this.elements=[],this.geometries=[]}insertElement(t){let e=this.layout;e&&!ws(e,t,e.elementsById,"Element",!0)||(t.parent=this,this.elements.push(t),e&&_s(e,t))}get isExternal(){if(this.parent)return this.parent.isExternal;const t=this.getSpaces().flatMap(t=>t?[t]:[]);return!t.length||t[0].isExternal}resetTransform(t=!1){super.resetTransform(t);for(const e of this.elements)e.resetTransform(t)}resetBoundingBox(t=!1){super.resetBoundingBox(t);for(const e of this.elements)e.resetBoundingBox(t)}removeElement(t){if(t.parent!==this)return void ve.warn(`Element ${t.id} not a child of element ${this.id}.`);let e=this.elements.indexOf(t);if(-1===e)return void ve.error(`Element ${t.id} not found in parent ${this.id}.`);let i=t.parent;t.parent=null,this.elements.splice(e,1),t.layout&&Ps(t.layout,t,i)}copyForClone(t){super.copyForClone(t),this.parameters=JSON.parse(JSON.stringify(t.parameters)),this.geometries=JSON.parse(JSON.stringify(t.geometries))}setParameters(t){Is(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.resetBoundingBox(),this.emit("element-parameters-change",this)}getSpaces(){return this.parent?this.parent.getSpaces():[]}toJSON(){return Os(this)}}function Ls(t,e,i){let s=t.getAxisLength(),r=[];for(let n of t.elements)if("element:opening"===n.type){let t=n.parameters.position[0],o=t/s,a=(t+n.parameters.dimensions[0])/s;i?e>=o&&e<a&&r.push(n):e>o&&e<a&&r.push(n)}return r}class Rs extends Ns{constructor(t,e,i){super(t,e),me(this,ae),this.edges=[],this.vertices=[],this.boundingBoxTransform=null,this.edgesChanged=!1,this.setEdges(i)}setEdges(t){var e,i;if(!t.length)return this.edges=[],this.vertices=[],void ye(this,ae,le).call(this);if(1===t.length)return this.edges=[t[0]],this.vertices=[t[0].vertices[0],t[0].vertices[1]],void ye(this,ae,le).call(this);const s=function(t){var e;const i=/* @__PURE__ */new Map;for(const s of t)for(const t of s.vertices)i.has(t)||i.set(t,[]),null==(e=i.get(t))||e.push(s);return i}(t),r=[];let n,o;for(const[h,u]of s.entries())if(1===u.length){n=u[0];const t=n.vertices.find(t=>t!==h);if(2!==(null==(e=s.get(t))?void 0:e.length))return void ve.error("Edge sequence is not continuous");r.push(h,t),o=t;break}if(!n||!o)return void ve.error("Unable to find start of edge sequence");const a=[n];let l=n;for(;a.length<t.length;){const t=o&&(null==(i=s.get(o))?void 0:i.find(t=>t!==l));if(!t)return void ve.error("Edge sequence is not continuous");if(a.includes(t))return void ve.error("Duplicate Edge in sequence",t.id,l.id);const e=t.vertices.find(t=>t!==o);r.push(e),a.push(t),o=e,l=t}this.edges=a,this.vertices=r,ye(this,ae,le).call(this)}getEdges(){return[...this.edges]}getVertices(){return ye(this,ae,he).call(this),[...this.vertices]}getStartVertex(){return ye(this,ae,he).call(this),this.vertices.at(0)}getEndVertex(){return ye(this,ae,he).call(this),this.vertices.at(-1)}getAxisPoints(){const t=this.getStartVertex(),e=this.getEndVertex();return t&&e?[t.position,e.position]:[]}getAxisLength(){const[t,e]=this.getAxisPoints();return t&&e?ri(ui(t,e)):0}getEdgeAtLinearPosition(t){if(t<0||t>1)return;if(1===this.edges.length)return this.edges[0];let e=this.getAxisLength();if(!e)return;let i=this.vertices[0].position;for(let s=0;s<this.vertices.length-1;s++){if(ni(i,this.vertices[s+1].position)/e>=t)return this.edges[s]}}getEdgesAtLinearSegment(t,e){if(t>e)return[];if(1===this.edges.length)return[this.edges[0]];let i=this.getAxisLength();if(!i)return[];let s=[],r=this.vertices[0].position,n=r;for(let o=0;o<this.vertices.length-1;o++){let a=this.vertices[o+1].position,l=ni(r,n)/i,h=ni(r,a)/i;(t<=l&&e>=h||t>=l&&t<h||e>l&&e<=h)&&s.push(this.edges[o]),n=a}return s}resetTransform(){this.boundingBoxTransform=null,this.objectAlignedBoundingBox=null,super.resetTransform()}getBoundingBox(){this.objectAlignedBoundingBox||(this.objectAlignedBoundingBox=this.calculateBoundingBox());const{min:t,max:e}=this.objectAlignedBoundingBox;return this.boundingBoxTransform||(this.boundingBoxTransform=this.calculateBoundingBoxTransform()),{min:t,max:e,transform:this.boundingBoxTransform}}calculateBoundingBoxTransform(){const[t,e]=this.getAxisPoints();if(!t||!e)return super.calculateTransform();const i={rotation:-(gi(t,e)/Math.PI*180)};return{position:[t[0],0,t[1]],rotation:i.rotation,rotationAxis:[0,1,0]}}get edge(){return ve.warn("Use getEdges() instead of edge"),this.edges[0]||null}getAdjacentElementsByVertex(){let t=[[],[]];for(let e=0;e<this.vertices.length;e++){let i=this.vertices[e].edges.filter(t=>t.element&&t.element.id!==this.id).map(t=>t.element);t[e]=i}return t}getAdjacentSpacesBySide(){let t=[[],[]];for(let e=0;e<2;e++){let i=this.edges.filter(t=>t.spaces[e]).map(t=>t.spaces[e]);t[e]=i}return t}getSpaces(){let t=[];for(let e of this.edges)e.spaces[0]&&t.push(e.spaces[0]),e.spaces[1]&&t.push(e.spaces[1]);return t}getElementsAtLinearPosition(t){return Ls(this,t,!0)}get isExternal(){let t=0,e=0;for(const i of this.getEdges())i.isExternal?t+=i.getLength():e+=i.getLength();return t>=e}}function Bs(t){for(let e of t.elements)if("element:door"===e.type){let t=e.parameters;t.hingeSide="right"===t.hingeSide?"left":"right",t.doorSide="side1"===t.doorSide?"side2":"side1"}}ae=/* @__PURE__ */new WeakSet,le=function(){this.edgesChanged=!1,this.resetSpatialIndexing(),this.emit("element-edges-change",this)},he=function(){this.edgesChanged&&this.edges.length&&this.setEdges(this.edges)};class ks extends xs{constructor(t,e,i){super(t,"spatialGraph:edge"),this.spaces=[void 0,void 0],this.boundaryWalls=[null,null],this.element=null,this.vertices=[e,i]}getPoints(){return[this.vertices[0].position,this.vertices[1].position]}getLength(){return ni(...this.getPoints())}get isExternal(){return this.spaces.some(t=>!t||t.isExternal)}setVertices(t,e){if(t===e)return void ve.warn("Cannot set both edge vertices to the same vertex.");let i,s,r=this.vertices[0],n=this.vertices[1];this.vertices[0]=t,this.vertices[1]=e,r!==t?(r.removeEdge(this),t.addEdge(this),i=!0):i=!1,n!==e?(n.removeEdge(this),e.addEdge(this),s=!0):s=!1,this.layout.spatialGraph.graphChanged=!0,this.element&&(this.element.edgesChanged=!0),this.resetSpatialIndexing(),(i||s)&&this.emit("edge-set-vertices",this,{previousVertices:[r,n]})}resetSpatialIndexing(){super.resetSpatialIndexing(),this.element&&this.element.resetSpatialIndexing()}calculateBoundingBox(){const[t,e]=this.getPoints();return{min:[Math.min(t[0],e[0]),0,Math.min(t[1],e[1])],max:[Math.max(t[0],e[0]),0,Math.max(t[1],e[1])]}}setVerticesByIds(t,e){let i=this.layout.spatialGraph,s=i.verticesById[t];if(!s)return void ve.error(`Cannot find vertex ${t}.`);let r=i.verticesById[e];r?this.setVertices(s,r):ve.error(`Cannot find vertex ${e}.`)}canSplit(t,e={}){let{minimumLength:i}=e;if(void 0!==i){if(t<0||t>1)return!1;let[e,s]=this.getPoints(),r=oi(e,s,t),n=ri(ui(r,e)),o=ri(ui(r,s));if(n<i||o<i)return!1}else if(t<=0||t>=1)return!1;if(this.element){let[e,i]=this.getPoints(),s=oi(e,i,t),[r]=this.element.getAxisPoints();if(!r)return!1;let n=this.element.getAxisLength(),o=ni(r,s)/n;return 0===Ls(this.element,o,!1).length}return!0}split(t,e={},i=!1){var s,r,n;let o=this.layout.spatialGraph,a=this.vertices[0],l=this.vertices[1],h=null==(s=this.element)?void 0:s.getAxisLength(),u=null==(n=null==(r=this.element)?void 0:r.getStartVertex())?void 0:n.position,[c,d]=this.getPoints(),p=oi(c,d,t),f=e.vertexId??(this.layout.debugIds?o.debugVertexCount.toString():Ut()),m=o.verticesById[f]??o.createVertex(f,p[0],p[1]);this.setVertices(a,m);let g=e.edgeId??o.getEdgeId(),y=o.createEdge(g,m,l);if(y.spaces[0]=this.spaces[0],y.spaces[1]=this.spaces[1],y.boundaryWalls[0]=this.boundaryWalls[0],y.boundaryWalls[1]=this.boundaryWalls[1],this.element&&e.elementId&&h&&u){let i=ni(u,p)/h,s=this.element.getEdges(),r=s.indexOf(this)+1,n=[y,...s.splice(r)];this.element.setEdges(s);let o=e.elementId??this.layout.getElementId(this.element),a=this.layout.createElement(this.element.type,o,n);a.parameters=JSON.parse(JSON.stringify(this.element.parameters));let l=ni(u,p),c=[...this.element.elements];for(let e of c)if("element:opening"===e.type){let s=e.parameters.position[0],r=s/h,n=(s+e.parameters.dimensions[0])/h;i<=r?(e.parameters.position[0]=r*h-l,this.element.removeElement(e),a.insertElement(e)):t<n&&ve.warn(`Opening ${e.id} overlaps split position.`)}}else if(this.element){const t=this.element.getEdges();this.element.setEdges([...t,y]),y.element=this.element}if(i)for(let v of y.spaces){if(!v)continue;let{boundary:t}=v.getBoundaryFromEdge(this);if(t){let e,i=t.vertices.indexOf(a),s=t.vertices.indexOf(l);e=0===i&&s===t.vertices.length-1?s:0===s&&i===t.vertices.length-1||i<s?i:s,t.vertices.splice(e+1,0,m),t.edges=[];for(let r=0;r<t.vertices.length;r++){let e=r,i=r<t.vertices.length-1?r+1:0,s=t.vertices[e],n=t.vertices[i],a=o.getEdgeFromVertices(s,n);a?t.edges.push(a):ve.error(`Cannot find edge with vertices ${s.id} and ${n.id}.`)}}else ve.error(`Edge ${this.id} not found in space boundary.`)}for(let v of y.boundaryWalls){if(!v)continue;let t,e=v.boundaries[0],i=e.vertices.indexOf(a),s=e.vertices.indexOf(l);t=0===i&&s===e.vertices.length-1?s:0===s&&i===e.vertices.length-1||i<s?i:s,e.vertices.splice(t+1,0,m),e.edges=[];for(let r=0;r<e.vertices.length;r++){let t=r,i=r<e.vertices.length-1?r+1:0,s=e.vertices[t],n=e.vertices[i],a=o.getEdgeFromVertices(s,n);a?e.edges.push(a):ve.error(`Cannot find edge with vertices ${s.id} and ${n.id}.`)}}return{vertex:m,edge:y,element:undefined}}canMerge(t){if(this.element&&!t.element||!this.element&&t.element)return!1;let e,i=this.vertices[0],s=this.vertices[1],r=t.vertices[0],n=t.vertices[1];if(i===r)e=[s,i,n];else if(i===n)e=[s,i,r];else if(s===r)e=[i,s,n];else{if(s!==n)return!1;e=[i,s,r]}if(0!==mi(e[0].position,e[1].position,e[2].position))return!1;let o=e[1];return!(!o.edges.includes(this)||!o.edges.includes(t))}merge(t,e=!1){var i;if(this.element&&!t.element||!this.element&&t.element)return void ve.warn("Either none or both edges must have an element, cannot merge.");let s,r,n=this.layout.spatialGraph,o=this.vertices[0],a=this.vertices[1],l=t.vertices[0],h=t.vertices[1];if(o===l)s=[h,o,a],r=!0;else if(o===h)s=[l,o,a],r=!1;else if(a===l)s=[o,a,h],r=!1;else{if(a!==h)return void ve.warn(`Edge ${this.id} does not share a vertex with edge ${t.id}, cannot merge.`);s=[o,a,l],r=!0}let u=s[0].position,c=s[1].position;if(0!==mi(u,c,s[2].position))return void ve.warn(`Edges ${this.id} and ${t.id} are not collinear, cannot merge.`);let d=s[1];if(d.edges.includes(this)&&d.edges.includes(t)||ve.error(`Common vertex ${d.id} edge list does not contain either one or both edges, cannot merge.`),t.element&&r&&function(t){let e=t.getAxisLength();for(let i of t.elements){if("element:opening"!==i.type)continue;let t=i.parameters;t.position[0]=e-(t.position[0]+t.dimensions[0]),Bs(i)}}(t.element),this.setVertices(s[0],s[2]),this.element&&this.element===t.element){const e=this.element.getEdges(),i=e.indexOf(t);e.splice(i,1),this.element.setEdges(e),t.element=null}else if(this.element&&t.element){const e=t.element.getEdges(),s=e.indexOf(t);e.splice(s,1);let r=[...this.element.getEdges(),...e];this.element.setEdges(r),t.element.setEdges([t]);for(const t of r)t.element=this.element;let n=null==(i=this.element.getStartVertex())?void 0:i.position;if(!n)return;let o=ni(c,n),a=[...t.element.elements];for(let i of a){if("element:opening"!==i.type)continue;t.element.removeElement(i),this.element.insertElement(i),i.parameters.position[0]+=o}}if(e)for(let p of t.spaces){if(!p)continue;let{boundary:e,edgeIndex:i}=p.getBoundaryFromEdge(t);if(e){e.edges.splice(i,1);let t=e.vertices.indexOf(s[1]);t>-1?e.vertices.splice(t,1):ve.error(`Cannot find vertex ${s[1].id} in space ${p.id}`)}else ve.error(`Cannot find edge ${t.id} in space ${p.id}.`)}for(let p of t.boundaryWalls){if(!p)continue;let e=p.boundaries[0],i=e.edges.indexOf(t);if(i>-1){e.edges.splice(i,1);let t=e.vertices.indexOf(s[1]);t>-1?e.vertices.splice(t,1):ve.error(`Cannot find vertex ${s[1].id} in boundary wall ${p.id}`)}else ve.error(`Cannot find edge ${t.id} in boundary wall ${p.id}.`)}t.spaces[0]=null,t.spaces[1]=null,t.boundaryWalls[0]=null,t.boundaryWalls[1]=null,n.removeEdge(t),0===d.edges.length&&n.removeVertex(d)}toJSON(){const t=this.vertices[0],e=this.vertices[1];return{...super.toJSON(),vertices:[t.id,e.id]}}}const Fs={usage:"generic",program:"none"};function Ds(t,e){const i=e.parent,s=i.getAxisLength(),{position:r,dimensions:n}=e.parameters,o=r[0]/s,a=(r[0]+n[0])/s;return i.getEdgesAtLinearSegment(o,a).some(e=>e.spaces[0]===t||e.spaces[1]===t)}class Us extends vs{constructor(t,e){super(t,"layout:space"),me(this,ue),ge(this,ue,null),this.boundaries=[],this.slabs=[],this.attributes={...Fs},this.boundaries=e,this.geometry={polygons:[]}}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes)),this.geometry=JSON.parse(JSON.stringify(t.geometry))}setId(t){if(t===this.id)return;let e=this.layout;if((null==e?void 0:e.spacesById[t])||(null==e?void 0:e.elementsById[t])||(null==e?void 0:e.annotationsById[t]))return void ve.error(`ID ${t} already in use in layout ${e.id}.`);if(e&&e.spacesById[this.id]!==this)return void ve.error(`Entry ${this.id} in 'spaces stored by ID' record does not contain space ${this.id}.`);let i=this.spaceGraph;if(null==i?void 0:i.nodesById[t])return void ve.error(`ID ${t} already in use in space graph object.`);if(i&&i.nodesById[this.id]!==this)return void ve.error(`Entry ${this.id} in 'nodes stored by ID' record does not contain space ${this.id}.`);let s=this.id;this.id=t,e&&(delete e.spacesById[s],e.spacesById[this.id]=this),i&&(delete i.nodesById[s],i.nodesById[this.id]=this),this.emit("node-id-change",this,s)}setAttributes(t){this.attributes.usage=t.usage??this.attributes.usage,this.attributes.program=t.program??this.attributes.program,this.emit("space-attributes-change",this)}get isExternal(){return["balcony","terrace","buildingOpening"].includes(this.attributes.usage)}calculateArea(){let t=this.geometry.polygons;if(0===t.length)return ve.error(`Geometry has not been computed for space ${this.id}.`),0;let e=_i(t[0]);for(let i=1;i<t.length;i++){e-=_i(t[i])}return e}getArea(){return null===fe(this,ue)&&ge(this,ue,this.calculateArea()),fe(this,ue)}getAdjacentSpaces(t,{connectivity:e}={}){var i;let s=null==(i=t.nodeMap.get(this))?void 0:i.get("graph:adjacentTo");if(!s)return[];if(void 0===e)return Array.from(s);{let i=0===e?2:2*e;return Array.from(s).filter(s=>{let r=t.findShortestPath("graph:connectedTo",s,this,{depthLimit:i});return!!(null==r?void 0:r.length)&&(0!==e||"element:spaceDivider"===r[1].type)})}}getElements(t){let e=t&&(Array.isArray(t)?t:[t]),i=[],s=this.layout.getElementList();for(let r of s){if(e&&!e.includes(r.type))continue;let t;switch(r.type){case"element:ceiling":case"element:floor":t=r.space===this;break;case"element:boundaryWall":break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":t=r.getEdges().some(t=>t.spaces[0]===this||t.spaces[1]===this);break;case"element:opening":t=Ds(this,r);break;case"element:door":case"element:window":t=Ds(this,r.parent);break;default:{let e,i=r;if(i.parent){let t=i.parent;for(;t.parent;)t=t.parent;e=t.getTransform().position}else e=i.position;t=xi([e[0],e[2]],this.geometry.polygons);break}}t&&i.push(r)}return i}getBoundaryFromVertex(t){for(let e of this.boundaries){let i=e.vertices.indexOf(t);if(i>-1)return{boundary:e,itemIndex:i}}return{boundary:void 0,itemIndex:-1}}getBoundaryFromEdge(t){for(let e of this.boundaries){let i=e.edges.indexOf(t);if(i>-1)return{boundary:e,edgeIndex:i}}return{boundary:void 0,edgeIndex:-1}}calculateBoundingBox(){var t;const e=W([null==(t=this.boundaries[0])?void 0:t.geometryProfile]);let i=0,s=0;for(const r of this.slabs)"element:floor"===r.type&&(i=r.parameters.elevation),"element:ceiling"===r.type&&(s=r.parameters.elevation);return{min:[e.min[0],i,e.min[1]],max:[e.max[0],s,e.max[1]]}}getAxisAlignedBoundingBox(){const{min:t,max:e}=this.getBoundingBox();return{min:t,max:e}}resetBoundingBox(t){super.resetBoundingBox(t),ge(this,ue,null)}resetSpatialIndexing(){super.resetSpatialIndexing();for(const t of this.slabs)t.resetSpatialIndexing()}attachSlab(t){if(null!==t.space)return void ve.warn(`Boundary slab ${t.id} already attached to space ${t.space.id}.`);this.slabs.indexOf(t)>-1?ve.warn(`Boundary slab ${t.id} already referenced by space ${this.id}.`):(t.boundaries=this.boundaries,t.space=this,this.slabs.push(t),this.resetBoundingBox())}detachSlab(t){if(t.space!==this)return void ve.warn(`Boundary slab ${t.id} not attached to space ${this.id}.`);let e=this.slabs.indexOf(t);-1!==e?(t.space=null,t.boundaries=pr(this.boundaries),this.slabs.splice(e,1),this.resetBoundingBox()):ve.warn(`Boundary slab ${t.id} not referenced by space ${this.id}.`)}toJSON(){const{program:t,usage:e}=this.attributes,i={...super.toJSON(),boundaries:[],attributes:{program:t,usage:e}};for(const s of this.boundaries)i.boundaries.push(s.toJSON());return i}}ue=/* @__PURE__ */new WeakMap;class Gs extends Ns{constructor(t,e,i){super(t,e),this.boundaries=pr(i)}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0],i=W([this.boundaries[0].geometryProfile]);return t[0]=i.min[0],e[0]=i.max[0],t[2]=i.min[1],e[2]=i.max[1],"element:floor"===this.type?(t[1]=this.parameters.elevation-this.parameters.height,e[1]=this.parameters.elevation):(t[1]=this.parameters.elevation,e[1]=this.parameters.elevation+this.parameters.height),{min:t,max:e}}}const Xs={top:"#202020",bottom:"#000000",side1:"asm:basic-wall",side2:"asm:basic-wall",join1:"asm:basic-wall",join2:"asm:basic-wall"},Ws={width:.15,height:3,offset:0,elevation:0,materials:{...Xs}};class Ys extends Rs{constructor(t,e){super(t,"element:wall",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(Ws)),this.geometryProfile={valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}}copyForClone(t){super.copyForClone(t),this.geometryProfile=JSON.parse(JSON.stringify(t.geometryProfile))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0],[i,s]=this.getAxisPoints();if(!i||!s)return super.calculateBoundingBox();const r=ni(i,s),{width:n,offset:o}=this.parameters,a=-.5*n+o,l=a+n,h=W([[[0,a],[r,a],[r,l],[0,l]]]);return t[0]=h.min[0],e[0]=h.max[0],t[2]=h.min[1],e[2]=h.max[1],t[1]=this.parameters.elevation,e[1]=this.parameters.elevation+this.parameters.height,{min:t,max:e}}}const Hs={"element:ceiling":{height:.2,elevation:Ws.elevation+Ws.height,materials:{top:"#808080",bottom:"asm:basic-ceiling",sides:"asm:basic-wall"}},"element:floor":{height:.2,elevation:0,materials:{top:"asm:basic-floor",bottom:"#808080",sides:"asm:basic-wall"}}};class $s extends Gs{constructor(t,e,i){super(t,e,i);let s=Hs[this.type];this.parameters=JSON.parse(JSON.stringify(s)),this.space=null}setParameters(t){super.setParameters(t)}getSpaces(){return null===this.space?[]:[this.space]}}function js(t,e){var i;let s,r=t.vertices.map(t=>t.position),n=[];for(let o of t.edges){if("element:wall"!==(null==(i=o.element)?void 0:i.type))continue;let t=o.element.geometryProfile.points;n.push(t)}if(0===n.length)s=[r];else if(e){s=z([r],Y(n))}else s=Y([r,...n]);return s=s.filter(t=>K(t)>1e-7),0===s.length?(ve.warn("No valid polygons, returning boundary polygon."),r):(s=Q(s,.001),s=s.filter(t=>t.length>0),0===s.length?(ve.warn("No valid polygons after filtering, returning boundary polygon."),r):(s.length>1&&(ve.warn(`Result has ${s.length} polygons, returning largest one.`),s=s.sort((t,e)=>K(e)-K(t))),s[0]))}function zs(t,e){var i;let s=[js(e.boundaries[0],!0)];for(let o=1;o<e.boundaries.length;o++){s=z(s,[js(e.boundaries[o],!1)])}let{edges:r}=t.spatialGraph,n=[];for(let o of r){if(o.spaces[0]!==e||o.spaces[1]!==e||"element:wall"!==(null==(i=o.element)?void 0:i.type))continue;let[t,r]=o.getPoints();if(xi(oi(t,r,.5),s)){let t=o.element.geometryProfile.points;n.push(t)}}n.length>0&&(s=z(s,n)),s.sort((t,e)=>{let i=K(t);return K(e)-i}),e.geometry.polygons=s}function Vs(t,e){return new Array(e-t).fill(void 0).map((e,i)=>t+i)}function qs(t){return`${t.type.split(":")[1]}Geometry-${t.id.substring(0,8)}`}function Js(t){let e;switch(t.type){case"curve:rectangle":e=4;break;case"curve:polygon":e=t.points.length;break;case"curve:polygonWithHoles":e=t.polygons.reduce((t,e)=>t+Js({type:"curve:polygon",points:e}),0);break;case"curve:composite":e=t.segments.reduce((t,e)=>t+Js(e),0);break;case"curve:polyline":e=t.points.length-1;break;case"curve:circle":case"curve:arc":case"curve:line":e=1}return e}function Ks(){return De([Math.random(),Math.random(),Math.random()])}function Zs(t,e=!1){let{materials:i,height:s,elevation:r}=t.parameters,n="element:floor"===t.type?-s:0,o=[];for(let d=1;d<t.boundaries.length;d++){let e=t.boundaries[d].geometryProfile.slice();o.push(e)}o=Y(o);let a=t.boundaries[0].geometryProfile.slice(),l=r+n,h={id:`boundarySlabGeometry-${t.id}-boundary`,type:"geometry:extrusion",position:[0,l,0],height:s,profile:{type:"curve:polygonWithHoles",polygons:[a,...o]},geometries:[]},u={top:[0],bottom:[1],sides:Vs(2,2+a.length)},c={top:e?Ks():i.top,bottom:i.bottom,sides:i.sides};h.surfaces=u,h.materials=c,t.geometries=[{type:"reference:geometry",geometry:h}],t.emit("geometry-update",t)}function Qs(t){for(let e=0;e<t.boundaries.length;e++){const i=t.boundaries[e];for(const s of i.edges){const r=s.vertices[0],n=s.vertices[1],o=i.vertices.indexOf(r),a=i.vertices.indexOf(n);let l,h;if(l=0===o?1===a:o===i.vertices.length-1?0===a:a-o===1,h=0===e?l?1:0:l?0:1,null===s.spaces[h])s.spaces[h]=t;else{const t=0===h?"left":"right";ve.error(`Edge ${s.id} already references a space on its ${t} side.`)}}}}function tr(t){for(const e of t.boundaries)for(const i of e.edges)i.spaces[0]||null!==i.boundaryWalls[0]?i.spaces[1]||null!==i.boundaryWalls[1]?ve.error(`Edge ${i.id} referenced by more than two adjacent nodes.`):i.boundaryWalls[1]=t:i.boundaryWalls[0]=t}function er(t,e){let i=t.spatialGraph;for(let s=0;s<e.edges.length;s++){let t=e.edges[s],r=i.edgesById[t.id];r?e.edges[s]=r:i.insertEdge(t)}lr(e)}function ir(t,e){if(0!==e.boundaries.length){for(let i of e.boundaries)er(t,i);switch(e.type){case"element:boundaryWall":tr(e);break;case"element:ceiling":case"element:floor":{let i=function(t,e){for(const i of t.spaces){if(i.boundaries.length!==e.length)continue;let t=0;for(;t<i.boundaries.length;){if(!hr(i.boundaries[t],e[t]))break;t++}if(t===i.boundaries.length)return cr(i,[{boundaries:e}])?i:void 0}return}(t,e.boundaries);i?i.attachSlab(e):ve.warn(`Matching space not found for boundary slab element ${e.id}.`);break}}}else ve.warn(`Boundary slab element ${e.id} does not specify boundaries.`)}function sr(t,e){let i=t.spatialGraph;const s=e.getEdges(),r=new Set(s);let n=!1;for(let o of s){let t=i.edgesById[o.id];t?(n=!0,r.delete(o),r.add(t)):i.insertEdge(o)}n&&e.setEdges(Array.from(r)),function(t){for(const e of t.getEdges())null===e.element?e.element=t:e.element!==t&&ve.error(`Edge ${e.id} referenced by more than one edge element.`)}(e)}function rr(t){var e;switch(t.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":!function(t){switch(t.type){case"element:boundaryWall":for(let e of t.boundaries)for(let i of e.edges)i.boundaryWalls[0]===t&&(i.boundaryWalls[0]=null),i.boundaryWalls[1]===t&&(i.boundaryWalls[1]=null);break;case"element:ceiling":case"element:floor":{let e=t.space;e?e.detachSlab(t):ve.warn(`Boundary slab element ${t.id} not attached to a space.`);break}}}(t);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":!function(t){for(const e of t.getEdges())e.element=null}(t);break;case"element:asset":null==(e=t.product)||e.instances.delete(t)}}function nr(t){const e=[];for(const i of t.boundaries){const t=[];for(const e of i.vertices)t.push(e.position);e.push(t)}return e}function or(t){let e=[];if(0===t.length)return e;if(1===t.length){let i=t[0];return e.push(i.vertices[0]),e.push(i.vertices[1]),e}for(let i=0;i<t.length;i++){let s=t[i],r=t[(i+1)%t.length],n=s.vertices[0],o=s.vertices[1],a=r.vertices[0],l=r.vertices[1];if(n===a||n===l)e.push(o);else{if(o!==a&&o!==l)return void ve.warn(`Could not add edge ${s.id} to current path.`);e.push(n)}}return e}function ar(t){let e=[];for(let i=0;i<t.length-1;i++){let s=t[i],r=t[i+1];for(let t of s.edges)if(r.edges.indexOf(t)>-1){e.push(t);break}}return e}function lr(t){let e=or(t.edges);if(!e)return!1;if(t.vertices=e,t.geometryProfile=t.vertices.map(t=>t.position),!Ei(t.geometryProfile)){let{vertices:e,edges:i,geometryProfile:s}=t;e.reverse(),s.reverse();{i.reverse();let t=e[e.length-1],s=i[0];s.vertices[0]!==t&&s.vertices[1]!==t||(e.pop(),e.unshift(t))}}return!0}function hr(t,e,i){if(t.edges.length!==e.edges.length)return!1;const s=function(t,e){let i=0;for(const s of t.edges)for(const t of e.edges)if(s.id===t.id){i++;break}return i}(t,e);let r;return r=s===t.edges.length,r}function ur(t,e,i){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++){if(!hr(t[s],e[s]))return!1}return!0}function cr(t,e,i=!1){const s=.01;if(!i){const i=t.boundaries.map(t=>t.geometryProfile),r=e.map(t=>t.boundaries.map(t=>t.geometryProfile)),n=Z(i),o=r.map(t=>Z(t)).reduce((t,e)=>t+e,0);if(Math.abs(n-o)>s)return!1}const r=e.map(t=>[t.boundaries[0].geometryProfile]),{polygons:n}=j(r,.01),{polygons:o}=j(n,-.01);if(0===o.length)return ve.warn(`No union polygon, cannot match space ${t.id}.`),!1;if(o.length>1)return ve.warn(` Disjoint union area, cannot match space ${t.id}.`),!1;const a=o[0][0],l=t.boundaries[0].geometryProfile,h=V([[l]],[[a]]).polygons,u=V([[a]],[[l]]).polygons,c=h.length?Z(h[0]):0,d=u.length?Z(u[0]):0;return c<s&&d<s}function dr(t){let e=new hs;return e.vertices=[...t.vertices],e.edges=[...t.edges],e.geometryProfile=JSON.parse(JSON.stringify(t.geometryProfile)),e}function pr(t){let e=[];for(let i of t){let t=dr(i);e.push(t)}return e}function fr(t,e,i){for(let s of t.edges)s.spaces[0]===e?s.spaces[0]=i:s.spaces[1]===e?s.spaces[1]=i:ve.warn(`Edge ${s.id} not in space ${e.id} boundary.`)}function mr(t,e,i,s){let r=function(t,e,i,s){let r=t.vertices,n=Math.min(e,i),o=Math.max(e,i),a=o-n+1,l=r.length-a+2;if(a<3||l<3)return ve.warn("Cannot split boundary, both fragments should have three or more vertices."),[];let h=r.slice(0,n+1),u=r.slice(n,o+1),c=r.slice(o,r.length).concat(h),d=u,p=ar(c).concat(s),f=ar(d).concat(s),m=c.map(t=>t.position),g=d.map(t=>t.position),y=new hs;y.vertices=c,y.edges=p,y.geometryProfile=m;let v=new hs;return v.vertices=d,v.edges=f,v.geometryProfile=g,[y,v]}(t.boundaries[0],e,i,s);if(!r)return void ve.warn(`Could not split outer boundary of space ${t.id}.`);let n=[r[0]],o=[r[1]];for(let f=1;f<t.boundaries.length;f++){let e=t.boundaries[f],i=e.vertices[0].position;if(vi(i,r[0].geometryProfile))n.push(e);else{if(!vi(i,r[1].geometryProfile)){ve.warn("Inner boundary is not contained by either of the two split boundaries.");continue}o.push(e)}}let a,l,h=t.layout;(null==h?void 0:h.debugIds)?(a=h.getSpaceId(),l=h.getSpaceId()):(a=Ut(),l=Ut());let u=new Us(a,n),c=new Us(l,o);for(let f of n)fr(f,t,u);for(let f of o)fr(f,t,c);for(let f of n)u.geometry.polygons.push(f.geometryProfile);for(let f of o)c.geometry.polygons.push(f.geometryProfile);zs(h,u),zs(h,c);let d=[],p=[];for(let f=0;f<t.slabs.length;f++){let e,i,s=t.slabs[f];if(null==h?void 0:h.debugIds){let t="element:ceiling"===s.type?"ceiling":"floor";e=`${t}-${f+1}-in-${a}`,i=`${t}-${f+1}-in-${l}`}else e=Ut(),i=Ut();let r=new $s(e,s.type,n),u=new $s(i,s.type,o);Zs(r,!0),Zs(u,!0),d.push(r),p.push(u)}return{spaces:[u,c],slabs:[d,p]}}function gr(t,e){let{position:i,rotation:s,rotationAxis:r}=t.getTransform(),n=Ti(i,s,r);return e&&ht(n,e,n),n}function yr(t){let e;return t.parent&&(e=yr(t.parent)),gr(t,e)}function vr(t,e){switch(e.type){case"annotation:floorPlanDxf":case"annotation:floorPlanImage":return{name:"annotation",nodes:t.annotations,nodesById:t.annotationsById,nodesByType:t.annotationsByType};case"view:2d":case"view:3d":return{name:"view",nodes:t.views,nodesById:t.viewsById,nodesByType:t.viewsByType}}}class xr{constructor(t){this.vertices=[],this.verticesById={},this.edges=[],this.edgesById={},this.graphChanged=!1,this.debugVertexCount=0,this.debugEdgeCount=0,this.layout=t}emit(t,...e){let i=this.layout.spaceGraph;i&&i.emit(t,...e)}copyForClone(t){this.debugVertexCount=t.debugVertexCount,this.debugEdgeCount=t.debugEdgeCount}deleteVertexAtIndex(t,e){let i=this.vertices[t];if(e){let t=i.edges.slice();for(let s of t){let t=s.vertices[0],r=s.vertices[1];t!==i&&r!==i||this.removeEdge(s,e)}}if(this.vertices.splice(t,1),this.verticesById[i.id]===i)return delete this.verticesById[i.id],i;ve.error(`Entry ${i.id} in 'vertices by ID' record does not contain this object.`)}deleteEdgeAtIndex(t,e){let i=this.edges[t];if(i.element&&this.layout.removeElement(i.element),i.vertices[0].removeEdge(i),i.vertices[1].removeEdge(i),e){if(i.spaces[0]!==i.spaces[1]){if(i.spaces[0]){let t=i.spaces[0].slabs;for(let e of t)this.layout.removeElement(e);this.layout.removeSpace(i.spaces[0])}if(i.spaces[1]){let t=i.spaces[1].slabs;for(let e of t)this.layout.removeElement(e);this.layout.removeSpace(i.spaces[1])}}i.boundaryWalls[0]&&this.layout.removeElement(i.boundaryWalls[0]),i.boundaryWalls[1]&&this.layout.removeElement(i.boundaryWalls[1])}if(this.edges.splice(t,1),this.edgesById[i.id]===i)return delete this.edgesById[i.id],this.graphChanged=!0,i;ve.error(`Entry ${i.id} in 'edges by id' record does not contain this object.`)}insertVertex(t){if(!ws(this.layout,t,this.edgesById,"Edge"))return;t.layout=this.layout,this.vertices.push(t),this.verticesById[t.id]=t;let e=this.layout.spaceGraph;e&&(e.registerNode(t),e.emit("vertex-create",t))}removeVertex(t,e=!1){let i=this.vertices.indexOf(t);if(-1===i)return void ve.warn(`Vertex ${t.id} not found.`);this.deleteVertexAtIndex(i,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(t),s.emit("vertex-delete",t)),t.layout=null,t}removeVertexAtIndex(t,e=!1){let i=this.vertices[t];if(!i)return void ve.warn(`Vertex not found at index ${t}.`);this.deleteVertexAtIndex(t,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(i),s.emit("vertex-delete",i)),i.layout=null,i}removeVertexById(t,e=!1){let i=this.verticesById[t];if(i&&i.id===t)return this.removeVertex(i,e);ve.error(`Entry ${t} in 'vertices by id' record does not contain this object.`)}insertEdge(t,e=!1){if(!ws(this.layout,t,this.edgesById,"Edge"))return;let i=this.verticesById[t.vertices[0].id],s=this.verticesById[t.vertices[1].id];i?t.vertices[0]=i:this.insertVertex(t.vertices[0]),s?t.vertices[1]=s:this.insertVertex(t.vertices[1]),t.layout=this.layout,this.edges.push(t),this.edgesById[t.id]=t,t.vertices[0].addEdge(t),t.vertices[1].addEdge(t);let r=this.layout.spaceGraph;r&&(r.registerNode(t),r.emit("edge-create",t)),e&&function(t){let e=t.layout,i=t.vertices[0],s=t.vertices[1];for(let r of e.spaces){let n=r.boundaries[0],o=n.vertices.indexOf(i),a=n.vertices.indexOf(s);if(o>-1&&a>-1){t.spaces[0]=r,t.spaces[1]=r;let i=mr(r,o,a,t);if(i){let s=r.slabs.slice();for(let t of s)e.removeElement(t);e.removeSpace(r);let[n,o]=i.spaces,[a,l]=i.slabs;e.insertSpace(n);for(let t of a)e.insertElement(t);e.insertSpace(o);for(let t of l)e.insertElement(t);t.emit("space-split",r,[n,o]),n.emit("geometry-profile-update",n),o.emit("geometry-profile-update",o);for(let t of n.slabs)t.emit("geometry-profile-update",t);for(let t of o.slabs)t.emit("geometry-profile-update",t)}else ve.warn(`Failed to split space ${r.id}.`);break}}}(t),this.graphChanged=!0}removeEdge(t,e=!1){let i=this.edges.indexOf(t);if(-1===i)return void ve.warn(`Edge ${t.id} not found.`);this.deleteEdgeAtIndex(i,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(t),s.emit("edge-delete",t)),t.layout=null,t}removeEdgeAtIndex(t,e=!1){let i=this.edges[t];if(!i)return void ve.warn(`Edge not found at index ${t}.`);this.deleteEdgeAtIndex(t,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(i),s.emit("edge-delete",i)),i.layout=null,i}removeEdgeById(t,e=!1){let i=this.edgesById[t];if(i&&i.id===t)return this.removeEdge(i,e);ve.error(`Entry ${t} in 'edges by id' record does not contain this object.`)}getEdgeFromVertices(t,e){let i=t.edges,s=e.edges;for(let r of i)for(let t of s)if(r===t)return r}getVertexId(t){return this.layout.debugIds?(t??"vertex-")+this.debugVertexCount:Ut()}getEdgeId(t){return this.layout.debugIds?(t??"edge-")+this.debugEdgeCount:Ut()}createVertex(t,e,i){let s=new bs(t,e,i);return this.insertVertex(s),s}createEdge(t,e,i,s=!1){let r=new ks(t,e,i);return this.insertEdge(r,s),r}createEdgeByVertexIds(t,e,i,s=!1){let r=this.verticesById[e],n=this.verticesById[i];return this.createEdge(t,r,n,s)}toJSON(){let t=[];for(let i of this.vertices){let e=i.toJSON();t.push(e)}let e=[];for(let i of this.edges){let t=i.toJSON();e.push(t)}return{vertices:t,edges:e}}}const br={height:3,elevation:0,surfaces:{top:[0],bottom:[1],sides:"..."},materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class wr extends Gs{constructor(t,e){super(t,"element:boundaryWall",e),this.parameters=JSON.parse(JSON.stringify(br))}setParameters(t){super.setParameters(t)}}const _r={materials:{}};class Pr extends Rs{constructor(t,e){super(t,"element:curtainWall",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(_r))}setParameters(t){super.setParameters(t)}}const Er={materials:{}};class Tr extends Rs{constructor(t,e){super(t,"element:spaceDivider",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(Er))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const[t,e]=this.getAxisPoints();if(!t||!e)return super.calculateBoundingBox();return{min:[0,0,-.01],max:[ni(t,e),0,.01]}}}class Ar extends Ns{constructor(t,e){super(t,e)}}function Ir(t,e,i=0){let{width:s,offset:r,elevation:n}=t.parameters,[o,a]=t.getAxisPoints();if(!o||!a)return{position:[0,0,0],rotation:0};let l=ui(a,o),h=ri(l),u=oi(o,a,e.parameters.position[0]/h);u=ti(u,hi(li(ai(l)),-.5*s+r-i));let c=e.parameters.position[1]+n;return{position:[u[0],c,u[1]],rotation:180*-ei(ui(a,o))/Math.PI}}function Sr(t,e,i,s){const r=.001;let n=s.parameters.dimensions[0],o=s.parameters.dimensions[1],{width:a,elevation:l}=e.parameters,{position:[h,u,c],rotation:d}=Ir(e,s,r),p=s.parameters.materials,f={id:i,type:"geometry:cuboid",position:[h,u-r-l,c],rotation:d,dimensions:[n,o+r,a+.002],surfaces:{top:[0],bottom:[1],frontBack:[2,4],sides:[3,5]}},m={top:p.top,bottom:p.bottom,frontBack:"#FFFFFF",sides:p.sides};f.materials=m;let g=e.geometries[0].geometry;g.geometries??(g.geometries=[]),g.geometries.push({type:"csg:subtract",geometry:f}),s.emit("geometry-update",s)}function Cr(t,e){let i,s={},r=Vs(0,e);for(let[n,o]of Object.entries(t))if("string"==typeof o)"..."===o?i=n:ve.warn("Invalid surface definition string.");else if(Array.isArray(o)){s[n]=[];for(let t of o){if(t<0||t>=e){ve.warn(`Face index ${t} out of range when defining surface ${n}.`);continue}let i=r.indexOf(t);-1!==i?(s[n].push(t),r.splice(i,1)):ve.warn(`Face index ${t} already assigned when defining surface ${n}.`)}}else ve.warn("Invalid surface definition.");return i&&r.length>0&&(s[i]=r),s}function Mr(t){let e,{surfaces:i,materials:s}=t.parameters;for(let r=0;r<t.boundaries.length;r++){let n=t.boundaries[r],o=t.parameters.elevation,a=or(n.edges);if(!a)return void ve.warn(`Could not create geometry for boundary wall ${t.id}.`);let l=a.map(t=>t.position),h=0===r?"boundary":"hole-"+r,u={id:`boundaryWallGeometry-${t.id}-${h}`,type:"geometry:extrusion",position:[0,o,0],height:t.parameters.height,profile:{type:"curve:polygon",points:l},geometries:[]};u.surfaces=Cr(i,2+l.length),u.materials=JSON.parse(JSON.stringify(s)),0===r?(e=u,t.geometries=[{type:"reference:geometry",geometry:u}]):e.geometries.push({type:"csg:subtract",geometry:u})}t.emit("geometry-update",t)}function Or(t){let{length:e,height:i,frameThickness:s,frameDepth:r,doorAngle:n,hingeSide:o,doorSide:a,doorType:l,materials:h}=t.parameters,u="right"===o,c=[e/2,r/2],d=qs(t),p=.05,f=[],m=(180-Math.min(180,Math.max(0,n)))/180,g=(r-p)/2,y=e-2*s,v=i-s;switch(l){case"singleSwing":u?f.push({position:[s-c[0],0,-c[1]],rotation:n,dimensions:[y,v,p]}):f.push({position:[c[0]-s,0,-c[1]],dimensions:[p,v,y],rotation:270-n});break;case"doubleSwing":y=e/2-s,f.push({position:[s-c[0],0,-c[1]],rotation:n,dimensions:[y,v,p]}),f.push({position:[c[0]-s,0,-c[1]],rotation:270-n,dimensions:[p,v,y]});break;case"slidingDoor":y=(e-2*s)*m;let t=u?s-c[0]:c[0]-y-s;f.push({position:[t,0,-c[1]+g],rotation:0,dimensions:[y,v,p]});break;case"garageDoor":f.push({position:[s-c[0],v*(1-m),-c[1]+g],rotation:0,dimensions:[y,v*m,p]});break;case"elevatorDoor":y=(e-2*s)/2-.005,f.push({position:[s-c[0],0,-c[1]+g],rotation:0,dimensions:[y,v,p]}),f.push({position:[0,0,-c[1]+g],rotation:0,dimensions:[y,v,p]})}let x=[];for(let b=0;b<f.length;b++){let{position:t,rotation:e,dimensions:i}=f[b],s={id:d+"-leaf-"+b,type:"geometry:cuboid",position:t,rotation:e,dimensions:i,material:h.leaf};x.push({type:"reference:geometry",position:[c[0],0,c[1]],rotation:"side2"===a?180:0,geometry:s})}return x}function Nr(t,e,i){let s=qs(t),{stepCount:r,stepHeight:n,angle:o,radius:a,width:l,circulation:h}=i,u=a-l,c=a-l/2,d=Math.PI*o/180*c/r/(u+l/2),p=[0,n,0],f=180/Math.PI*d,m=0;"right"===h&&(f=-f,m=180);let g=function(t,e,i){let{stepThickness:s,stepHeight:r,angle:n,width:o,stepCount:a,radius:l,circulation:h}=i,u=l-o/2,c=l-o,d=Math.PI*n/180*u/a/(c+o/2),p="right"===h,f=r,m=c,g=(p?-1:1)*Math.sin(d)*c,y=r-s,v=Math.cos(d)*c,x=-s,b=c+o,w=(p?-1:1)*Math.sin(d)*(c+o),_=Math.cos(d)*(c+o),P=[0,f,m,0,0,m,g,y,v,g,f,v,0,x,m,0,f,b,0,0,b,w,y,_,w,f,_,0,x,b],E=[0,8,3,0,5,8,0,3,2,0,2,1,1,2,4,0,6,5,0,1,6,5,7,8,5,6,7,6,9,7,2,7,4,4,7,9,8,7,3,7,2,3];if(p)for(let T=0;T<E.length;T+=3){let t=E[T+1];E[T+1]=E[T+2],E[T+2]=t}return{id:t,type:"geometry:mesh",vertices:P,indices:E,rotation:0,surfaces:{top:[0,1],base:[2,3,4,5,6,7,8,9,10,11,12,13]},materials:{top:e.tread,base:e.steps}}}(s,e,i);return{type:"reference:geometry",position:{type:"vector3:range",range:{start:[0,0,0],step:p,count:r}},rotation:{type:"number:range",range:{start:m,step:f,count:r}},geometry:g}}function Lr(t){let{width:e,height:i,materials:s}=t.parameters;const r=Math.max(1,Math.round(i/.17)),n={height:i,width:e,stepCount:r,stepHeight:i/r,stepThickness:.1};let o;if("straight"===t.parameters.stairFlightType){let{length:e}=t.parameters;o=function(t,e,i){let{stepCount:s,width:r,stepHeight:n,length:o,stepThickness:a}=i,l=o/s,h=[l,n,0],u=function(t,e,i){let{riser:s,tread:r,width:n,thickness:o}=i;return{id:t,type:"geometry:extrusion",rotation:90,rotationAxis:[1,0,0],height:n,profile:{type:"curve:polygon",points:[[0,0],[0,o],[r,o-s],[r,-s],[0,-s]]},surfaces:{top:[5],base:[0,1,2,3,4,6]},materials:{top:e.tread,base:e.steps}}}(qs(t),e,{tread:l,riser:n,width:r,thickness:a});return{type:"reference:geometry",position:{type:"vector3:range",range:{start:[0,0,0],step:h,count:s}},geometry:u}}(t,s,{...n,length:e})}else{let{radius:e,angle:i,circulation:r}=t.parameters;o=Nr(t,s,{...n,radius:e,angle:i,circulation:r})}t.geometries=[o],t.emit("geometry-update",t)}function Rr(t,e=!1){let{sidePoints1:i,sidePoints2:s,joinPoints1:r,joinPoints2:n,points:o}=t.geometryProfile;if(0===o.length)return;let a="wallGeometry-"+t.id,l={id:a,type:"geometry:extrusion",position:[0,t.parameters.elevation,0],height:t.parameters.height,profile:{type:"curve:composite",segments:[{type:"curve:polyline",points:i},{type:"curve:polyline",points:r},{type:"curve:polyline",points:s},{type:"curve:polyline",points:n}]}},h=t.parameters.materials,u={top:[0],bottom:[1],side1:[2],side2:[4]},c={top:e?Ks():h.top??Xs.top,bottom:h.bottom??Xs.bottom,side1:h.side1??Xs.side1,side2:h.side2??Xs.side2},[d,p]=function(t){let e=[!1,!1],i=[t.getStartVertex(),t.getEndVertex()];for(let s=0;s<i.length;s++){let t=i[s];t&&(t.edges.filter(t=>{var e;return"element:wall"===(null==(e=t.element)?void 0:e.type)}).map(t=>t.element).length>0?e[s]=!0:ve.error(`Vertex ${t.id} not referencing edge that references it.`))}return e}(t);d&&(u.join1=[3],c.join1=h.join1??Xs.join1),p&&(u.join2=[5],c.join2=h.join2??Xs.join2),l.surfaces=u,l.materials=c,t.geometries=[{type:"reference:geometry",geometry:l}];for(let f=0;f<t.elements.length;f++){let e=t.elements[f];if("element:opening"!==e.type)continue;let i=a+"-opening-"+(f+1);Sr(t.layout,t,i,e)}t.emit("geometry-update",t)}function Br(t){switch(t.type){case"element:asset":case"element:beam":case"element:curtainWall":case"element:opening":case"element:ramp":case"element:roof":case"element:spaceDivider":case"element:stairs":break;case"element:casework":!function(t){let{length:e,width:i,height:s,counterHeight:r,materials:n}=t.parameters,o=Math.min(.6,e),a=Math.floor(e/o),l=e%o,h=i-.02,u=s-r,c=.02,d=qs(t),p=[],f=t.elements;for(let y of f)if("product"in y&&y.product){let{min:t,max:e}=y.product.getBoundingBox();if(0===pi(t,e))continue;let i=di(t,[0,.01,0]),s=di(e,i),r=ci(i,y.position);p.push({id:d+"-subtraction-"+y.id.substring(0,8),type:"geometry:cuboid",position:[...r],dimensions:s})}let m=[];r>0&&m.push({id:d+"-counter",type:"geometry:cuboid",position:[0,u,0],dimensions:[e,r,i],material:n.counter}),m.push({id:d+"-doors",type:"geometry:cuboid",position:{type:"vector3:range",range:{start:[c,c,h],step:[o,0,0],count:a}},dimensions:[o-.04,u-.04,c],material:n.cabinetDoors}),l>.04&&m.push({id:d+"-doors+2",type:"geometry:cuboid",position:[a*o+c,c,h],dimensions:[l-.04,u-.04,c],material:n.cabinet});let g={id:d+"-cabinet",type:"geometry:cuboid",position:[0,0,0],dimensions:[e,u,h],geometries:[...m.map(t=>({type:"reference:geometry",geometry:t})),...p.map(t=>({type:"csg:subtract",geometry:t}))],material:n.cabinet};t.geometries=[{type:"reference:geometry",geometry:g}],t.emit("geometry-update",t)}(t);break;case"element:column":!function(t){let{profile:e,height:i,materials:s}=t.parameters,r=qs(t),n=[0,0,0];"curve:rectangle"===e.type&&(n=[-e.dimensions[0]/2,0,-e.dimensions[1]/2]);let o={id:r,type:"geometry:extrusion",position:n,profile:e,height:i},a=Js(e);o.surfaces={top:[0],bottom:[1],sides:Vs(2,2+a)},o.materials={top:s.top,bottom:s.bottom,sides:s.sides},t.geometries=[{type:"reference:geometry",geometry:o}],t.emit("geometry-update",t)}(t);break;case"element:ceiling":case"element:floor":Zs(t);break;case"element:boundaryWall":Mr(t);break;case"element:door":!function(t){let{height:e,length:i,frameThickness:s,frameDepth:r,materials:n}=t.parameters,o=qs(t),a={id:o+"-frame-top",type:"geometry:cuboid",position:[0,e-s,0],rotation:0,dimensions:[i,s,r],material:n.frame},l={id:o+"-frame-side",type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,0,0],[i-s,0,0]]},rotation:0,dimensions:[s,e-s,r],material:n.frame};t.geometries=[{type:"reference:geometry",geometry:a},{type:"reference:geometry",geometry:l},...Or(t)],t.emit("geometry-update",t)}(t);break;case"element:generic":!function(t){let{profile:e,height:i,materials:s}=t.parameters;if("none"===e)return;let r=Js(e),n={id:qs(t),type:"geometry:extrusion",position:[0,0,0],profile:e,height:i,surfaces:{top:[0],bottom:[1],sides:Vs(2,2+r)},materials:{top:s.top,bottom:s.bottom,sides:s.sides}};t.geometries=[{type:"reference:geometry",geometry:n}],t.emit("geometry-update",t)}(t);break;case"element:railing":!function(t){let e,{height:i,length:s,width:r,segmentCount:n,segmentLength:o,materials:a}=t.parameters,l=.01;e=o&&o>0?Math.max(Math.round(s/o),1):n&&n>0?n:Math.max(Math.round(s/.12),1);let h=(s-l)/e,u=qs(t),c={id:u+"-horizontal",type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,i-l,-r/2],[0,0,-r/2]]},rotation:0,dimensions:[s,l,r],material:a.surface},d={id:u+"-vertical",type:"geometry:cuboid",position:{type:"vector3:range",range:{start:[0,l,-r/2],step:[h,0,0],count:e+1}},rotation:0,dimensions:[l,i-.02,r],material:a.surface};t.geometries=[{type:"reference:geometry",geometry:c},{type:"reference:geometry",geometry:d}],t.emit("geometry-update",t)}(t);break;case"element:slab":!function(t){let{profile:e,height:i,materials:s}=t.parameters,r={id:qs(t),type:"geometry:extrusion",position:[0,0,0],profile:e,height:i},n=Js(e);r.surfaces={top:[0],bottom:[1],sides:Vs(2,2+n)},r.materials={top:s.top,bottom:s.bottom,sides:s.sides},t.geometries=[{type:"reference:geometry",geometry:r}],t.emit("geometry-update",t)}(t);break;case"element:stairFlight":Lr(t);break;case"element:wall":Rr(t);break;case"element:window":!function(t){let{panelCount:e,panelLength:i,height:s,length:r,frameThickness:n,frameDepth:o,materials:a}=t.parameters,l=qs(t),h={id:l,type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,s-n,0],[0,0,0]]},rotation:0,dimensions:[r,n,o],material:a.frame},u=[[0,n,0]],c=r-n;if(e&&(i=c/e),i&&i>n){let t=i;for(;t<c;)u.push([t,n,0]),t+=i}u.push([r-n,n,0]);let d={id:l+"-vertical",type:"geometry:cuboid",position:{type:"vector3:list",list:u},rotation:0,dimensions:[n,s-2*n,o],material:a.frame},p={id:l+"-glass",type:"geometry:extrusion",position:[n,n,o/2],rotation:0,height:s-2*n,profile:{type:"curve:rectangle",dimensions:[r-2*n,.01]},material:a.panel};t.geometries=[{type:"reference:geometry",geometry:h},{type:"reference:geometry",geometry:d},{type:"reference:geometry",geometry:p}],t.emit("geometry-update",t)}(t)}for(let e of t.elements)Br(e)}function kr(t){for(let e of t.elements)Br(e)}const Fr={position:[0,0],dimensions:[1,2],materials:{top:"#FFFFFF",bottom:"#FFFFFF",sides:"#FFFFFF"}};class Dr extends Ar{constructor(t){super(t,"element:opening"),this.parameters=JSON.parse(JSON.stringify(Fr))}getTransform(){var t;if("element:wall"!==(null==(t=this.parent)?void 0:t.type)){const t=this.parent?`Parent of element ${this.id} is not a wall.`:`Element ${this.id} does not have a parent.`;return ve.error(t),{position:[0,0,0],rotation:0,rotationAxis:[0,1,0]}}let{position:e,rotation:i}=Ir(this.parent,this);return{position:e,rotation:i,rotationAxis:[0,1,0]}}get position(){return this.getTransform().position}get rotation(){return this.getTransform().rotation}setParameters(t){let e=!!t.position,i=!!t.dimensions;if(super.setParameters(t),this.emit("element-parameters-change",this),e||i){let t=this.parent;if(t&&Br(t),i)for(let e of this.elements)Br(e);this.resetSpatialIndexing()}}getBoundingBox(t=!1){const{dimensions:e}=this.parameters,i=this.parent,s=(null==i?void 0:i.parameters.width)||0;return{min:[0,0,0],max:[e[0],e[1],s],transform:t?this.getTransform():this.getWorldTransform()}}getSpaces(){if(this.parent){return this.parent.getSpaces().filter(t=>Ds(t,this))}return ve.error(`Element ${this.id} does not have a parent.`),[]}get isExternal(){const t=this.parent;if(!t)return super.isExternal;const[e]=t.getAxisPoints();if(!e)return super.isExternal;const i=t.getAxisLength(),{position:s,dimensions:r}=this.parameters,n=s[0]/i,o=(s[0]+r[0])/i,a=t.getEdgesAtLinearSegment(n,o);if(1===a.length)return a[0].isExternal;let l=0,h=0;for(const u of a){const[t,s]=u.getPoints().map(t=>ni(e,t)/i).sort((t,e)=>t-e),r=(o>s?s:o)-(n>t?n:t);u.isExternal?l+=r:h+=r}return l>=h}}class Ur extends Ns{constructor(t,e){super(t,e),this.position=[0,0,0],this.rotation=0,this.rotationAxis=[0,1,0]}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation,this.rotationAxis=[...t.rotationAxis]}setPosition(t){this.position=[...t],this.resetTransform(!0),this.emit("element-transform-change",this)}setRotation(t,e){this.rotation=t,e&&(this.rotationAxis=[...e]),this.resetTransform(!0),this.emit("element-transform-change",this)}setTransform(t,e,i){this.position=[...t],this.rotation=e,i&&(this.rotationAxis=[...i]),this.resetTransform(!0),this.emit("element-transform-change",this)}getSpaces(){if(this.parent)return this.parent.getSpaces();let t=[this.position[0],this.position[2]];for(let e of this.layout.spaces)if(xi(t,e.geometry.polygons))return[e];return[]}calculateTransform(){return{position:[...this.position],rotation:this.rotation,rotationAxis:[...this.rotationAxis]}}calculateWorldTransform(){if(!this.parent)return this.getTransform();let t=yr(this),{position:e,rotation:i,rotationAxis:s}=Ai(t);return 0===s[0]&&s[1]<0&&0===s[2]&&(s=[0,1,0],i=-i),{position:e,rotation:i,rotationAxis:s}}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0];if("length"in this.parameters&&(e[0]=this.parameters.length),"height"in this.parameters&&(e[1]=this.parameters.height),"width"in this.parameters?e[2]=this.parameters.width:"frameDepth"in this.parameters&&(e[2]=this.parameters.frameDepth),"radius"in this.parameters&&(t[0]=t[2]=-this.parameters.radius,e[0]=e[2]=this.parameters.radius),"profile"in this.parameters&&"none"!==this.parameters.profile)switch(this.parameters.profile.type){case"curve:rectangle":{let[i,s]=this.parameters.profile.dimensions;e[0]=i,e[2]=s,"element:column"===this.type&&(t[0]=-i/2,e[0]=i/2,t[2]=-s/2,e[2]=s/2);break}case"curve:circle":t[0]=t[2]=-this.parameters.profile.radius,e[0]=e[2]=this.parameters.profile.radius;break;case"curve:polygon":let i=W([this.parameters.profile.points]);t[0]=i.min[0],e[0]=i.max[0],t[2]=i.min[1],e[2]=i.max[1]}return{min:t,max:e}}setParameters(t){super.setParameters(t),Br(this)}}const Gr={materials:{}};class Xr extends Ur{constructor(t){super(t,"element:asset"),this.product=null,this.parameters=JSON.parse(JSON.stringify(Gr))}get isComponentInstance(){var t;return"product:component"===(null==(t=this.product)?void 0:t.type)}get isComponentInstanceChild(){var t;return"element:asset"===(null==(t=this.parent)?void 0:t.type)&&this.parent.isComponentInstance}setParameters(t){super.setParameters(t)}setProduct(t){this.product=t,this.product.instances.add(this),this.resetBoundingBox(),this.emit("node-property-change",this,"product"),this.emit("geometry-update",this)}calculateBoundingBox(){if(!this.product)return super.calculateBoundingBox();const{min:t,max:e}=this.product.getBoundingBox();return{min:t,max:e}}}const Wr={length:2,width:.1,height:.2,materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class Yr extends Ur{constructor(t){super(t,"element:beam"),this.parameters=JSON.parse(JSON.stringify(Wr))}setParameters(t){super.setParameters(t)}}const Hr={length:2,height:.7,width:.6,counterHeight:.03,materials:{cabinet:"asm:cabinet_paint_white",cabinetDoors:"asm:cabinet_paint_white",counter:"asm:cabinet_paint_white"}};class $r extends Ur{constructor(t){super(t,"element:casework"),this.parameters=JSON.parse(JSON.stringify(Hr))}setParameters(t){super.setParameters(t)}}const jr={type:"curve:circle",radius:.1},zr={"curve:circle":{...jr},"curve:rectangle":{type:"curve:rectangle",dimensions:[.1,.1]},"curve:polygon":{type:"curve:polygon",points:[[0,0],[.1,0],[.1,.1],[0,.1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[.1,0],[.1,.1],[0,.1]],[[.02,.02],[.02,.08],[.08,.08],[.08,.02]]]}},Vr={profile:{...jr},height:3,materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class qr extends Ur{constructor(t){super(t,"element:column"),this.parameters=JSON.parse(JSON.stringify(Vr))}setParameters(t){var e;(null==(e=t.profile)?void 0:e.type)&&t.profile.type!==this.parameters.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(zr[t.profile.type]))),super.setParameters(t)}}const Jr={length:1,height:2,frameThickness:.05,frameDepth:.1,doorType:"singleSwing",doorAngle:90,hardware:!0,hingeSide:"right",doorSide:"side1",materials:{frame:"asm:doorLeaf-flush-white",leaf:"asm:doorLeaf-flush-white"}};class Kr extends Ur{constructor(t){super(t,"element:door"),this.parameters=JSON.parse(JSON.stringify(Jr))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const t=super.calculateBoundingBox(),{doorType:e,frameThickness:i,frameDepth:s,doorSide:r,length:n}=this.parameters;if("singleSwing"===e||"doubleSwing"===e){const o="singleSwing"===e?n-2*i:n/2-i;"side1"===r?t.min[2]=-o:t.max[2]=s+o}return t}}const Zr={"curve:circle":{type:"curve:circle",radius:.5},"curve:rectangle":{type:"curve:rectangle",dimensions:[1,1]},"curve:polygon":{type:"curve:polygon",points:[[0,0],[1,0],[1,1],[0,1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[1,0],[1,1],[0,1]],[[.25,.25],[.25,.75],[.75,.75],[.75,.25]]]}},Qr={profile:"none",height:0,materials:{top:"#F0F0F0",bottom:"#F0F0F0",sides:"#F0F0F0"}};class tn extends Ur{constructor(t){super(t,"element:generic"),this.parameters=JSON.parse(JSON.stringify(Qr))}setParameters(t){t.profile&&"none"!==t.profile&&t.profile.type&&"none"!==this.parameters.profile&&this.parameters.profile.type!==t.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(Zr[t.profile.type]))),super.setParameters(t)}}const en="product:static",sn={manufacturer:"",categories:[],subCategories:[],thumbnail:"",boundingBox:{min:[0,0,0],max:[0,0,0]},seatCapacity:0,updatedAt:""};class rn extends gs{constructor(t,e){super(t,e),this.instances=/* @__PURE__ */new Set,this.attributes=JSON.parse(JSON.stringify(sn))}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes))}setAttributes(t){var e,i;let s=this.attributes;s.manufacturer=t.manufacturer??s.manufacturer,s.categories=(null==(e=t.categories)?void 0:e.slice())??s.categories,s.subCategories=(null==(i=t.subCategories)?void 0:i.slice())??s.subCategories,s.thumbnail=t.thumbnail??s.thumbnail,t.boundingBox&&(s.boundingBox.min=[...t.boundingBox.min],s.boundingBox.max=[...t.boundingBox.max]),s.seatCapacity=t.seatCapacity??s.seatCapacity,s.updatedAt=t.updatedAt??s.updatedAt}getBoundingBox(){return this.attributes.boundingBox}toJSON(){const t=super.toJSON(),e={},i=this.attributes;""!==i.manufacturer&&(e.manufacturer=i.manufacturer),i.categories.length>0&&(e.categories=[...i.categories]),i.subCategories.length>0&&(e.subCategories=[...i.subCategories]),""!==i.thumbnail&&(e.thumbnail=i.thumbnail);let{min:s,max:r}=i.boundingBox;return 0===s[0]&&0===pi(r,s)||(e.boundingBox={min:[...i.boundingBox.min],max:[...i.boundingBox.max]}),i.seatCapacity>0&&(e.seatCapacity=i.seatCapacity),""!==i.updatedAt&&(e.updatedAt=i.updatedAt),t.attributes=e,t}}class nn extends rn{constructor(t){super(t,en),this.geometries=[]}copyForClone(t){super.copyForClone(t),this.geometries=JSON.parse(JSON.stringify(t.geometries))}toJSON(){return{...super.toJSON(),type:en,geometries:JSON.parse(JSON.stringify(this.geometries))}}}const on="product:component";class an extends rn{constructor(t){super(t,on),this.products=[],this.geometries=[],this.attributes=JSON.parse(JSON.stringify(sn))}copyForClone(t){super.copyForClone(t),this.products=JSON.parse(JSON.stringify(t.products))}toJSON(){return{...super.toJSON(),type:on,products:JSON.parse(JSON.stringify(this.products)),geometries:[]}}setProducts(t){this.products=JSON.parse(JSON.stringify(t))}setInstances(){var t;for(const e of this.instances){if(this.products.length===e.elements.length&&this.products.every((t,i)=>{var s;const r=e.elements[i];return"element:asset"===(null==r?void 0:r.type)&&t.product===(null==(s=r.product)?void 0:s.id)}))for(let i=0;i<this.products.length;i++){const s=this.products[i];if("type"in s.position)continue;if("number"!=typeof s.rotation)continue;const r=e.elements[i];"element:asset"===r.type&&(null==(t=r.product)?void 0:t.id)===s.product&&r.setTransform(s.position,s.rotation)}else{for(let t=e.elements.length-1;t>=0;t--)e.removeElement(e.elements[t]);for(const t of this.products){const i=new Xr(Ut()),s=this.spaceGraph.productsById[t.product];s||ve.error(`Product ${t.product} is missing`),i.setProduct(s),"type"in t.position||"number"==typeof t.rotation&&(i.setTransform(t.position,t.rotation),e.insertElement(i))}}}}}function ln(t){for(let e=t.elements.length-1;e>=0;e--)t.removeElement(t.elements[e])}function hn(t,e,i){let s=t.elements.filter(t=>t.type===e);for(let r=s.length-1;r>=i;r--)t.removeElement(s[r]);for(let r=0;r<i;r++)if(!s[r]){let i=Ut();s[r]="element:casework"===e?new $r(i):new Xr(i),t.insertElement(s[r])}return s}function un(t){let{length:e,width:i,height:s,wallCabinet:r,leftHighCabinetCount:n,rightHighCabinetCount:o,sinkElementSlot:a,materials:l}=t.parameters,h=Math.min(.6,e),u=s-1.5,c=Math.min(e,h*Math.max(n,0)),d=e>c?h*o:0,p=Math.max(e-c-d,0);d=Math.max(e-c-p,0);let f=0;p>0&&(f++,r&&f++),c>0&&f++,d>0&&f++;let m=p>0&&a*h>=c&&a*h<=c+p,g=hn(t,"element:casework",f),y={cabinet:l.cabinet,cabinetDoors:l.cabinetDoors,counter:l.counter};if(p>0){let e=g.shift();if(e){let s=hn(e,"element:asset",m?1:0);if(m){let e=s[0],r=function(t){const e="7f24bd1c-1ebc-4724-8cd4-ca78c7d4a1e5";if(null==t?void 0:t.productsById[e])return null==t?void 0:t.productsById[e];let i=new nn(e);return i.setName("Kitchen Sink"),i.setAttributes({categories:["appliances"],subCategories:["kitchen"],boundingBox:{max:[.54,.21,0],min:[0,-.17,-.47]}}),i.geometries=[{type:"reference:geometry",geometry:{id:"sinkGeometry",type:"geometry:uri",format:"data3d",uri:"015f8f8e-e588-4f51-a342-2930559834ee/201208-0355-60hukz/bf4e4a56-ed95-4b58-a214-4b1a0a84ae0e.gz.data3d.buffer"}}],i}(t.spaceGraph),{min:n,max:o}=r.getBoundingBox(),l=ci(n,(v=di(o,n),x=.5,[v[0]*x,v[1]*x,v[2]*x]));l[1]=0;let u=ci([a*h-c,.9,0],[h/2,0,i/2]);r&&(e.setProduct(r),e.setPosition(di(u,l)))}e.setParameters({length:p,width:i,height:.9,counterHeight:.03,materials:{...y}}),e.setTransform([c,0,0],0)}let s=r&&g.shift();s&&(ln(s),s.setParameters({length:p,width:.45,height:u,counterHeight:0,materials:{...y}}),s.setTransform([c,1.5,0],0))}var v,x;let b=c>0&&g.shift();b&&(ln(b),b.setParameters({length:c,width:i,height:s,counterHeight:0,materials:{...y}}),b.setTransform([0,0,0],0));let w=d>0&&g.shift();w&&(ln(w),w.setParameters({length:d,width:i,height:s,counterHeight:0,materials:{...y}}),w.setTransform([c+p,0,0],0))}const cn={length:3,width:.6,height:2.2,wallCabinet:!0,leftHighCabinetCount:1,rightHighCabinetCount:0,sinkElementSlot:-1,cooktopElementSlot:-1,ovenElementSlot:-1,materials:{cabinet:"asm:cabinet_paint_white",cabinetDoors:"asm:cabinet_paint_white",counter:"asm:cabinet_paint_white"}};class dn extends Ur{constructor(t){super(t,"element:kitchen"),this.parameters=JSON.parse(JSON.stringify(cn))}setParameters(t,e=!1){super.setParameters(t),e||un(this),this.emit("element-parameters-change",this)}}const pn={length:2,width:.05,height:1,segmentCount:0,segmentLength:.12,materials:{surface:"#CCCCCC"}};class fn extends Ur{constructor(t){super(t,"element:railing"),this.parameters=JSON.parse(JSON.stringify(pn))}setParameters(t){super.setParameters(t)}}const mn={length:2,width:1,height:.5,materials:{top:"asm:basic-floor",bottom:"asm:basic-wall",sides:"asm:basic-wall"}};class gn extends Ur{constructor(t){super(t,"element:ramp"),this.parameters=JSON.parse(JSON.stringify(mn))}}const yn={materials:{}};class vn extends Ur{constructor(t){super(t,"element:roof"),this.parameters=JSON.parse(JSON.stringify(yn))}}const xn={type:"curve:rectangle",dimensions:[1,1]},bn={"curve:circle":{type:"curve:circle",radius:1},"curve:rectangle":{...xn},"curve:polygon":{type:"curve:polygon",points:[[0,0],[1,0],[1,1],[0,1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[1,0],[1,1],[0,1]],[[.25,.25],[.25,.75],[.75,.75],[.75,.25]]]}},wn={profile:{...xn},height:.1,materials:{top:"asm:basic-floor",bottom:"asm:basic-floor",sides:"asm:basic-wall"}};class _n extends Ur{constructor(t){super(t,"element:slab"),this.parameters=JSON.parse(JSON.stringify(wn))}setParameters(t){var e;(null==(e=t.profile)?void 0:e.type)&&t.profile.type!==this.parameters.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(bn[t.profile.type]))),super.setParameters(t)}}const Pn={height:3,width:1.2,materials:{steps:"asm:basic-wall",tread:"asm:basic-floor"}},En={straight:{stairFlightType:"straight",length:3,...Pn},spiral:{stairFlightType:"spiral",angle:270,radius:1.5,circulation:"right",...Pn}};class Tn extends Ur{constructor(t){super(t,"element:stairFlight"),this.parameters=JSON.parse(JSON.stringify(En.straight))}setParameters(t){if(t.stairFlightType&&this.parameters.stairFlightType!==t.stairFlightType){let{height:e,materials:i,width:s}=this.parameters;this.parameters={...JSON.parse(JSON.stringify(En[t.stairFlightType])),height:e,materials:i,width:s}}super.setParameters(t)}}function An(t,e,i){let s=t.elements.filter(t=>t.type===e);for(let r=s.length-1;r>=i;r--)t.removeElement(s[r]);for(let r=0;r<i;r++)if(!s[r]){let i=Ut();s[r]="element:stairFlight"===e?new Tn(i):new _n(i),t.insertElement(s[r])}return s}const In=.1;const Sn={height:3,railing:"right",materials:{steps:"asm:basic-wall",tread:"asm:basic-floor",railing:"#CCCCCC"}},Cn={straight:{stairsType:"straight",length:4,width:1.2,...Sn},straightLanding:{stairsType:"straightLanding",length:4,width:1.2,...Sn},halfLanding:{stairsType:"halfLanding",length:4,width:2.5,stepWidth:1.2,circulation:"right",...Sn},quarterLanding:{stairsType:"quarterLanding",length:4,width:2.5,stepWidth:1.2,circulation:"right",...Sn},twoQuarterLanding:{stairsType:"twoQuarterLanding",length:3,width:4,stepWidth:1.2,circulation:"right",...Sn},winder:{stairsType:"winder",length:4,width:2.5,stepWidth:1.2,circulation:"right",...Sn},doubleWinder:{stairsType:"doubleWinder",length:4,width:2.5,stepWidth:1.2,circulation:"right",...Sn},spiral:{stairsType:"spiral",radius:1.5,angle:270,stepWidth:1.2,circulation:"right",...Sn},custom:{stairsType:"custom",stepWidth:1.2,...Sn}},Mn=Cn.straight;class On extends Ur{constructor(t){super(t,"element:stairs"),this.parameters=JSON.parse(JSON.stringify(Mn))}setParameters(t,e=!1){if(t.stairsType&&this.parameters.stairsType!==t.stairsType){let{height:e,railing:i,materials:s}=this.parameters;this.parameters={...JSON.parse(JSON.stringify(Cn[t.stairsType])),height:e,railing:i,materials:s}}super.setParameters(t),e||function(t){switch(t.parameters.stairsType){case"straight":{let{length:e,width:i,height:s,materials:r}=t.parameters,[n]=An(t,"element:stairFlight",1);An(t,"element:slab",0),n.setParameters({stairFlightType:"straight",length:e,width:i,height:s,materials:{steps:r.steps,tread:r.tread}}),n.setTransform([0,0,0],0);break}case"straightLanding":{let{length:e,width:i,height:s,materials:r}=t.parameters,n=(e-i)/2,[o,a]=An(t,"element:stairFlight",2),[l]=An(t,"element:slab",1);o.setParameters({stairFlightType:"straight",length:n,width:i,height:s/2,materials:{steps:r.steps,tread:r.tread}}),o.setTransform([0,0,0],0),l.setParameters({profile:{type:"curve:rectangle",dimensions:[i,i]},height:In,materials:{top:r.tread,bottom:r.steps,sides:r.steps}}),l.setTransform([n,s/2-In,0],0),a.setParameters({stairFlightType:"straight",length:n,width:i,height:s/2}),a.setTransform([e-n,s/2,0],0);break}case"halfLanding":{let{length:e,width:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,[l,h]=An(t,"element:stairFlight",2),[u]=An(t,"element:slab",1);l.setParameters({stairFlightType:"straight",length:e-r,width:r,height:s/2,materials:{steps:o.steps,tread:o.tread}}),l.setTransform([0,0,a?0:-r],0),u.setParameters({profile:{type:"curve:rectangle",dimensions:[r,i]},height:In,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),u.setPosition([e-r,s/2-In,a?0:-i]),h.setParameters({stairFlightType:"straight",length:e-r,width:r,height:s/2,materials:{steps:o.steps,tread:o.tread}}),h.setTransform([e-r,s/2,a?i:-i+r],-180);break}case"quarterLanding":{let{length:e,width:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,l=e-r,h=i-r,u=l/(l+h)*s,c=h/(l+h)*s,[d,p]=An(t,"element:stairFlight",2),[f]=An(t,"element:slab",1);d.setParameters({stairFlightType:"straight",length:l,width:r,height:u,materials:{steps:o.steps,tread:o.tread}}),d.setTransform([0,0,a?0:-r],0),f.setParameters({profile:{type:"curve:rectangle",dimensions:[r,r]},height:In,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),f.setPosition([e-r,u-In,a?0:-r]),p.setParameters({stairFlightType:"straight",length:h,width:r,height:c,materials:{steps:o.steps,tread:o.tread}}),a?p.setTransform([e,u,r],-90):p.setTransform([e-r,u,-r],90);break}case"twoQuarterLanding":{let{length:e,width:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,l=e-r,h=i-2*r,u=l/(2*l+h)*s,c=h/(2*l+h)*s,[d,p,f]=An(t,"element:stairFlight",3),[m,g]=An(t,"element:slab",2);d.setParameters({stairFlightType:"straight",length:l,width:r,height:u,materials:{steps:o.steps,tread:o.tread}}),d.setTransform([0,0,a?0:-r],0),m.setParameters({profile:{type:"curve:rectangle",dimensions:[r,r]},height:In,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),m.setPosition([e-r,u-In,a?0:-r]),p.setParameters({stairFlightType:"straight",length:h,width:r,height:c,materials:{steps:o.steps,tread:o.tread}}),a?p.setTransform([e,u,r],-90):p.setTransform([e-r,u,-r],90),g.setParameters({profile:{type:"curve:rectangle",dimensions:[r,r]},height:In,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),g.setPosition([e-r,u+c-In,a?i-r:-i]),f.setParameters({stairFlightType:"straight",length:l,width:r,height:u,materials:{steps:o.steps,tread:o.tread}}),f.setTransform([e-r,u+c,a?i:-i+r],-180);break}case"spiral":{let{radius:e,angle:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,[l]=An(t,"element:stairFlight",1);An(t,"element:slab",0),l.setParameters({stairFlightType:"spiral",radius:e,angle:i,height:s,width:r,circulation:n,materials:{steps:o.steps,tread:o.tread}}),l.setTransform([0,0,a?e:-e],0);break}}}(this),this.emit("element-parameters-change",this)}calculateBoundingBox(){const t=super.calculateBoundingBox();return"radius"in this.parameters&&(t.min[2]=0,t.max[2]=2*this.parameters.radius,t.min[0]=-this.parameters.radius,t.max[0]=this.parameters.radius),"circulation"in this.parameters&&"left"===this.parameters.circulation&&(t.min[2]=-t.max[2],t.max[2]=0),t}}const Nn={length:1,height:1.2,frameThickness:.05,frameDepth:.1,panelLength:0,panelCount:1,materials:{frame:"#CCCCCC",panel:"asm:glass"}};class Ln extends Ur{constructor(t){super(t,"element:window"),this.parameters=JSON.parse(JSON.stringify(Nn))}setParameters(t){super.setParameters(t)}}class Rn extends ys{constructor(){super(...arguments),this.position=[0,0,0],this.rotation=0}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation,this.parameters=JSON.parse(JSON.stringify(t.parameters))}setTransform(t,e){this.position=[...t],this.rotation=e,this.emit("annotation-transform-change",this)}setParameters(t){Is(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.emit("annotation-parameters-change",this)}toJSON(){return{...super.toJSON(),position:[...this.position],parameters:JSON.parse(JSON.stringify(this.parameters)),rotation:this.rotation}}}const Bn={uri:"",drawingOrigin:[0,0],drawingUnits:"unitLess",hiddenLayers:[]};class kn extends Rn{constructor(t){super(t,"annotation:floorPlanDxf"),this.parameters=JSON.parse(JSON.stringify(Bn))}setParameters(t){super.setParameters(t)}}class Fn extends ys{copyForClone(t){super.copyForClone(t),this.parameters=JSON.parse(JSON.stringify(t.parameters))}setParameters(t){Is(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.emit("view-parameters-change",this)}toJSON(){return{...super.toJSON(),parameters:JSON.parse(JSON.stringify(this.parameters))}}}const Dn={style:{background:{fill:"#f7f8fa"},units:"metric",byId:{},byType:{},byAttribute:{program:{},usage:{}}},hidden:[]};class Un extends Fn{constructor(t){super(t,"view:2d"),this.parameters=JSON.parse(JSON.stringify(Dn))}setParameters(t){var e,i;let{style:s}=t;void 0===(null==s?void 0:s.byId)&&(this.parameters.style.byId={}),void 0===(null==s?void 0:s.byType)&&(this.parameters.style.byType={}),void 0===(null==(e=null==s?void 0:s.byAttribute)?void 0:e.program)&&(this.parameters.style.byAttribute.program={}),void 0===(null==(i=null==s?void 0:s.byAttribute)?void 0:i.usage)&&(this.parameters.style.byAttribute.usage={}),Is(this.parameters,t,{onNewKeys:{allow:!1},copyScopes:[".style.byId",".style.byType",".style.byAttribute.program",".style.byAttribute.usage"],cloneObjects:!0}),this.emit("view-parameters-change",this)}}const Gn={position:[0,0,0],normal:[0,0,1],fov:"default",scale:1,lensShiftX:0,lensShiftY:0,projection:"perspective"};class Xn extends Fn{constructor(t){super(t,"view:3d"),this.parameters=JSON.parse(JSON.stringify(Gn))}setParameters(t){super.setParameters(t)}}function Wn(t){var e;return null==(e=null==t?void 0:t.type)?void 0:e.startsWith("element")}function Yn(t){return"layout:space"===(null==t?void 0:t.type)}function Hn(t){return"product:component"===(null==t?void 0:t.type)||"product:static"===(null==t?void 0:t.type)}const $n="relation:group";class jn extends be{constructor(t){super(t,$n),this.elements=/* @__PURE__ */new Set}insertElements(t){for(let e of t)this.elements.add(e)}removeElements(t){for(let e of t)this.elements.delete(e)}copyForClone(t){super.copyForClone(t)}toJSON(){const t=super.toJSON();return t.elements=Array.from(this.elements).map(t=>t.id),t}}class zn extends gs{constructor(t,e){super(t,e)}}function Vn(t,e){e.registerNode(t),function(t,e){let{vertices:i,edges:s}=t.spatialGraph;for(let r of i)e.registerNode(r),e.emit("vertex-create",r);for(let r of s)e.registerNode(r),e.emit("edge-create",r)}(t,e);for(let s of t.spaces)e.registerNode(s);let i=t.getElementList();for(let s of i)e.registerNode(s);for(let s of t.annotations)e.registerNode(s);for(let s of t.views)e.registerNode(s);e.emit("spatial-structure-create",t)}function qn(t,e){e.unregisterNode(t),function(t,e){let{vertices:i,edges:s}=t.spatialGraph;for(let r of i)e.unregisterNode(r),e.emit("vertex-delete",r);for(let r of s)e.unregisterNode(r),e.emit("edge-delete",r)}(t,e);for(let s of t.spaces)e.unregisterNode(s);let i=t.getElementList();for(let s of i)e.unregisterNode(s);for(let s of t.annotations)e.unregisterNode(s);e.emit("spatial-structure-delete",t)}function Jn(t,e){e.registerNode(t);for(let i of t.layouts)Vn(i,e);e.emit("spatial-structure-create",t)}function Kn(t,e){e.unregisterNode(t);for(let i of t.layouts)qn(i,e);e.emit("spatial-structure-delete",t)}function Zn(t,e,...i){let s;switch(t){case"element:ceiling":case"element:floor":s=new $s(e,t,i[0]);break;case"element:boundaryWall":s=new wr(e,i[0]);break;case"element:curtainWall":s=new Pr(e,i[0]);break;case"element:spaceDivider":s=new Tr(e,i[0]);break;case"element:wall":s=new Ys(e,i[0]);break;case"element:opening":s=new Dr(e);break;case"element:asset":s=new Xr(e);break;case"element:beam":s=new Yr(e);break;case"element:casework":s=new $r(e);break;case"element:column":s=new qr(e);break;case"element:door":s=new Kr(e);break;case"element:generic":s=new tn(e);break;case"element:kitchen":s=new dn(e);break;case"element:ramp":s=new gn(e);break;case"element:roof":s=new vn(e);break;case"element:railing":s=new fn(e);break;case"element:slab":s=new _n(e);break;case"element:stairs":s=new On(e);break;case"element:stairFlight":s=new Tn(e);break;case"element:window":s=new Ln(e)}return s}const Qn={uri:"",length:1,width:1};class to extends Rn{constructor(t){super(t,"annotation:floorPlanImage"),this.parameters=JSON.parse(JSON.stringify(Qn))}setParameters(t){super.setParameters(t)}}function eo(t,e){let i;switch(t){case"annotation:floorPlanDxf":i=new kn(e);break;case"annotation:floorPlanImage":i=new to(e)}return i}function io(t,e){let i;switch(t){case"view:2d":i=new Un(e);break;case"view:3d":i=new Xn(e)}return i}class so{constructor(){this.nodeMap=/* @__PURE__ */new Map}addNode(t){return this.nodeMap.has(t)||this.nodeMap.set(t,/* @__PURE__ */new Map),this.nodeMap.get(t)}addEdge(t,e,i){var s,r;let n=this.addNode(e),o=this.addNode(i);n.has(t)||n.set(t,/* @__PURE__ */new Set),o.has(t)||o.set(t,/* @__PURE__ */new Set),null==(s=n.get(t))||s.add(i),null==(r=o.get(t))||r.add(e)}removeNode(t){if(this.nodeMap.has(t)){for(let e of this.nodeMap.get(t))for(let i of e[1])this.removeEdge(e[0],t,i);this.nodeMap.delete(t)}}removeEdge(t,e,i){var s,r,n,o;null==(r=null==(s=this.nodeMap.get(e))?void 0:s.get(t))||r.delete(i),null==(o=null==(n=this.nodeMap.get(i))?void 0:n.get(t))||o.delete(e)}findShortestPath(t,e,i,s={}){var r;let n=[[e]],o=/* @__PURE__ */new Set;for(;n.length>0;){let e=n.shift();if(!e)return null;if(s.depthLimit&&e.length-1>s.depthLimit)return null;let a=e[e.length-1];if(a===i)return e;if(!o.has(a)&&this.nodeMap.has(a)&&(null==(r=this.nodeMap.get(a))?void 0:r.has(t))){o.add(a);for(let i of this.nodeMap.get(a).get(t))n.push([...e,i])}}return null}toJSON(){const t=[],e=[];for(const[i,s]of this.nodeMap.entries()){t.push({id:i.id,type:i.type});for(const[t,r]of s.entries())for(const s of r)i.id<s.id&&e.push({type:String(t),nodes:[i.id,s.id]})}return{nodes:t,edges:e}}}const ro=t=>{const e={};for(const i in t)e[i]=[];return e},no={"element:ceiling":$s,"element:floor":$s,"element:boundaryWall":wr,"element:curtainWall":Pr,"element:spaceDivider":Tr,"element:wall":Ys,"element:opening":Dr,"element:asset":Xr,"element:beam":Yr,"element:casework":$r,"element:column":qr,"element:door":Kr,"element:generic":tn,"element:kitchen":dn,"element:railing":fn,"element:ramp":gn,"element:roof":vn,"element:slab":_n,"element:stairs":On,"element:stairFlight":Tn,"element:window":Ln},oo={"annotation:floorPlanDxf":kn,"annotation:floorPlanImage":to},ao={"view:2d":Un,"view:3d":Xn};const lo=t=>{const{min:e,max:i}=t.getAxisAlignedBoundingBox();return{id:t.id,type:t.type,minX:e[0],minY:e[2],maxX:i[0],maxY:i[2]}};class ho extends Ht{constructor(t){super(),this.nodeIds=/* @__PURE__ */new Set,this.layout=t}find({min:t,max:e,margin:i,types:s}){i??(i=0),e??(e=t);const r={minX:t[0]-i,maxX:e[0]+i,minY:t[1]-i,maxY:e[1]+i},n=this.search(r),o=[];for(const a of n)(null==s?void 0:s.length)&&!(null==s?void 0:s.includes(a.type))||(this.layout.spaceGraph.nodesById[a.id]?o.push(this.layout.spaceGraph.nodesById[a.id]):ve.warn(`Indexed node ${a.id} is not part of the layout anymore`));return o}addNode(t){const e=lo(t);this.nodeIds.has(t.id)&&this.remove(e),this.insert(e),this.nodeIds.add(t.id)}removeNode(t){const e=lo(t);this.nodeIds.has(t.id)&&this.remove(e)}remove(t){return this.nodeIds.delete(t.id),super.remove(t,(t,e)=>t.id===e.id),this}}const uo={...no,"spatialGraph:edge":ks,"spatialGraph:vertex":bs,"layout:space":Us,"view:2d":Un,"view:3d":Xn,"annotation:floorPlanDxf":kn,"annotation:floorPlanImage":to};class co extends be{constructor(t,e){super(t,e),this.position=[0,0,0],this.rotation=0,this.rotationAxis=[0,1,0],this.surfaces={},this.materials={},this.boundingBox={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}}class po extends co{constructor(t,e){super(t,e),this.normals="generator",this.uvs="generator",this.geometries=[]}}const fo={"geometry:plane":class extends po{constructor(t){super(t,"geometry:plane"),this.normal=[0,1,0],this.size=1,this.doubleSided=!1}},"geometry:cuboid":class extends po{constructor(t){super(t,"geometry:cuboid"),this.dimensions=[1,1,1]}},"geometry:sphere":class extends po{constructor(t){super(t,"geometry:sphere"),this.radius=1}},"geometry:extrusion":class extends po{constructor(t,e){super(t,"geometry:extrusion"),this.height=1,this.profile=e}},"geometry:mesh":class extends co{constructor(t){super(t,"geometry:mesh"),this.vertices=[],this.indices=[],this.normals=[],this.uvs=[]}},"geometry:uri":class extends co{constructor(t){super(t,"geometry:uri"),this.format="data3d",this.uri="",this.normals="smooth"}}},mo={"material:embedded":Ae,"material:basic":Se,"material:color":_e,"material:standard":Ee},go={"product:static":nn,"product:component":an},yo={"relation:group":jn},vo={...uo,...fo,...mo,...go,...yo,"spatialStructure:building":null,"spatialStructure:floor":null,"spatialStructure:layout":null};function xo(t,e){t.name=e.name??t.name,t.customId=e.customId??t.customId}function bo(t,e){let i;return t.type===on?(i=new an(t.id),i.products=JSON.parse(JSON.stringify(t.products))):(i=new nn(t.id),i.geometries=JSON.parse(JSON.stringify(t.geometries))),t.attributes&&i.setAttributes(t.attributes),t.customAttributes&&i.setCustomAttributes(t.customAttributes,e),xo(i,t),i}function wo(t){return JSON.parse(JSON.stringify(t))}function _o(t){let e;if(Array.isArray(t)||"string"==typeof t)ve.warn("Color literal or standard material reference not allowed in shared resources section.");else if("object"==typeof t)switch(t.type){case we:let[i,s,r,n]=function(t){let[e,i,s,r]=[1,1,1,1];return Array.isArray(t)?[e,i,s,r]=Be(t):"string"==typeof t&&([e,i,s,r]=[1,1,1,1],""===t?ve.warn("Empty string not a valid color literal."):t.startsWith("#")?[e,i,s,r]=ke(t):t.startsWith("rgb(")?[e,i,s,r]=Fe(t,!1):t.startsWith("rgba(")?[e,i,s,r]=Fe(t,!0):ve.warn(`String ${t} not a valid color literal.`)),[e,i,s,r]}(t.value);e=new _e(t.id,[i,s,r],n);break;case Pe:e=new Ee(t.id,t.reference);break;case Ie:e=new Se(t.id),xo(e,t),e.colorDiffuse=[...t.colorDiffuse],t.colorSpecular&&(e.colorSpecular=[...t.colorSpecular]),e.specularCoefficient=t.specularCoefficient??e.specularCoefficient,e.opacity=t.opacity??e.opacity;break;default:e=new _e(t.id,[1,1,1],1),ve.warn(`Unknown material type ${t.type}, creating default material.`)}else ve.warn("Material not an array, string or object.");return e}function Po(t,e){let i;if(e.type===$n){i=new jn(e.id);let s=[];for(let r of e.elements)t.nodesById[r]?s.push(t.nodesById[r]):ve.error(`Element ${r} not found, referenced by relation ${i.id}.`);i.insertElements(s)}return xo(i,e),i}function Eo(t){const e=function(t){const{id:e,attributes:{resourceType:i}}=t;return e.endsWith(`:${i}`)?e:`${e}:${i}`}(t),i=new fs(e,t.attributes);return xo(i,t),i}function To(t,e){!function(t,e){for(let i of e){let e=Eo(i);e&&t.insertCustomAttribute(e)}}(t,e.customAttributes||[]),function(t,e){for(let i of e){let e=bo(i,t.customAttributesById);t.insertProduct(e)}}(t,e.products),function(t,e){for(let i of e){let e=wo(i);t.insertGeometry(e)}}(t,e.geometries),function(t,e){for(let i of e){let e=_o(i);e&&t.insertMaterial(e)}}(t,e.materials)}function Ao(t,e){let i=function(t,e){let i;switch(e.type){case Vo:i=qo.fromJSON(e,{spaceGraph:t,skipInsert:!0});break;case jo:i=zo.fromJSON(e,{spaceGraph:t,skipInsert:!0});break;case Ho:i=$o.fromJSON(e,{spaceGraph:t,skipInsert:!0})}return i}(t,e);t.insertSpatialStructure(i)}function Io(t,e){To(t,e.sharedResources),Ao(t,e.spatialStructure),function(t,e){for(let i of e){let e=Po(t,i);e&&t.insertRelation(e)}}(t,e.sharedResources.relations||[])}class So{constructor(t){this.products=[],this.productsById={},this.productsByType=ro(go),this.customAttributes=[],this.customAttributesById={},this.customAttributesByType=ro(ms),this.geometries=[],this.geometriesById={},this.geometriesByType=ro(fo),this.materials=[],this.materialsById={},this.materialsByType=ro(mo),this.relations=[],this.relationsById={},this.relationsByType=ro(yo),this.nodes=[],this.nodesById={},this.nodesByType=ro(vo),this.spatialStructure=null,this.emitter=new ce.TinyEmitter,this.sourceSchemaVersion=t}getEvents(){return this.emitter.e??{}}copyEvents(t){let e=t.getEvents();for(let[i,s]of Object.entries(e))this.emitter.on(i,s)}deleteNodeAtIndex(t,e,i,s){let r=e[t];if(e.splice(t,1),i[r.id]!==r)return void ve.error(`Entry ${r.id} in 'nodes stored by ID' record does not contain this object.`);delete i[r.id];let n=s[r.type];if(!n)return void ve.error(`Node ${r.id} not found in 'nodes stored by type' record.`);let o=n.indexOf(r);if(-1!==o)return n.splice(o,1),r;ve.error(`Node ${r.id} not found in 'nodes stored by type' record.`)}insertNode(t,e,i,s){i[t.id]?ve.error(`Node ${t.id} already registered.`):(e.push(t),i[t.id]=t,s[t.type]||(s[t.type]=[]),s[t.type].push(t))}removeNode(t,e,i,s){let r=e.indexOf(t);if(-1!==r)return this.deleteNodeAtIndex(r,e,i,s),t;ve.warn(`Node ${t.id} not found.`)}registerNode(t){var e,i;t.spaceGraph=this;let{nodes:s,nodesById:r,nodesByType:n}=this;this.insertNode(t,s,r,n),"getBoundingBox"in t&&"layout"in t&&(null==(e=t.layout)?void 0:e.spatialIndex)&&(null==(i=t.layout)||i.spatialIndex.addNode(t))}unregisterNode(t){var e,i;t.spaceGraph=null;let{nodes:s,nodesById:r,nodesByType:n}=this;this.removeNode(t,s,r,n),"getBoundingBox"in t&&"layout"in t&&(null==(e=t.layout)?void 0:e.spatialIndex)&&(null==(i=t.layout)||i.spatialIndex.removeNode(t))}insertSpatialStructure(t){if(this.spatialStructure)ve.warn(`Space graph object already has spatial structure ${this.spatialStructure.id} attached.`);else if(t.spaceGraph)ve.warn(`Spatial structure ${t.id} already part of a space graph object.`);else{switch(t.spaceGraph=this,this.spatialStructure=t,t.type){case"spatialStructure:building":!function(t,e){e.registerNode(t);for(let i of t.floors)Jn(i,e);e.emit("spatial-structure-create",t)}(t,this);break;case"spatialStructure:floor":Jn(t,this);break;case"spatialStructure:layout":Vn(t,this)}this.emit("spatial-structure-create",t)}}removeSpatialStructure(){let t=this.spatialStructure;if(t){switch(t.spaceGraph=null,this.spatialStructure=null,t.type){case"spatialStructure:building":!function(t,e){e.unregisterNode(t);for(let i of t.floors)Kn(i,e);e.emit("spatial-structure-delete",t)}(t,this);break;case"spatialStructure:floor":Kn(t,this);break;case"spatialStructure:layout":qn(t,this)}return this.emit("spatial-structure-delete",t),t}ve.warn("No spatial structure attached to space graph object.")}insertProduct(t){t.spaceGraph?ve.warn(`Product ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.products,this.productsById,this.productsByType),this.registerNode(t),this.emit("product-create",t))}removeProduct(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.products,this.productsById,this.productsByType),this.unregisterNode(t),this.emit("product-delete",t)):ve.warn(`Product ${t.id} already in a detached state.`)}createProduct(t,e){let i;return i=e===on?new an(t):new nn(t),this.insertProduct(i),i}insertGeometry(t){let{geometries:e,geometriesById:i,geometriesByType:s}=this;e.push(t),i[t.id]=t,s[t.type].push(t)}removeGeometry(t){let{geometries:e,geometriesById:i,geometriesByType:s}=this,r=e.indexOf(t);if(-1===r)return void ve.warn(`Geometry ${t.id} not found.`);if(e.splice(r,1),i[t.id]!==t)return void ve.error(`Entry ${t.id} in 'geometries stored by ID' record does not contain this object.`);delete this.geometriesById[t.id];let n=s[t.type];if(!n)return void ve.error(`Geometry ${t.id} not found in 'geometries stored by type' record.`);let o=n.indexOf(t);-1!==o?n.splice(o,1):ve.error(`Node ${t.id} not found in 'nodes stored by type' record.`)}insertMaterial(t){t.spaceGraph?ve.warn(`Material ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.materials,this.materialsById,this.materialsByType),this.registerNode(t),this.emit("material-create",t))}removeMaterial(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.materials,this.materialsById,this.materialsByType),this.unregisterNode(t),this.emit("material-delete",t)):ve.warn(`Material ${t.id} already in a detached state.`)}createMaterial(t,e,...i){let s;switch(t){case we:s=new _e(e,i[0],i[1]);break;case Pe:s=new Ee(e,i[0]);break;case Te:s=new Ae(e,i[0],i[1]);break;case Ie:s=new Se(e)}return this.insertMaterial(s),s}insertRelation(t){t.spaceGraph?ve.warn(`Relation ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.relations,this.relationsById,this.relationsByType),this.registerNode(t),this.emit("relation-create",t))}removeRelation(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.relations,this.relationsById,this.relationsByType),this.unregisterNode(t),this.emit("relation-delete",t)):ve.warn(`Relation ${t.id} already in a detached state.`)}createRelation(t,e){let i;if(t===$n)i=new jn(e);return this.insertRelation(i),i}insertCustomAttribute(t){t.spaceGraph?ve.warn(`Custom attribute ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.customAttributes,this.customAttributesById,this.customAttributesByType),this.registerNode(t),this.emit("custom-attribute-create",t))}removeCustomAttribute(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.customAttributes,this.customAttributesById,this.customAttributesByType),this.unregisterNode(t),this.emit("custom-attribute-delete",t)):ve.warn(`Custom attribute ${t.id} already in a detached state.`)}getId(){return Ut()}emit(t,...e){this.emitter.emit(t,...e)}on(t,e,i){this.emitter.on(t,e,i)}once(t,e,i){this.emitter.once(t,e,i)}off(t,e){this.emitter.off(t,e)}toJSON(){let t=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.products),e=function(t){let e=[];for(let i of t){let t=y(i);e.push(t)}return e}(this.geometries),i=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.materials),s=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.relations),r=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.customAttributes);return{schemaVersion:"0.24.6",spatialStructure:this.spatialStructure.toJSON(),sharedResources:{products:t,geometries:e,materials:i,relations:s,customAttributes:r}}}static fromJSON(t){const e=new So(t.schemaVersion);return Io(e,t),e}}function Co(t,e){let i=t.spatialGraph,s=new hs;for(let r of e.edges){let t=i.edgesById[r];if(!t)return void ve.warn(`Edge ${r} not found, skipping boundary.`);s.edges.push(t)}if(lr(s))return s}function Mo(t,e){let i=[];for(let s of e){let e=Co(t,s);if(!e)return;i.push(e)}return i}function Oo(t,e){let{id:i,position:s}=e,r=new bs(i,s[0],s[1]);return Ss(r,e),r}function No(t,e){let i=t.spatialGraph,s=e.vertices[0],r=e.vertices[1];if(s===r)return void ve.warn(`Same vertex referenced twice, skipping edge ${e.id}.`);let n=i.verticesById[s],o=i.verticesById[r];if(!n||!o)return void ve.warn(`One or both vertices not found, skipping edge ${e.id}.`);let a=new ks(e.id,n,o);return Ss(a,e),a}function Lo(t,e,i){i??(i=t.spaceGraph.customAttributesById);let s=Mo(t,e.boundaries);if(!s)return void ve.warn(`Invalid boundaries, skipping space ${e.id}.`);let r=new Us(e.id,s);return Ss(r,e),Cs(r,e,i),e.attributes&&r.setAttributes(e.attributes),r}function Ro(t,e){let i=eo(e.type,e.id);return Ss(i,e),i.setTransform(e.position,e.rotation??0),e.parameters&&i.setParameters(e.parameters),i}function Bo(t,e){let i=io(e.type,e.id);return Ss(i,e),e.parameters&&i.setParameters(e.parameters),i}const ko={};function Fo(t,e,i){return ko[t]||(ko[t]={}),ko[t][e]=i,i}const Do={.15:t=>{if(("layout:space"===t.type||"element:floor"===t.type||"element:ceiling"===t.type)&&t.id.includes(":")){const e=JSON.parse(JSON.stringify(t));return e.id=Ut(),e}return t},.16:t=>{if("element:window"===t.type&&t.parameters&&"framePosition"in t.parameters){const e=JSON.parse(JSON.stringify(t));return delete e.parameters.framePosition,e}return t},"0.20.3":t=>{if("layout:space"===t.type||!t.parameters)return t;let e=!1;const i=JSON.parse(JSON.stringify(t.parameters));if("height"in i&&i.height<.01&&(i.height=.01,e=!0),"width"in i&&i.width<.01&&(i.width=.01,e=!0),"length"in i&&i.length<.01&&(i.length=.01,e=!0),e){const e=JSON.parse(JSON.stringify(t));return e.parameters=i,e}return t}};function Uo(t,e){return!e||function(t,e){var i;if(void 0!==(null==(i=ko[t])?void 0:i[e]))return ko[t][e];const s=t.split(".").map(t=>parseInt(t)),r=e.split(".").map(t=>parseInt(t));for(let n=0;n<Math.max(s.length,r.length);n++){const i=s[n]||0,o=r[n]||0;if(i>o)return Fo(t,e,1);if(i<o)return Fo(t,e,-1)}return Fo(t,e,0)}(e,t)<0}function Go(t,e){let i=t;for(const s in Do)Uo(s,e)&&(i=Do[s](i));return i}function Xo(t,e){var i;let{position:s,rotation:r,rotationAxis:n}=e;if(t.setTransform(s??[0,0,0],r??0,n),e.parameters){let s=!!(null==(i=e.elements)?void 0:i.length);!function(t,e,i=!1){switch(t.type){case"element:ceiling":case"element:floor":case"element:boundaryWall":case"element:curtainWall":case"element:spaceDivider":case"element:wall":case"element:opening":case"element:asset":case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:ramp":case"element:roof":case"element:railing":case"element:slab":case"element:stairFlight":case"element:window":t.setParameters(e);break;case"element:kitchen":case"element:stairs":t.setParameters(e,i)}}(t,e.parameters,s)}"element:generic"!==e.type&&"element:asset"!==e.type||(t.geometries=e.geometries?JSON.parse(JSON.stringify(e.geometries)):[])}function Wo(t,e,i){i??(i=t.spaceGraph);let s,r=Go(e,null==i?void 0:i.sourceSchemaVersion);switch(r.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":s=function(t,e){let i=Mo(t,e.boundaries);if(!i)return void ve.warn(`Invalid boundaries, skipping boundary wall ${e.id}.`);let s=Zn(e.type,e.id,i);return e.parameters&&s.setParameters(e.parameters),s}(t,r);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":s=function(t,e){let i=[];if(i=Array.isArray(e.edge)?e.edge:[e.edge],!i.length)return void ve.warn(`Element ${e.id} references no edges and is skipped.`);let s=[];for(let n of i){let i=t.spatialGraph.edgesById[n];if(!i)return void ve.warn(`Edge ${e.edge} not found, skipping edge element ${e.id}.`);s.push(i)}let r=Zn(e.type,e.id,s);return e.parameters&&r.setParameters(e.parameters),r}(t,r);break;case"element:opening":s=function(t,e){let i=Zn("element:opening",e.id);return e.parameters&&i.setParameters(e.parameters),i}(0,r);break;case"element:asset":s=function(t,e,i){let s=Zn(e.type,e.id);if(Xo(s,e),!e.product)return e.geometries||ve.warn(`Element ${s.id} does not specify a 'geometries' field and does not reference a product.`),s;let r=t.spaceGraph??i;if(r){let t=r.nodesById[e.product];if(!t)return void ve.warn(`Product ${e.product} not found, skipping element ${e.id}.`);s.setProduct(t)}else ve.warn(`Layout not attached and space graph not passed as an argument, cannot find product ${e.product}.`);return s}(t,r,i);break;case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:kitchen":case"element:railing":case"element:ramp":case"element:roof":case"element:slab":case"element:stairFlight":case"element:stairs":case"element:window":s=function(t,e){let i=Zn(e.type,e.id);return Xo(i,e),i}(0,r);break;default:return void ve.warn(`Unknown element type '${r.type}', skipping element.`)}if(!s)return;Ss(s,r),Cs(s,r,null==i?void 0:i.customAttributesById);let n=r.elements??[];for(let o of n){let e=Wo(t,o,i);e&&s.insertElement(e)}return s}function Yo(t,e,i){Cs(t,e,i.customAttributesById),Ss(t,e),function(t,e){let i=t.spatialGraph,s=e.spatialGraph;for(let r of s.vertices){let t=Oo(0,r);i.insertVertex(t)}for(let r of s.edges){let e=No(t,r);e&&i.insertEdge(e)}}(t,e),function(t,e,i){for(let s of e.spaces){let e=Lo(t,Go(s),i.customAttributesById);e&&t.insertSpace(e)}}(t,e,i),function(t,e,i){for(let s of e.elements){let e=Wo(t,s,i);e&&t.insertElement(e)}}(t,e,i),function(t,e){let i=e.annotations??[];for(let s of i){let e=Ro(0,s);t.insertAnnotation(e)}}(t,e),function(t,e){let i=e.views??[];for(let s of i){let e=Bo(0,s);t.insertView(e)}}(t,e),function(t){const e=t.spatialGraph.edges;for(const s of e)s.spaces=[null,null],s.boundaryWalls=[null,null];const i=[];for(const s of t.spaces)Qs(s),i.push(nr(s));for(const s of e){if(null!==s.spaces[0]||null!==s.spaces[1])continue;const[e,r]=s.getPoints(),n=oi(e,r,.5);for(let o=0;o<t.spaces.length;o++)if(xi(n,i[o])){s.spaces[0]=t.spaces[o],s.spaces[1]=t.spaces[o];break}}for(const s of t.elements)"element:boundaryWall"===s.type&&tr(s)}(t)}const Ho="spatialStructure:layout";class $o extends zn{constructor(t){super(t,Ho),this.parent=null,this.spaces=[],this.spacesById={},this.elements=[],this.elementsById={},this.elementsByType=ro(no),this.annotations=[],this.annotationsById={},this.annotationsByType=ro(oo),this.views=[],this.viewsById={},this.viewsByType=ro(ao),this.debugIds=!1,this.suggestedIds={},this.spatialGraph=new xr(this),this.spatialIndex=new ho(this)}copyForClone(t){super.copyForClone(t),this.debugIds=t.debugIds,this.suggestedIds={...t.suggestedIds}}insertSpace(t){ws(this,t,this.spacesById,"Space")&&(!function(t,e){for(let i of t.elements)"element:ceiling"!==i.type&&"element:floor"!==i.type||ur(e.boundaries,i.boundaries)&&e.attachSlab(i)}(this,t),t.layout=this,this.spaces.push(t),this.spacesById[t.id]=t,t.boundaries.length&&(this.spatialGraph.graphChanged=!0),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("space-create",t)))}removeSpace(t){let e=this.spaces.indexOf(t);if(-1!==e){if(function(t){let e=t.slabs.slice();for(let i of e)t.detachSlab(i);for(let i of t.boundaries)for(let e of i.edges)e.spaces[0]===t&&(e.spaces[0]=null),e.spaces[1]===t&&(e.spaces[1]=null)}(t),this.spaces.splice(e,1),this.spacesById[t.id]===t)return delete this.spacesById[t.id],this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("space-delete",t)),t.layout=null,t;ve.error(`Entry ${t.id} in 'spaces stored by ID' record does not contain this object.`)}else ve.warn(`Space ${t.id} not found.`)}createSpace(t,e){let i=new Us(t,e);return this.insertSpace(i),i}insertElement(t){ws(this,t,this.elementsById,"Element",!0)&&(!function(t,e){switch(e.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":ir(t,e);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":sr(t,e)}}(this,t),this.elements.push(t),_s(this,t))}removeElement(t){if(t.layout!==this)return void ve.warn(`Element ${t.id} not part of layout ${this.id}.`);if(t.parent)return void ve.warn(`Element ${t.id} not a root element, cannot remove from layout.`);rr(t);let e=this.elements.indexOf(t);if(-1!==e)return this.elements.splice(e,1),Ps(this,t,null),t;ve.warn(`Element ${t.id} not found.`)}createElement(t,e,...i){let s=Zn(t,e,...i);return this.insertElement(s),s}insertNode(t){let{nodes:e,nodesById:i,nodesByType:s}=vr(this,t);t.layout=this,e.push(t),i[t.id]=t,s[t.type]||(s[t.type]=[]),s[t.type].push(t)}removeNode(t){let{name:e,nodes:i,nodesById:s,nodesByType:r}=vr(this,t),n=i.indexOf(t);if(-1===n)return void ve.warn(`Node ${t.id} not found in '${e}' list.`);if(i.splice(n,1),s[t.id]!==t)return void ve.error(`Entry ${t.id} in '${e} stored by ID' record does not contain this object.`);delete s[t.id];let o=r[t.type],a=null==o?void 0:o.indexOf(t);o&&-1!==a?r[t.type].splice(a,1):ve.error(`Node ${t.id} not found in '${e} stored by type' record.`)}insertAnnotation(t){ws(this,t,this.annotationsById,"Annotation")&&(this.insertNode(t),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("annotation-create",t)))}removeAnnotation(t){return this.removeNode(t),this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("annotation-delete",t)),t.layout=null,t}createAnnotation(t,e){let i=eo(t,e);return this.insertAnnotation(i),i}insertView(t){ws(this,t,this.viewsById,"View")&&(this.insertNode(t),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("view-create",t)))}removeView(t){return this.removeNode(t),this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("view-delete",t)),t.layout=null,t}createView(t,e){let i=io(t,e);return this.insertView(i),i}clearSpaces(){let t=[...this.spaces];for(let e of t)this.removeSpace(e)}getElementList(){return Object.values(this.elementsById)}getArea(t={program:{exclude:["void"]}}){var e,i;let s=(null==(e=null==t?void 0:t.program)?void 0:e.include)??[],r=(null==(i=null==t?void 0:t.program)?void 0:i.exclude)??[];if(s.length&&r.length)return ve.warn("Cannot use 'include' and 'exclude' filters at the same time, skipping area calculation."),0;let n=0;for(let o of this.spaces){let t=!1;s.length&&(t=s.includes(o.attributes.program)),r.length&&(t=r.includes(o.attributes.program)),t||(n+=o.getArea())}return n}getLayoutGraph(){var t;let e=new so,i=this.elementsByType["element:spaceDivider"].slice();for(let s of this.elementsByType["element:opening"])"element:window"!==(null==(t=s.elements[0])?void 0:t.type)&&i.push(s);for(let s of i)for(let t of s.getSpaces())t&&e.addEdge("graph:connectedTo",t,s);for(let s of this.spatialGraph.edges)s.spaces[0]&&s.spaces[1]&&e.addEdge("graph:adjacentTo",s.spaces[0],s.spaces[1]);return e}getUniqueId(t,e){let i=0,s=t+i++;for(;this.suggestedIds[s]||e[s];)s=t+i++;return this.suggestedIds[s]=!0,s}getSpaceId(t){let e;return t=t??"space-",e=this.debugIds?this.getUniqueId(t,this.spacesById):Ut(),e}getElementId(t,e){let i;return e=e??t.type.split(":")[1]+"-",i=this.debugIds?this.getUniqueId(e,this.elementsById):Ut(),i}getBoundingBox(){const t={position:[0,0,0],rotation:0,rotationAxis:[0,1,0]};if(0===this.spaces.length&&0===this.elements.length)return{min:[0,0,0],max:[0,0,0],transform:t};const e=[];for(const r of this.spaces){const{min:t,max:i}=r.getAxisAlignedBoundingBox();e.push(t,i)}for(const r of this.getElementList()){const{min:t,max:i}=r.getAxisAlignedBoundingBox();e.push(t,i)}const{min:i,max:s}=as(e.flat());return{min:i,max:s,transform:t}}toJSON(){let t=this.spatialGraph.toJSON(),e=function(t){let e=[];for(let i of t.spaces){let t=i.toJSON();e.push(t)}return e}(this),i=function(t){let e=[];for(let i of t.elements){let t=i.toJSON();t&&e.push(t)}return e}(this),s=function(t){let e=[];for(let i of t.annotations){let t=i.toJSON();e.push(t)}return e}(this),r=function(t){let e=[];for(let i of t.views){let t=i.toJSON();e.push(t)}return e}(this);return{...super.toJSON(),spatialGraph:t,spaces:e,elements:i,annotations:s,views:r}}static fromJSON(t,e){const i=(null==e?void 0:e.spaceGraph)??new So,s=new $o(t.id);return Yo(s,t,i),(null==e?void 0:e.skipInsert)||i.insertSpatialStructure(s),s}}const jo="spatialStructure:floor";class zo extends zn{constructor(t){super(t,jo),this.parent=null,this.position=[0,0,0],this.rotation=0,this.level=null,this.layouts=[]}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation}setPosition(t){this.position=[...t],this.emit("floor-transform-change",this)}setRotation(t){this.rotation=t,this.emit("floor-transform-change",this)}setTransform(t,e){this.position=[...t],this.rotation=e,this.emit("floor-transform-change",this)}insertLayout(t){t.parent?ve.warn(`SpaceGraphLayout ${t.id} already part of floor ${t.parent.id}.`):(t.parent=this,this.layouts.push(t),this.spaceGraph&&Vn(t,this.spaceGraph))}removeLayout(t){-1!==this.layouts.indexOf(t)?(this.spaceGraph&&qn(t,this.spaceGraph),t.parent=null):ve.warn(`Floor ${t.id} not found.`)}createLayout(t){let e=new $o(t);return this.insertLayout(e),e}toJSON(){const t={...super.toJSON(),position:[...this.position],rotation:this.rotation,layouts:[]};null!==this.level&&(t.level=this.level);for(let e of this.layouts){let i=e.toJSON();t.layouts.push(i)}return t}static fromJSON(t,e){const i=(null==e?void 0:e.spaceGraph)??new So,s=new zo(t.id);xo(s,t),Cs(s,t,i.customAttributesById),s.position=[...t.position],s.rotation=t.rotation,void 0!==t.level&&(s.level=t.level);for(const r of t.layouts){const t=$o.fromJSON(r,{spaceGraph:i,skipInsert:!0});s.insertLayout(t)}return(null==e?void 0:e.skipInsert)||i.insertSpatialStructure(s),s}}const Vo="spatialStructure:building";class qo extends zn{constructor(t){super(t,Vo),this.floors=[],this.floorsByLevel={},this.location={latLong:[0,0],rotation:0}}copyForClone(t){super.copyForClone(t),this.location=JSON.parse(JSON.stringify(t.location))}getLevelOrder(){const t=Object.keys(this.floorsByLevel);return t.length?t.sort((t,e)=>{var i,s;return(null==(i=this.floorsByLevel[t][0])?void 0:i.position[1])-(null==(s=this.floorsByLevel[e][0])?void 0:s.position[1])}):[]}insertFloor(t){var e,i;t.parent?ve.warn(`Floor ${t.id} already part of building ${t.parent.id}.`):(t.parent=this,t.level&&((e=this.floorsByLevel)[i=t.level]??(e[i]=[]),this.floorsByLevel[t.level].push(t)),this.floors.push(t),this.spaceGraph&&Jn(t,this.spaceGraph))}removeFloor(t){let e=this.floors.indexOf(t);if(-1!==e){if(t.level&&this.floorsByLevel[t.level]){let e=this.floorsByLevel[t.level].indexOf(t);this.floorsByLevel[t.level].splice(e,1),this.floorsByLevel[t.level].length||delete this.floorsByLevel[t.level]}this.floors.splice(e,1),this.spaceGraph&&Kn(t,this.spaceGraph),t.parent=null}else ve.warn(`Floor ${t.id} not found.`)}createFloor(t){let e=new zo(t);return this.insertFloor(e),e}toJSON(){let t={...super.toJSON(),floors:[]},e=this.location;e.latLong[0]&&e.latLong[1]&&e.rotation&&(t.location={latLong:[...e.latLong],rotation:e.rotation});for(let i of this.floors){let e=i.toJSON();t.floors.push(e)}return t}static fromJSON(t,e){const i=e.spaceGraph??new So,s=new qo(t.id);xo(s,t),Cs(s,t,i.customAttributesById),t.location&&(s.location=JSON.parse(JSON.stringify(s.location)));for(const r of t.floors){const t=zo.fromJSON(r,{spaceGraph:i,skipInsert:!0});s.insertFloor(t)}return e.skipInsert||i.insertSpatialStructure(s),s}}function Jo(t,e,i,s){const r=1e-7*1e-7;let n=[e[0]-t[0],e[1]-t[1]],o=[s[0]-i[0],s[1]-i[1]],a=i[0]-t[0],l=i[1]-t[1],h=n[0]*o[1]-n[1]*o[0],u=h*h,c=n[0]*n[0]+n[1]*n[1];if(u>r*c*(o[0]*o[0]+o[1]*o[1])){let e=(a*o[1]-l*o[0])/h,i=(a*n[1]-l*n[0])/h;return{tag:2,intersect:!0,p:[t[0]+e*n[0],t[1]+e*n[1]],u:e,v:i}}return h=a*n[1]-l*n[0],u=h*h,u>r*c*(a*a+l*l)?{tag:0,intersect:!1}:{tag:1,intersect:!0}}function Ko(t,e,i,s){const r=[e[0]-t[0],e[1]-t[1]],n=[s[0]-i[0],s[1]-i[1]],o=i[0]-t[0],a=i[1]-t[1];let l=r[0]*n[1]-r[1]*n[0],h=l*l;const u=r[0]*r[0]+r[1]*r[1];let c,d,p,f;if(h>1e-14*u*(n[0]*n[0]+n[1]*n[1])){const e=(o*n[1]-a*n[0])/l;if(e<0||e>1)return{tag:0,intersect:!1};{const i=(o*r[1]-a*r[0])/l;return i<0||i>1?{tag:0,intersect:!1}:(c=t[0]+e*r[0],d=t[1]+e*r[1],{tag:1,intersect:!0,p:[c,d],u:e,v:i})}}if(l=o*r[1]-a*r[0],h=l*l,h>1e-14*u*(o*o+a*a))return{tag:2,intersect:!1};{const e=(r[0]*o+r[1]*a)/u,i=e+(r[0]*n[0]+r[1]*n[1])/u;let s,l;e<i?(s=e,l=i):(s=i,l=e);const h=function(t,e,i,s){if(e<i||t>s)return{tag:0,intersect:!1};if(t===i&&e===s)return{tag:1,intersect:!0};if(e>i)return e<s?{tag:3,intersect:!0,w0:t<i?i:t,w1:e>s?s:e}:{tag:2,intersect:!0,w:t};return{tag:2,intersect:!0,w:e}}(0,1,s,l);switch(h.tag){case 0:return{tag:3,intersect:!1};case 1:return{tag:4,intersect:!0};case 2:{const e=h.w;return c=t[0]+e*r[0],d=t[1]+e*r[1],{tag:5,intersect:!0,p:[c,d],u:e}}case 3:{const e=h.w0,i=h.w1;return c=t[0]+e*r[0],d=t[1]+e*r[1],p=t[0]+i*r[0],f=t[1]+i*r[1],{tag:6,intersect:!0,p:[c,d],q:[p,f],u0:e,u1:i}}default:throw new Error("Unknown tag value.")}}}function Zo(...t){}function Qo(t,e,i,s){let r=t[0],n=t[1];for(let o=1;o<e.length-1;o++){let a=e[o];if(bi(a,r,n)<1e-7)return i?t[0]=a:t[1]=a,void(s?e.splice(0,o):e.splice(o+1))}}function ta(t){let e=0;for(;e<t.length-2;){let i=t[e],s=t[e+2];bi(t[e+1],i,s)<1e-7?t.splice(e+1,1):e++}}function ea(t){if(t.length<3)return!1;let e=t.slice();e.push(t[0]);for(let i=0;i<e.length-2;i++){let t=e[i],s=e[i+1];for(let r=i+1;r<e.length-1;r++){const i=1e-7;let n=Ko(t,s,e[r],e[r+1]);if(1===n.tag&&n.u>i&&n.u<1-i)return!0}}return!1}function ia(t,e){return{position:[t,e],edges:[],geometry:{parameters:{joinStyle:{type:"miter",parameters:{distance:.05}}}}}}function sa(t,e){let i={indices:[t,e],faces:[-1,-1],geometry:{tangible:!0,skipped:!1,parameters:{width:.15,height:2.5,offset:0},fragments:[],computed:{valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}},openings:[]};return i.geometry.fragments=[{edge:i,angle:0,points:[],joinPoints:[],sidePoints:[]},{edge:i,angle:0,points:[],joinPoints:[],sidePoints:[]}],i}const ra="intersectCap",na="intersectCap";function oa(...t){}function aa(t){let e=t.toFixed(3),i=parseFloat(e);return e+=t>i?"+":t<i?"-":" ",t>=0&&(e=" "+e),e}function la(t){if(t.length>0)for(let e=0;e<t.length;e++){let i=t[e];oa((i[0],i[1]))}}function ha(t,e){for(let i of e)if(t.length>0){let e=t[0],s=t[t.length-1],r=ri(ui(i,e)),n=ri(ui(i,s));r>1e-7&&n>1e-7&&t.push(i)}else t.push(i)}function ua(t,e,i,s,r){0===t.joinPoints.length?(ha(t.joinPoints,[...s,i]),ha(t.sidePoints[0],r)):(ha(t.joinPoints,s),ha(t.sidePoints[1],r.slice().reverse())),la(t.joinPoints),la(t.sidePoints[0]),la(t.sidePoints[1])}function ca(t,e,i,s,r){ua(t,0,i,[s],[s]),ua(e,0,i,[r],[r]),t.edge.geometry.computed.skipped=!0,e.edge.geometry.computed.skipped=!0}function da(t,e,i,s){ua(t,0,i,[s],[s]),ua(e,0,i,[s],[s])}function pa(t,e,i,s,r){ua(t,0,i,[s],[s]),ua(e,0,i,[r],[r])}function fa(t,e,i,s,r,n,o,a,l,h,u){if("ignore"===u)ca(t,e,i,r,a);else{let u;if(u=h?Jo(s,r,l,a):Jo(n,r,o,a),2!==u.tag)return ve.warn("Edge side line does not intersect edge cap line, ignoring result."),void ca(t,e,i,r,a);let c=u.p;h?(ua(t,0,i,[c],[c]),ua(e,0,i,[a,c],[a])):(ua(t,0,i,[r,c],[r]),ua(e,0,i,[c],[c]))}}function ma(t,e,i,s,r,n,o,a,l,h,u,c){t.edge.id,e.edge.id;let d=Jo(s,r,a,l);if(2!==d.tag)return ve.warn("Edge side lines do not intersect, ignoring result.",d),void ca(t,e,i,r,l);let p=ri(ui(r,s)),f=ri(ui(l,a)),m=Math.max(0,1-.2/p),g=Math.max(0,1-.2/f),{p:y,u:v,v:x}=d,b="",w="";if(v>=.9999999)if(o)if(x>=.9999999){const s=1;if(ri(ui(y,i))>s){let s,n=Jo(y,i,r,l);2!==n.tag?(ve.warn("Bevel construction failed, using center point.",n),s=oi(r,l,.5)):s=n.p,ua(t,0,i,[s],[r,s]),ua(e,0,i,[s],[l,s])}else da(t,e,i,y)}else if(x>=g)da(t,e,i,y);else{let c=o&&u?ra:"ignore";fa(t,e,i,s,r,n,a,l,h,!0,c),w="ignore"===c?"* (ignore)":"* (intersectCap)"}else ca(t,e,i,r,l);else if(x>=.9999999)if(u)if(v>=m)da(t,e,i,y);else{let c=o&&u?ra:"ignore";fa(t,e,i,s,r,n,a,l,h,!1,c),b="ignore"===c?"* (ignore)":"* (intersectCap)"}else ca(t,e,i,r,l);else ve.warn("Edge side line segments cross, ignoring result."),ca(t,e,i,r,l);aa(v),m.toFixed(3),aa(x),g.toFixed(3)}function ga(t,e,i,s,r,n,o,a,l,h,u,c){t.edge.id,e.edge.id;let d=Jo(s,r,a,l);if(2!==d.tag)return ve.warn("Edge side lines do not intersect, ignoring result.",d),void ca(t,e,i,r,l);let p=ri(ui(r,s)),f=ri(ui(l,a)),m=Math.max(0,1-1/p),g=Math.max(0,1-1/f),{p:y,u:v,v:x}=d,b="",w="";if(v>=0&&v<=1+1e-7&&x>=0&&x<=1+1e-7)da(t,e,i,y);else if(v>1&&x>1)ve.warn("Edge side line segments do not cross, ignoring result."),ca(t,e,i,r,l);else if(v>1)if(x>=g)da(t,e,i,y);else{let c=o&&u?na:"ignore";fa(t,e,i,s,r,n,a,l,h,!1,c),w="ignore"===c?"* (ignore)":"* (intersectCap)"}else if(x>1)if(v>=m)da(t,e,i,y);else{let c=o&&u?na:"ignore";fa(t,e,i,s,r,n,a,l,h,!0,c),b="ignore"===c?"* (ignore)":"* (intersectCap)"}else ca(t,e,i,r,l);aa(v),m.toFixed(3),aa(x),g.toFixed(3)}function ya(t,e){let i,s,r,n=e[0];n.indices[0]===t?(i=n.geometry.fragments[0],s=i.points[0],r=i.points[1]):(i=n.geometry.fragments[1],s=i.points[1],r=i.points[0]),i.joinPoints.push(s,r),i.sidePoints[0].push(s),i.sidePoints[1].push(r)}function va(t,e,i){for(let s=0;s<e.length;s++){let r,n,o,a,l,h,u,c,d,p,f,m,g=e[s],y=s<e.length-1?e[s+1]:e[0],v=!g.geometry.skipped&&0!==g.geometry.parameters.width,x=!y.geometry.skipped&&0!==y.geometry.parameters.width;if(!v&&!x)continue;g.indices[0]===t?(r=g.geometry.fragments[0],n=g.geometry.fragments[1],o=n.points[0],a=r.points[0],l=r.points[1],h=i[g.indices[1]].position):(r=g.geometry.fragments[1],n=g.geometry.fragments[0],o=n.points[1],a=r.points[1],l=r.points[0],h=i[g.indices[0]].position),y.indices[0]===t?(u=y.geometry.fragments[0],c=y.geometry.fragments[1],d=c.points[1],p=u.points[1],f=u.points[0],m=i[y.indices[1]].position):(u=y.geometry.fragments[1],c=y.geometry.fragments[0],d=c.points[0],p=u.points[0],f=u.points[1],m=i[y.indices[0]].position);let b=i[t].position;const w=.01;let _=yi(o,a,d,p);if(_<w||_>Math.PI-w)pa(r,u,b,a,p);else{1===mi(h,b,m)?ma(r,u,b,o,a,l,v,d,p,f,x):ga(r,u,b,o,a,l,v,d,p,f,x)}}}function xa(t){let e=t.geometry;e.fragments[0].joinPoints=[],e.fragments[0].sidePoints[0]=[],e.fragments[0].sidePoints[1]=[],e.fragments[1].joinPoints=[],e.fragments[1].sidePoints[0]=[],e.fragments[1].sidePoints[1]=[],e.computed={valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}}function ba(t,e){let i=function(t){let e={};for(let i of t){let t=i.indices[0],s=i.indices[1],r=Math.min(t,s),n=Math.max(t,s);e[r.toString()+"_"+n.toString()]=i}return e}(e),s=[];for(let n of e){if(!n.geometry.tangible||n.geometry.skipped)continue;let t=n.indices[0],e=n.indices[1];s[t]=!0,s[e]=!0,xa(n)}let{vertices:r}=t;for(let n=0;n<r.length;n++){if(!s[n])continue;let t=[],e=r[n];for(let s of e.edges){if(!s.geometry.tangible||s.geometry.skipped)continue;let e=s.indices[0],r=s.indices[1],n=Math.min(e,r),o=Math.max(e,r);i[n.toString()+"_"+o.toString()]&&t.push(s)}oa(t.length),1===t.length?ya(n,t):va(n,t,r)}}function wa(t,e){let i=e.element;if(i?t.geometry.tangible="element:spaceDivider"!==i.type:e.boundaryWalls[0]||e.boundaryWalls[1]?t.geometry.tangible=!0:t.geometry.tangible=!1,i&&"element:wall"===i.type){let{width:e,height:s,offset:r}=i.parameters;t.geometry.parameters={width:e,height:s,offset:r}}else t.geometry.parameters={width:0,height:0,offset:0}}function _a(t,e){let i=[],s={};for(let a of e)for(let t of a.vertices)if(void 0===s[t.id]){let e=ia(t.position[0],t.position[1]);e.reference=t,s[t.id]=i.push(e)-1}let r=[],n={};for(let a of e){let t=a.vertices[0],e=a.vertices[1],i=sa(s[t.id],s[e.id]);wa(i,a),i.id=a.id,i.reference=a,r.push(i),n[a.id]=!0}let o=function(t,e){return{vertices:t,edges:e,cycles:[],faces:[]}}(i,r);return function(t){let{vertices:e,edges:i}=t;for(let s of e)s.edges=[];for(let s of i){let t=s.indices[0],i=s.indices[1];e[t].edges.push(s),e[i].edges.push(s)}}(o),function(t){let{vertices:e}=t;for(let i=0;i<e.length;i++){let t=e[i],s=t.edges,r=[];for(let n of s){let s=e[i===n.indices[0]?n.indices[1]:n.indices[0]],o={edge:n,angle:ei([s.position[0]-t.position[0],s.position[1]-t.position[1]]),points:[],joinPoints:[],sidePoints:[[],[]]},a={edge:n,fragment:o};i===n.indices[0]?n.geometry.fragments[0]=o:n.geometry.fragments[1]=o,r.push(a)}r.sort((t,e)=>t.fragment.angle-e.fragment.angle),t.edges=r.map(t=>t.edge)}}(o),o}function Pa(t){const e=t.map(t=>t.geometry.computed),i=function(t){var e;if(0===t.length)return[];const i={};for(const l of t)for(const t of l.indices)i[t]??(i[t]=[]),i[t].push(l);let s=(null==(e=Object.entries(i).find(([,t])=>1===t.length))?void 0:e[0])||Object.keys(i)[0];const r=[],n=/* @__PURE__ */new Set;let o=parseInt(s),a=i[o][0];for(;r.length<t.length;){if(n.has(a)){if(a=t.find(t=>!n.has(t)),!a)break;o=a.indices[0];continue}const e=a.indices[0]!==o;r.push({edge:a,reverse:e}),n.add(a);const s=e?a.indices[0]:a.indices[1],l=i[s].find(t=>!n.has(t));if(l)o=s,a=l;else{if(a=t.find(t=>!n.has(t)),!a)break;o=a.indices[0]}}return r}(t),s=t[0].geometry.computed;let r=s.valid;const n=i[0].reverse,o=i[0].edge.geometry.computed,a=i[i.length-1].reverse,l=i[i.length-1].edge.geometry.computed,h=n?o.joinPoints2:o.joinPoints1,u=a?l.joinPoints1:l.joinPoints2,c=[],d=[];for(const{edge:m,reverse:g}of i){const{computed:t}=m.geometry;g?(c.unshift(...t.sidePoints2),d.push(...t.sidePoints1)):(c.unshift(...t.sidePoints1),d.push(...t.sidePoints2))}const p=Y(e.map(t=>t.points));let f=[];if(1===p.length)f=p[0];else if(p.length>1){const t=$(p,.001,void 0,!0);t.length>0&&(f=t[0])}return 0===f.length&&(ve.warn(`Empty wall geometry after merging edge profiles: ${t.map(t=>t.id).join(", ")}`),r=!1),{valid:r,skipped:s.skipped,selfIntersecting:s.selfIntersecting,sidePoints1:c.slice(),sidePoints2:d.slice(),joinPoints1:h.slice(),joinPoints2:u.slice(),points:f}}function Ea(t,e){zs(t,e),e.emit("geometry-profile-update",e);for(let i of e.slabs)i.emit("geometry-profile-update",i)}function Ta(t){let e=function(t){let e=/* @__PURE__ */new Map;for(let i of t)for(let t of i.boundaryWalls)t&&e.set(t.id,t);return[...e.values()]}(t);for(let i of e)Mr(i)}function Aa(t){let e=t.spatialGraph.edges,i=_a(0,e);!function(t){let{vertices:e,edges:i}=t;for(let s of i){let{geometry:t}=s,i=s.indices[0],r=s.indices[1],n=t.parameters.width,o=t.parameters.offset,a=e[i].position,l=e[r].position,h=ui(l,a);if(t.skipped=ri(h)<1e-7,!t.skipped){let e=li(ai(h)),i=hi(e,.5*n+o),s=hi(e,-.5*n+o),r=ti(a,i),u=ti(a,s),c=ti(l,i),d=ti(l,s);t.fragments[0].points=[r,u],t.fragments[1].points=[c,d]}}}(i),ba(i,i.edges),function(t,e){for(let i of e){let{geometry:t}=i;if(!t.tangible||t.skipped||0===t.parameters.width)continue;let e=t.fragments[0],s=t.fragments[1],r=[...e.joinPoints],n=[...s.joinPoints],o=[...e.sidePoints[0]],a=[...e.sidePoints[1]],l=[...s.sidePoints[0]],h=[...s.sidePoints[1]],u=Jo(r[0],n[n.length-1],r[r.length-1],n[0]);2===u.tag&&u.u>0&&u.u<1&&u.v>0&&u.v<1&&(n.reverse(),l.reverse(),h.reverse(),[l,h]=[h,l]);let c=h.concat(o),d=a.concat(l);2===c.length&&2===d.length&&(Qo(c,r,!1,!0),Qo(c,n,!0,!1),Qo(d,r,!0,!1),Qo(d,n,!1,!0)),ta(c),ta(r),ta(d),ta(n),1===mi(c[0],c[c.length-1],d[0])&&(c.reverse(),d.reverse(),r.reverse(),n.reverse(),[c,d]=[d,c]);let p=c.slice(0,c.length-1),f=r.slice(0,r.length-1),m=d.slice(0,d.length-1),g=n.slice(0,n.length-1),y=tt(p.concat(f).concat(m).concat(g),.001),v=i.geometry.computed;v.sidePoints1=c,v.sidePoints2=d,v.joinPoints1=r,v.joinPoints2=n,v.points=y,v.selfIntersecting=ea(v.points),v.valid=v.points.length>=3&&!v.skipped&&!v.selfIntersecting,Zo(i.id),Zo(v.valid),Zo(v.skipped),Zo(v.selfIntersecting)}}(0,i.edges),function(t){var e;let i={};for(let s of t.edges){let t=s.reference.element;if("element:wall"===(null==t?void 0:t.type)){let r=s.geometry.computed;1===t.getEdges().length?(t.geometryProfile={valid:r.valid,skipped:r.skipped,selfIntersecting:r.selfIntersecting,sidePoints1:r.sidePoints1.slice(),sidePoints2:r.sidePoints2.slice(),joinPoints1:r.joinPoints1.slice(),joinPoints2:r.joinPoints2.slice(),points:r.points.slice()},t.emit("geometry-profile-update",t)):(i[e=t.id]??(i[e]=[]),i[t.id].push(s),i[t.id].length===t.getEdges().length&&(t.geometryProfile=Pa(i[t.id]),t.emit("geometry-profile-update",t)))}}}(i),function(t){var e;for(let i of t)"element:wall"===(null==(e=i.element)?void 0:e.type)&&Rr(i.element)}(e),Ta(e)}function Ia(t){Aa(t),function(t){let e=t.spaces;for(let i of e){Ea(t,i);for(let t of i.slabs)Zs(t)}}(t)}function Sa(t){return new Promise((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error)})}function Ca(t,e){let i;return(s,r)=>(()=>{if(i)return i;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),i=Sa(s),i.then(t=>{t.onclose=()=>i=void 0},()=>{}),i})().then(t=>r(t.transaction(e,s).objectStore(e)))}let Ma;function Oa(){return Ma||(Ma=Ca("keyval-store","keyval")),Ma}const Na=["eq","neq","gt","gte","lt","lte","in","nin","contains","null"],La=t=>{var e;return Yn(t)?null==(e=t.geometry)?void 0:e.polygons:"element:wall"===t.type?[t.geometryProfile.points]:"getBoundingBoxContour"in t?[t.getBoundingBoxContour()]:[]},Ra=(t,e)=>{var i,s;switch(e){case"localBoundingBox":{const{min:e,max:i}=t.getBoundingBox();return{min:e,max:i}}case"boundingBox":{const{min:e,max:i}="axisAlignedBoundingBox"in t?t.getAxisAlignedBoundingBox():t.getBoundingBox();return{min:e,max:i}}case"dimensions":{const e=t.getBoundingBox();return{length:e.max[0]-e.min[0],width:e.max[2]-e.min[2],height:e.max[1]-e.min[1]}}case"boundingBoxContour":return"getBoundingBoxContour"in t?t.getBoundingBoxContour():void 0;case"polygons":case"contour":return La(t);case"area":return Yn(t)?t.getArea():void 0;case"position":case"rotation":if("getWorldTransform"in t){return t.getWorldTransform()[e]}return;case"transform":if("getWorldTransform"in t){const{position:e,rotation:i}=t.getWorldTransform();return{position:e,rotation:i}}return;case"localTransform":if("getTransform"in t){const{position:e,rotation:i}=t.getTransform();return{position:e,rotation:i}}return;case"labelPoint":return Pi(La(t));case"category":return Yn(t)?t.attributes.program:Hn(t)?t.attributes.categories[0]:"product"in t?null==(i=t.product)?void 0:i.attributes.categories[0]:void 0;case"subCategory":return Yn(t)?t.attributes.usage:Hn(t)?t.attributes.subCategories[0]:"product"in t?null==(s=t.product)?void 0:s.attributes.subCategories[0]:void 0;case"seatCapacity":if(Yn(t)){return t.getElements("element:asset").reduce((t,e)=>{var i,s;return t+((null==(s=null==(i=e.product)?void 0:i.attributes)?void 0:s.seatCapacity)||0)},0)}return Hn(t)?t.attributes.seatCapacity||0:void 0;default:return}},Ba=(t,e)=>{switch(e){case"spaceGraph":case"layout":case"rotationAxis":return;default:{const i=t[e];return"function"!=typeof i?i:void 0}}},ka={id:!0,type:!0,name:!0,category:!0,subCategory:!0,dimensions:!0,boundingBox:!0},Fa={id:!0,type:!0},Da=/* @__PURE__ */new Set(["elements","parent"]);function Ua(t,e,i=0){if(!t||"object"!=typeof t)return t;const s={};for(const[r,n]of Object.entries(e)){if(Da.has(r)&&i>=3)continue;const e=Da.has(r)?i+1:i;if(!0===n||void 0===n)if("elements"!==r||Hn(t))if("parent"===r&&"parent"in t&&t.parent&&Wn(t))s[r]=Ua(t.parent,Fa,e);else if("product"===r&&"product"in t&&t.product)s[r]=Ua(t.product,ka,i);else{const e=Ra(t,r);if(void 0!==e)s[r]=e;else{const e=Ba(t,r);void 0!==e&&(s[r]=e)}}else{const i=Yn(t)?t.getElements():t.elements;s[r]=$a(i,{},e)}else if("object"==typeof n)if("elements"!==r||Hn(t)){const i=t[r];if(Array.isArray(i))s[r]=i.map(t=>Ua(t,n,e));else if(i&&"object"==typeof i)s[r]=Ua(i,n,e);else{const i=Ra(t,r);null!=i&&(s[r]=Ua(i,n,e))}}else{const i=Yn(t)?t.getElements():t.elements,o={select:n.select||Fa,where:n.where};s[r]=$a(i,o,e)}}return s}const Ga=t=>null!=t&&"object"==typeof t&&!Array.isArray(t)&&Na.some(e=>e in t);function Xa(t,e){for(const[i,s]of Object.entries(e)){const e=t[i];if(null!=s)if("object"!=typeof s||Array.isArray(s)){if(e!==s)return!1}else if(Ga(s)){if(!Wa(e,s))return!1}else if(!e||"object"!=typeof e||!Xa(e,s))return!1}return!0}function Wa(t,e){if("eq"in e&&t!==e.eq)return!1;if("ne"in e&&t===e.ne)return!1;if("gt"in e&&!("number"==typeof t&&"number"==typeof e.gt&&t>e.gt))return!1;if("gte"in e&&!("number"==typeof t&&"number"==typeof e.gte&&t>=e.gte))return!1;if("lt"in e&&!("number"==typeof t&&"number"==typeof e.lt&&t<e.lt))return!1;if("lte"in e&&!("number"==typeof t&&"number"==typeof e.lte&&t<=e.lte))return!1;if("in"in e&&Array.isArray(e.in)&&!e.in.includes(t))return!1;if("nin"in e&&Array.isArray(e.nin)&&e.nin.includes(t))return!1;if("contains"in e&&("string"!=typeof t||"string"!=typeof e.contains||!t.toLowerCase().includes(e.contains.toLowerCase())))return!1;if("null"in e){const i=null==t;if(e.null!==i)return!1}return!0}function Ya(t,e){if(!e)return t;const i=JSON.parse(JSON.stringify(t)),s=t=>"object"==typeof t&&null!==t;return function t(e,i){for(const r in i)if(e[r]){if(!0===e[r])continue;s(i[r])&&s(e[r])&&t(e[r],i[r])}else s(i[r])&&!Ga(i[r])?(e[r]={},t(e[r],i[r])):e[r]=!0}(i,e),i}function Ha(t,e){if(!e||!0===e)return t;const i={};for(const[s,r]of Object.entries(e))if(s in t)if(!0===r)i[s]=t[s];else if("object"==typeof r&&t[s])if(r&&("select"in r||"where"in r))i[s]=t[s];else if(Array.isArray(t[s])){const e=t[s];i[s]=e.map(t=>"object"==typeof t&&null!==t?Ha(t,r):t)}else"object"==typeof t[s]&&null!==t[s]&&(i[s]=Ha(t[s],r));return i}function $a(t,e,i=0){const s=(null==e?void 0:e.select)||Fa,r=Ya(s,null==e?void 0:e.where),n=[];for(const o of t){const t=Ua(o,r,i);n.push(t)}return((null==e?void 0:e.where)?n.filter(t=>Xa(t,e.where)):n).map(t=>Ha(t,s))}function ja(t){const{at:e,within:i,...s}=t;return{spatial:{at:e,within:i},nonSpatial:s}}function za(t,e,i){var s,r;if(!(null==(s=null==i?void 0:i.where)?void 0:s.at)&&!(null==(r=null==i?void 0:i.where)?void 0:r.within))return{items:t,args:i};const{spatial:n,nonSpatial:o}=ja(i.where),a=function(t,e,i){const{at:s,within:r}=i;if(!s&&!r)return t;const n=s?{min:s}:{min:r.min,max:r.max},o=e.spatialIndex.find(n),a=new Set(o.map(t=>t.id));return t.filter(t=>a.has(t.id))}(t,e,n),l=Object.keys(o).length>0?o:void 0;return{items:a,args:{...i,where:l}}}function Va(t,e){var i;const s=t.elementsById[e.id]||t.spacesById[e.id]||(null==(i=t.spaceGraph)?void 0:i.productsById[e.id]);if(!s)return!1;let r=e.where;if(e.where.at||e.where.within){const{spatial:i,nonSpatial:s}=ja(e.where),n=i.at?{min:i.at}:{min:i.within.min,max:i.within.max};if(!t.spatialIndex.find(n).some(t=>t.id===e.id))return!1;r=s}if(0===Object.keys(r).length)return!0;return Xa(Ua(s,Ya({},r)),r)}for(var qa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ja="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Ka=0;Ka<64;Ka++)Ja[qa.charCodeAt(Ka)]=Ka;var Za={exports:{}};function Qa(t,e){return t<e?-1:t>e?1:0}const tl=/* @__PURE__ */St(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:class{constructor(t=[],e=Qa){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(t){this.data.push(t),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:i}=this,s=e[t];for(;t>0;){const r=t-1>>1,n=e[r];if(i(s,n)>=0)break;e[t]=n,t=r}e[t]=s}_down(t){const{data:e,compare:i}=this,s=this.length>>1,r=e[t];for(;t<s;){let s=1+(t<<1),n=e[s];const o=s+1;if(o<this.length&&i(e[o],n)<0&&(s=o,n=e[o]),i(n,r)>=0)break;e[t]=n,t=s}e[t]=r}}},Symbol.toStringTag,{value:"Module"})));var el;!function(){if(el)return Za.exports;el=1;var t=tl;function e(e,r,n){var o,a,l,h;r=r||1;for(var u=0;u<e[0].length;u++){var c=e[0][u];(!u||c[0]<o)&&(o=c[0]),(!u||c[1]<a)&&(a=c[1]),(!u||c[0]>l)&&(l=c[0]),(!u||c[1]>h)&&(h=c[1])}var d=l-o,p=h-a,f=Math.min(d,p),m=f/2;if(0===f){var g=[o,a];return g.distance=0,g}for(var y=new t(void 0,i),v=o;v<l;v+=f)for(var x=a;x<h;x+=f)y.push(new s(v+m,x+m,m,e));var b=function(t){for(var e=0,i=0,r=0,n=t[0],o=0,a=n.length,l=a-1;o<a;l=o++){var h=n[o],u=n[l],c=h[0]*u[1]-u[0]*h[1];i+=(h[0]+u[0])*c,r+=(h[1]+u[1])*c,e+=3*c}return 0===e?new s(n[0][0],n[0][1],0,t):new s(i/e,r/e,0,t)}(e),w=new s(o+d/2,a+p/2,0,e);w.d>b.d&&(b=w);for(var _=y.length;y.length;){var P=y.pop();P.d>b.d&&(b=P,n&&console.log("found best %d after %d probes",Math.round(1e4*P.d)/1e4,_)),P.max-b.d<=r||(m=P.h/2,y.push(new s(P.x-m,P.y-m,m,e)),y.push(new s(P.x+m,P.y-m,m,e)),y.push(new s(P.x-m,P.y+m,m,e)),y.push(new s(P.x+m,P.y+m,m,e)),_+=4)}n&&(console.log("num probes: "+_),console.log("best distance: "+b.d));var E=[b.x,b.y];return E.distance=b.d,E}function i(t,e){return e.max-t.max}function s(t,e,i,s){this.x=t,this.y=e,this.h=i,this.d=function(t,e,i){for(var s=!1,n=1/0,o=0;o<i.length;o++)for(var a=i[o],l=0,h=a.length,u=h-1;l<h;u=l++){var c=a[l],d=a[u];c[1]>e!=d[1]>e&&t<(d[0]-c[0])*(e-c[1])/(d[1]-c[1])+c[0]&&(s=!s),n=Math.min(n,r(t,e,c,d))}return 0===n?0:(s?1:-1)*Math.sqrt(n)}(t,e,s),this.max=this.d+this.h*Math.SQRT2}function r(t,e,i,s){var r=i[0],n=i[1],o=s[0]-r,a=s[1]-n;if(0!==o||0!==a){var l=((t-r)*o+(e-n)*a)/(o*o+a*a);l>1?(r=s[0],n=s[1]):l>0&&(r+=o*l,n+=a*l)}return(o=t-r)*o+(a=e-n)*a}t.default&&(t=t.default),Za.exports=e,Za.exports.default=e,Za.exports}();var il,sl={exports:{}};var rl,nl,ol=(il||(il=1,rl=sl,nl=function(){var t={},e=Math.PI/180,i=180/Math.PI,s=6378137,r=20037508.342789244;function n(t){return Number(t)===t&&t%1!=0}function o(e){if(e=e||{},this.size=e.size||256,this.expansion=!0===e.antimeridian?2:1,!t[this.size]){var i=this.size,s=t[this.size]={};s.Bc=[],s.Cc=[],s.zc=[],s.Ac=[];for(var r=0;r<30;r++)s.Bc.push(i/360),s.Cc.push(i/(2*Math.PI)),s.zc.push(i/2),s.Ac.push(i),i*=2}this.Bc=t[this.size].Bc,this.Cc=t[this.size].Cc,this.zc=t[this.size].zc,this.Ac=t[this.size].Ac}return o.prototype.px=function(t,i){if(n(i)){var s=this.size*Math.pow(2,i),r=s/2,o=s/360,a=s/(2*Math.PI),l=s,h=Math.min(Math.max(Math.sin(e*t[1]),-.9999),.9999),u=r+t[0]*o,c=r+.5*Math.log((1+h)/(1-h))*-a;return u>l*this.expansion&&(u=l*this.expansion),c>l&&(c=l),[u,c]}return r=this.zc[i],h=Math.min(Math.max(Math.sin(e*t[1]),-.9999),.9999),u=Math.round(r+t[0]*this.Bc[i]),c=Math.round(r+.5*Math.log((1+h)/(1-h))*-this.Cc[i]),u>this.Ac[i]*this.expansion&&(u=this.Ac[i]*this.expansion),c>this.Ac[i]&&(c=this.Ac[i]),[u,c]},o.prototype.ll=function(t,e){if(n(e)){var s=this.size*Math.pow(2,e),r=s/360,o=s/(2*Math.PI),a=s/2,l=(t[1]-a)/-o;return[(t[0]-a)/r,i*(2*Math.atan(Math.exp(l))-.5*Math.PI)]}return l=(t[1]-this.zc[e])/-this.Cc[e],[(t[0]-this.zc[e])/this.Bc[e],i*(2*Math.atan(Math.exp(l))-.5*Math.PI)]},o.prototype.bbox=function(t,e,i,s,r){s&&(e=Math.pow(2,i)-1-e);var n=[t*this.size,(+e+1)*this.size],o=[(+t+1)*this.size,e*this.size],a=this.ll(n,i).concat(this.ll(o,i));return"900913"===r?this.convert(a,"900913"):a},o.prototype.xyz=function(t,e,i,s){"900913"===s&&(t=this.convert(t,"WGS84"));var r=[t[0],t[1]],n=[t[2],t[3]],o=this.px(r,e),a=this.px(n,e),l=[Math.floor(o[0]/this.size),Math.floor((a[0]-1)/this.size)],h=[Math.floor(a[1]/this.size),Math.floor((o[1]-1)/this.size)],u={minX:Math.min.apply(Math,l)<0?0:Math.min.apply(Math,l),minY:Math.min.apply(Math,h)<0?0:Math.min.apply(Math,h),maxX:Math.max.apply(Math,l),maxY:Math.max.apply(Math,h)};if(i){var c={minY:Math.pow(2,e)-1-u.maxY,maxY:Math.pow(2,e)-1-u.minY};u.minY=c.minY,u.maxY=c.maxY}return u},o.prototype.convert=function(t,e){return"900913"===e?this.forward(t.slice(0,2)).concat(this.forward(t.slice(2,4))):this.inverse(t.slice(0,2)).concat(this.inverse(t.slice(2,4)))},o.prototype.forward=function(t){var i=[s*t[0]*e,s*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return i[0]>r&&(i[0]=r),i[0]<-r&&(i[0]=-r),i[1]>r&&(i[1]=r),i[1]<-r&&(i[1]=-r),i},o.prototype.inverse=function(t){return[t[0]*i/s,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/s)))*i]},o}(),rl.exports=nl),sl.exports);const al=/* @__PURE__ */It(ol),ll={work:{name:"Work",isHidden:!0,description:"space for individual head-down work",spaceUsage:{privateOffice:{name:"Private office",category:["office"]},focusRoom:{name:"Focus room",category:["office"]},openWorkspace:{name:"Open workspace",category:["office"]},enclosedWorkspace:{name:"Enclosed workspace",category:["office"]},closedWorkspace:{name:"Closed workspace",isDeprecated:!0,category:["office"]},executiveOffice:{name:"Executive office",isDeprecated:!0,category:["office"]}}},meet:{name:"Meet",isHidden:!0,spaceUsage:{meetingRoom:{name:"Meeting room",category:["office"]},hub:{name:"Hub",category:["office"]},assembly:{name:"Assembly",category:["office"]},boardRoom:{name:"Board room",category:["office"]},trainingRoom:{name:"Training room",category:["office"]},collaboration:{name:"Collaboration",isDeprecated:!0,category:["office"]}}},live:{name:"live",isHidden:!0,spaceUsage:{living:{name:"Living",category:["residential"]},dining:{name:"Dining",category:["residential"]},dining_living:{name:"Living & Dining",category:["residential"]},homeOffice:{name:"Home office",category:["residential"]},bedroom:{name:"Bedroom",category:["residential"]}}},socialize:{name:"Socialize",isHidden:!0,spaceUsage:{lobby:{name:"Lobby",category:["office","residential"]},reception:{name:"Reception",category:["office"]},lounge:{name:"Lounge",category:["office"]},cafe:{name:"Cafe",category:["office"]},canteen:{name:"Canteen",category:["office"]},pantry:{name:"Pantry",category:["office"]},terrace:{name:"Terrace",isOutdoor:!0,category:["office","residential"]},balcony:{name:"Balcony",isOutdoor:!0,category:["office","residential"]},rooftop:{name:"Rooftop",isOutdoor:!0,category:["office","residential"]},courtyard:{name:"Courtyard",isOutdoor:!0,category:["office","residential"]},garden:{name:"Garden",isOutdoor:!0,category:["residential"]},common:{name:"Common",isDeprecated:!0,category:["office"]}}},support:{name:"Support",isHidden:!0,spaceUsage:{serviceKitchen:{name:"Service kitchen",category:["office"]},printStation:{name:"Print station",category:["office"]},storage:{name:"Storage",category:["lightIndustrial","residential","office","parking"]},mailRoom:{name:"Mail room",category:["office"]},operationalRoom:{name:"Operational room",category:["lightIndustrial","office","parking"]},serviceRoom:{name:"Service room",category:["office"]},laundryRoom:{name:"Laundry room",category:["residential"]},loadingDock:{name:"Loading dock",category:["lightIndustrial"]},operate:{name:"Operate",isDeprecated:!0,category:["office"]},services:{name:"Services",isDeprecated:!0,category:["office","residential"]}}},care:{name:"Care",isHidden:!0,spaceUsage:{kitchen:{name:"Kitchen",category:["residential"]},wellnessRoom:{name:"Wellness room",category:["lightIndustrial","office"]},restroom:{name:"Restroom",category:["lightIndustrial","office","parking"]},bathroom:{name:"Bathroom",category:["residential"]},shower:{name:"Shower",category:["lightIndustrial","office","residential"]},toilet:{name:"Toilet",category:["residential"]}}},circulate:{name:"Circulate",isHidden:!0,spaceUsage:{corridor:{name:"Corridor",category:["lightIndustrial","residential","office","parking"]},foyer:{name:"Foyer",category:["lightIndustrial","residential","office","parking"]},staircase:{name:"Staircase",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},elevator:{name:"Elevator",isVertical:!0,category:["lightIndustrial","residential","office","parking"]}}},drive:{name:"Drive",isHidden:!0,spaceUsage:{parkingSpot:{name:"Parking spot",category:["parking"]},driveway:{name:"Driveway",category:["parking"]},garage:{name:"Garage",category:["residential"]}}},produce:{name:"Produce",isHidden:!0,spaceUsage:{productionArea:{name:"Production area",category:["lightIndustrial"]}}},void:{isHidden:!0,name:"Void",spaceUsage:{shaft:{name:"Shaft",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},buildingOpening:{name:"Building opening",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},floorOpening:{name:"Floor opening",isVertical:!0,category:["lightIndustrial","residential","office","parking"]}}},undefined:{isHidden:!0,spaceUsage:{undefined:{name:"Undefined",category:["residential","office"],isHidden:!0}}}},hl={};function ul(t,e,i){let s=ft(...t),r=ft(...e),n=ft(...i),o=dt(),a=dt(),l=dt();return yt(o,s,n),yt(a,r,n),xt(l,o,a),vt(l,l),[...l]}function cl(t){let{indices:e,vertices:i}=t,s=[],r=[],n=[],o=as(i);for(let u=0;u<i.length;u+=3){let t=i[u],e=i[u+1],n=i[u+2];s.push([t,e,n]),r.push([t,n])}for(let u=0;u<e.length;u+=3){let t=e[u],i=e[u+1],o=e[u+2];ul(s[t],s[i],s[o])[1]<.01||n.push([r[t],r[i],r[o]])}let a=[],l=[[]];if(!n.length)return{outlines:a,holes:l,boundingBox:o};let h=Q(Y(n),.0015);h=h.filter(t=>t&&t.length&&K(t)>5e-4);for(let u of h)Ei(u)?l[0].push(u):a.push(u);return{outlines:a,holes:l,boundingBox:o}}function dl(t,e={}){let i=function(t,e=nt(),i=/* @__PURE__ */new Map,s=!0){let r=[],n=t.spaceGraph;if("geometries"in t&&t.geometries)for(let o of t.geometries){let t,a,l,h;if("string"==typeof o){if(t=n.geometriesById[o],!t){ve.warn(`Geometry ${o} not found.`);continue}a=[0,0,0],l=0,h=[0,1,0]}else{if("reference:geometry"!==o.type){ve.warn(`Operation ${o.type} not supported.`);continue}let e=o.geometry;if("string"==typeof e){if(t=n.geometriesById[e],!t){ve.warn(`Geometry ${e} not found.`);continue}}else t=e;a=o.position??[0,0,0],l=o.rotation??0,h=o.rotationAxis??[0,1,0]}let u=je(a,l);for(let o of u){let a=Ti(o.position,o.rotation,h);s&&(a=ht(nt(),e,a));let l=[];if("geometry:uri"===t.type&&"data3d"===t.format){let e=i.get(t.uri),s=(null==e?void 0:e.meshGeometries)||{};for(let t in s){let e=s[t];l.push(...os(e,n.geometriesById,n.materialsById,[]))}}else l=os(t,n.geometriesById,n.materialsById,[]);let u=_t(),c=dt();ct(u,a),ut(c,a);for(let t of l)Ii(t.vertices,a);r.push({meshes:l,rotation:u,position:c})}}return r}(t,e.applyElementMatrix?gr(t,e.parentMatrix):void 0,e.resources),s=[];for(let r of i)for(let t of r.meshes)s.push(cl(t));return s}Object.keys(ll).forEach(t=>{const e=ll[t];hl[t]={name:e.name,type:"program",category:[]},e.isHidden&&(hl[t].isHidden=e.isHidden);const i={};Object.keys(ll[t].spaceUsage).forEach(e=>{const s=ll[t].spaceUsage[e];hl[e]={...s,type:"space",program:t},s.category.forEach(t=>{i[t]=!0})}),hl[t].category=Object.keys(i)}),new al({size:256});const pl=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function fl(t){return"string"==typeof t&&pl.test(t)}const ml={programs:{care:[{name:"bathroom",tags:[],categories:["residential"]},{name:"kitchen",tags:[],categories:["residential"]},{name:"restroom",tags:[],categories:["lightIndustrial","office","parking","laboratory"]},{name:"shower",tags:[],categories:["lightIndustrial","office","residential","laboratory"]},{name:"toilet",tags:[],categories:["residential"]},{name:"wellnessRoom",tags:[],categories:["lightIndustrial","office","laboratory"]}],circulate:[{name:"corridor",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"elevator",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"foyer",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"staircase",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]}],drive:[{name:"driveway",tags:[],categories:["parking"]},{name:"garage",tags:[],categories:["residential"]},{name:"parkingSpot",tags:[],categories:["parking"]}],live:[{name:"bedroom",tags:[],categories:["residential"]},{name:"dining",tags:[],categories:["residential"]},{name:"dining_living",tags:[],categories:["residential"]},{name:"homeOffice",tags:[],categories:["residential"]},{name:"living",tags:[],categories:["residential"]}],meet:[{name:"assembly",tags:[],categories:["office"]},{name:"boardRoom",tags:[],categories:["office"]},{name:"hub",tags:[],categories:["office"]},{name:"meetingRoom",tags:[],categories:["office"]},{name:"trainingRoom",tags:[],categories:["office"]}],none:[{name:"generic",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]}],produce:[{name:"productionArea",tags:[],categories:["lightIndustrial"]}],research:[{name:"lab",tags:[],categories:["lightIndustrial","laboratory"]}],socialize:[{name:"balcony",tags:["outdoor"],categories:["office","residential"]},{name:"cafe",tags:[],categories:["office","laboratory"]},{name:"canteen",tags:[],categories:["office"]},{name:"courtyard",tags:["outdoor"],categories:["office","residential"]},{name:"garden",tags:["outdoor"],categories:["residential"]},{name:"lobby",tags:[],categories:["office","residential","laboratory"]},{name:"lounge",tags:[],categories:["office","laboratory"]},{name:"pantry",tags:[],categories:["office"]},{name:"reception",tags:[],categories:["office","laboratory"]},{name:"rooftop",tags:["outdoor"],categories:["office","residential"]},{name:"terrace",tags:["outdoor"],categories:["office","residential"]}],support:[{name:"chemicalStore",tags:[],categories:["laboratory"]},{name:"cleanRoom",tags:[],categories:["laboratory"]},{name:"coldRoom",tags:[],categories:["laboratory"]},{name:"laundryRoom",tags:[],categories:["residential"]},{name:"loadingDock",tags:[],categories:["lightIndustrial"]},{name:"mailRoom",tags:[],categories:["office"]},{name:"operationalRoom",tags:[],categories:["lightIndustrial","office","parking","laboratory"]},{name:"printStation",tags:[],categories:["office"]},{name:"serviceKitchen",tags:[],categories:["office"]},{name:"serviceRoom",tags:[],categories:["office"]},{name:"storage",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]}],void:[{name:"buildingOpening",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"floorOpening",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"shaft",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]}],work:[{name:"enclosedWorkspace",tags:[],categories:["office"]},{name:"focusRoom",tags:[],categories:["office"]},{name:"openWorkspace",tags:[],categories:["office"]},{name:"privateOffice",tags:[],categories:["office"]}]}},gl="#ffffff",yl="#0c1829",vl="#4d586b",xl="#929baa",bl="#72849e",wl="#f1f2f3",_l="#cfd5de",Pl="#e8ebef",El="#f7f8fa",Tl="#3355ff",Al="#dfecff",Il="#ab220a",Sl={api:{productDataCacheAge:864e5,productContourCacheAge:864e6},hideElements:[],panZoom:!0,preserveViewbox:"center-center",showCeilingLamps:!1,destroyOnDomRemove:!1,ui:{scale:!0,coordinates:!1},spaceLabelMapping:{},theme:{fontFamily:"Inter, Avenir, Verdana, sans-serif",background:{color:El,showGrid:!1},wallContours:!1,showAssetTextures:!1},units:{system:"metric",areaDecimals:0,lengthDecimals:3,roomDimensions:"area"},zoomRange:[3,300]};let Cl="archilogic/product",Ml="https://storage.archilogic.com";const Ol=({apiStorageUrl:t,spaceApiUrl:e,apiProductDataPath:i}={})=>{"string"==typeof t&&(Ml=t),"string"==typeof i&&(Cl=i),"string"==typeof e&&(R=e)};let Nl=new E(["info","warnings","errors"]);function Ll(t,e){let i,s=e.product.geometries[0];const r="product:component"===e.product?.type;if("string"==typeof s){let t=s;i=e.spaceGraph.geometriesById[t]}else"reference:geometry"===s?.type&&"string"!=typeof s.geometry&&(i=s.geometry);if(!r&&!("geometry:uri"===i?.type))return Promise.reject("Unsupported product geometry: "+e.product.id);const n=r?["productJson"]:["productJson","productContour"];return t.loadResources(e.product.id,e,n).catch(t=>Nl.error(t))}const Rl=t=>{const e=[];return t.layout.elementsByType["element:asset"].forEach(t=>{"product"in t&&"product:static"===t.product?.type&&e.push(t)}),Promise.allSettled(e.map(e=>Ll(t.loader,e)))};function Bl(t){return fetch(`${Ml}/${Cl}/outline/${t}.json`).then(t=>{if(t.ok)return t.json();throw Error(t.statusText)})}const kl="undefined"==typeof window||"undefined"!=typeof process;let Fl;try{Fl=!kl&&Ca("al-kvs","al-keyval")}catch($w){Nl.warn("indexedDb initialization failed")}async function Dl(t,e,i){if(!Fl)return Promise.resolve();i=i||2592e6;try{const s={timeStamp:/* @__PURE__ */(new Date).getTime(),content:e,maxAge:i};return await function(t,e,i=Oa()){return i("readwrite",i=>(i.put(e,t),Sa(i.transaction)))}(t,s,Fl),t}catch(s){return}}async function Ul(t,e){if(!Fl)return Promise.resolve();const i=e||2592e6,s=/* @__PURE__ */(new Date).getTime();let r;try{r=await function(t,e=Oa()){return e("readonly",e=>Sa(e.get(t)))}(t,Fl);const e=s-r.timeStamp;if(e>Math.min(r.maxAge,i))return;if(r.content)return r.content}catch(n){return}}const Gl="fpe-dc2-";var Xl=/* @__PURE__ */(t=>(t[t.None=0]="None",t[t.Default=1]="Default",t[t.Grayscale=2]="Grayscale",t))(Xl||{});class Wl extends ce.TinyEmitter{constructor(t){super(),this.promiseCache=/* @__PURE__ */new Map,this.loadStages={product:!0,productContour:!0,productTexture:!1},this.queue={productJson:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.resources={nodes:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.initialLoading=!0,this._requestCounter=0,this._loadCounter=0;const{settings:e}=t;this.floorPlan=t,this.productContourCacheAge=e.api?.productContourCacheAge,this.productDataCacheAge=e.api?.productDataCacheAge,this.loadStages.productTexture=!!e.theme?.showAssetTextures&&!1!==e.loadTextures,this.on("resource-loaded",this.loadStatus,this)}loadStatus(){const t=this._requestCounter;this._loadCounter++,this.emit("loading-status",{totalCount:t,doneCount:this._loadCounter}),t===this._loadCounter&&this.emit("loading-done",{totalCount:t})}loadResources(t,e,i){return Promise.all(i.map(i=>this.loadResource(t,e,i)))}loadResource(t,e,i){if(this.resources.nodes.has(t)||this.resources.nodes.set(t,/* @__PURE__ */new Set),this.resources.nodes.get(t).add(e),this.queue[i].has(t))return this.queue[i].get(t);let s;switch(this._requestCounter++,i){case"productJson":s=Yl(t,this,e.product);break;case"productContour":this.loadStages.productTexture&&this._requestCounter++,s=Hl(t,this).then(()=>{if(this.loadStages.productTexture&&!this.resources.texture.has(t)){if(!this.resources.productJson.has(t))return void Nl.warn("texture loading failed, no product info yet");const e=`${Ml}/${Cl}/thumb/${t}.png`;this.resources.texture.set(t,{textureUrl:e,applyFilter:1}),this.emit("product-load-texture",{resourceId:t})}})}return this.queue[i].set(t,s),s}reset(){this.resources={nodes:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.queue={productContour:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this._loadCounter=0,this._requestCounter=0,this.promiseCache=/* @__PURE__ */new Map,this.initialLoading=!0}}const Yl=(t,e,i)=>{const s=e.floorPlan.spaceGraph;t!==i?.id||s.productsById[t]||s.insertProduct(i);const r=JSON.parse(JSON.stringify(i?.attributes||{}));return Number.isFinite(r.boundingBox?.min[0])||(Nl.warn("invalid product bounding box"),delete r.boundingBox),e.resources.productJson.set(t,r),Promise.resolve().then(()=>{e.emit("resource-loaded",{resourceId:t})})},Hl=async(t,e)=>{const i=Gl+t,s=e.promiseCache.get(i);if(s)return s;const r=function(t,e){const i=e.productContourCacheAge,s=i||864e6;if(!t)return Promise.reject("product id missing");const r=Gl+t,n=e.promiseCache.get(r);if(n)return n;const o=Ul(r,i).then(e=>e||Bl(t).then(t=>(Dl(r,t,s),t))).catch(t=>{Nl.warn(t)});return e.promiseCache.set(r,o),o}(t,e).then(i=>{const s=i,r=e.resources.productJson.get(t);if(!r.boundingBox){Nl.warn("product boundingbox missing - creating from contour");let t=W(s);r.boundingBox={min:[t.min[0],0,t.min[1]],max:[t.max[0],0,t.max[1]]}}e.resources.productContour.set(t,s),e.emit("resource-loaded",{resourceId:t})}).catch(()=>{});return e.promiseCache.set(i,r),r};function $l(t){return t.max.map((e,i)=>e-t.min[i])}function jl(t,e=[0,0]){const{dimensions:i}=t.parameters,s=t.parent;let r=[];if("element:wall"===s?.type){let t=s.parameters.width;r=[[-e[0],-e[1]],[i[0]+e[0],-e[1]],[i[0]+e[0],t+e[1]],[-e[0],t+e[1]]]}return[{type:"curve:polygon",points:r}]}function zl(t,e){const i=t.elements[0]||t,s=e?.[i?.type];return void 0===s||("boolean"==typeof s?s:i.isExternal?s.external:s.internal)}function Vl(t,e={clip:{"element:door":!0,"element:window":!0}}){const i=.01,s=t.elementsByType["element:wall"],r=t.elementsByType["element:boundaryWall"],n=t.elementsByType["element:column"],o=t.elementsByType["element:opening"],a=[];for(const c of o){if(!zl(c,e.clip))continue;const t=jl(c,[0,i]),{position:s,rotation:r}=c,n={position:[s[0],s[2]],rotation:r},o=Mi(t[0].points,n);a.push([o])}const l=[];for(const c of s){let{points:t}=c.geometryProfile;t=$([t],i)[0],l.push([t])}for(const c of n){const{profile:t}=c.parameters;let{points:e}=ss(t);if("curve:rectangle"===t.type){const[i,s]=t.dimensions;e=[[-i/2,-s/2],[i/2,-s/2],[i/2,s/2],[-i/2,s/2]]}e=Mi(e,{position:[c.position[0],c.position[2]],rotation:c.rotation}),e=$([e],i)[0],l.push([e])}for(const c of r){let t=c.boundaries[0].geometryProfile;t=$([t],i)[0],l.push([t])}let{polygons:h}=function(t){if(!t.length||!t[0])return{polygons:[],polyTree:[]};let e=et(t[0]),i=[];for(let n=1;n<t.length;n++)i.push(...et(t[n]));let s=new X.Clipper;s.AddPaths(e,X.PolyType.ptSubject,!0),s.AddPaths(i,X.PolyType.ptClip,!0);let r=new X.PolyTree;return s.Execute(X.ClipType.ctUnion,r,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),H(r)}(l);h=j(h,-.01).polygons,a.length&&(h=V(h,a).polygons);const u=[];for(const c of h){const t=[];for(const e of c){let i=tt(e,.001);i.length&&t.push(i)}t.length&&u.push(t)}return u}const ql=class t{constructor({options:t={}}={}){this.settings=y(Sl),this.fpeId="fpe-"+Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,3),this.computed={wallContours:[],snapPoints:[],snapMargin:0},this.isBrowser="object"!=typeof process&&"undefined"!=typeof window,this.location={latitude:0,longitude:0,bearing:0},this._emitter=new ce.TinyEmitter,ve.setLevels("errors"),this.set(t),this.loader=new Wl(this)}on(t,e,i){return this._emitter.on(t,e,i),this}once(t,e,i){return this._emitter.once(t,e,i),this}off(t,e){return this._emitter.off(t,e),this}emit(t,...e){return this._emitter.emit(t,...e),this}loadLayout(t,{skipGeometryCompute:e=!1}={}){this.loadSpaceGraph(t.spaceGraph,{skipGeometryCompute:e,layoutId:t.id})}loadSpaceGraph(t,{skipGeometryCompute:e=!1,layoutId:i}={}){if(this.loader.initialLoading||this.loader.reset(),this.spaceGraph=t,this.layout=i?t.nodesById[i]:t.nodesByType["spatialStructure:layout"][0],"spatialStructure:building"===this.spaceGraph.spatialStructure.type?(this.building=this.spaceGraph.spatialStructure,this.settings.loadFloorLevel||(this.settings.loadFloorLevel=this.building.getLevelOrder()[0])):this.building=null,this.layout&&"spatialStructure:layout"===this.layout.type){if(!e)for(const e of t.nodesByType["spatialStructure:layout"])Ia(e),kr(e);this.settings.theme.wallContours&&(this.computed.wallContours=Vl(this.layout)),setTimeout(()=>{this.updateThemeFilter(),this.loader.emit("spaces-loaded")},0),Rl(this).then(()=>{const t=this.settings.hideElements.includes("element:asset"),e=0===Object.keys(this.spaceGraph.products).length;this.updateThemeFilter(),this.loader.emit("assets-loaded",!0),(t||e)&&this.loader.emit("loading-done",{totalCount:0})}).catch(t=>Nl.warn(t)),this.loader.initialLoading=!1}else Nl.warn("No layout to load")}loadSpaceGraphJson(t){this.loadSpaceGraph(So.fromJSON(t))}async loadFloorById(e,i=this.settings.api){return new Promise(async(r,n)=>{e&&"string"==typeof e||n(`Expected non-empty string floorId parameter; instead got: "${e}"`);try{const n=B({...i,sdkVersion:t.version}),a=new U(n);this.loader.once("assets-loaded",r);const l=await a.getFloorById(e,!1,!1,!0),h=l.properties?.address;if(o=h?.latitude,s(o,90)&&(this.location.latitude=h.latitude),function(t){return s(t,180)}(h?.longitude)&&(this.location.longitude=h.longitude),function(t){return s(t,180)}(h?.bearing)&&(this.location.bearing=h.bearing),!l.layout?.layout)throw new Error(`The floor ${e} has no space graph layout`);this.emit("space-api-floor-loaded",e),this.loadSpaceGraphJson(l.layout.layout)}catch($w){n($w)}var o}).catch(t=>{throw this.emit("space-api-floor-error",e,t),t})}async loadLayoutById(e,i=this.settings.api){return new Promise(async(s,r)=>{e&&"string"==typeof e||r(`Expected non-empty string layoutId parameter; instead got: "${e}"`);try{const r=B({...i,sdkVersion:t.version}),n=new U(r);this.loader.once("assets-loaded",s);const o=await n.getLayout(e);if(!o?.layout)throw new Error(`Loading layout ${e} failed`);this.emit("space-api-floor-loaded",e),this.loadSpaceGraphJson(o.layout)}catch($w){r($w)}}).catch(t=>{throw this.emit("space-api-floor-error",e,t),t})}set(t={}){const e=this.settings.hideElements?.includes("element:asset");let i=y(t);("roomStampSize"in i||i.theme&&"elements"in i.theme)&&(i.theme=(t=>{const e=t.theme||{};if(!e?.elements&&void 0===t.roomStampSize)return e;const i={};for(const s of Object.keys(e))"elements"!==s&&(i[s]=e[s]);if(e?.elements)for(const s of Object.keys(e.elements))if("roomStamp"===s)i.roomStamps=e.elements[s];else if("layout:space"===s){const t=y(e.elements[s]);if(delete t.program,delete t.usage,i.byType??={},i.byType[s]=t,e.elements[s]?.program){i.byFilter??=[];for(const t of Object.keys(e.elements[s].program)){const r=e.elements[s].program[t];i.byFilter.push({where:{type:"layout:space",category:t},style:r})}}if(e.elements[s]?.usage){i.byFilter??=[];for(const t of Object.keys(e.elements[s].usage)){const r=e.elements[s].usage[t];i.byFilter.push({where:{type:"layout:space",subCategory:t},style:r})}}}else"byId"===s?i.byId=e.elements[s]:"floorPlan"===s?(i.byType??={},i.byType["annotation:floorPlanImage"]=e.elements[s]):(i.byType??={},i.byType[s]=e.elements[s]);return t.roomStampSize&&(i.roomStamps??={},i.roomStamps.fontSize=t.roomStampSize),i})(i)),i.theme&&(i.theme=v(Sl.theme,i.theme)),i.ui&&(i.ui={...Sl.ui,...i.ui}),i.api&&(i.api={...Sl.api,...i.api}),i.units&&(i.units={...Sl.units,...i.units});const s=!i.hideElements?.includes("element:asset");for(let r in i)this.settings[r]=i[r];this.layout&&(e&&s&&Rl(this),i.theme?.wallContours&&!this.computed.wallContours?.length?this.computed.wallContours=Vl(this.layout):!i.theme?.wallContours&&this.computed.wallContours?.length&&(this.computed.wallContours=[])),this.updateThemeFilter(),this.emit("update-settings",this.settings)}updateThemeFilter(){this.settings?.theme?.byResolvedFilter&&(this.settings.theme.byResolvedFilter={}),this.layout&&this.settings?.theme?.byFilter&&(this.settings.theme.byResolvedFilter=function(t,e=[]){const i={};for(const s of e){const e={id:!0},r=t.getElements({select:e,where:s.where});r.push(...t.getSpaces({select:e,where:s.where}));for(const t of r)"style"in s&&(i[t.id]=s.style)}return i}(this,this.settings.theme.byFilter))}getBoundingBox(t=0){let e={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]};if(this.building&&this.settings.loadFloorLevel){const t=this.building.floorsByLevel[this.settings.loadFloorLevel]||[];for(const i of t){const{position:t,rotation:s}=i,r=i.layouts[0];if(!r)continue;const n=ls({...r.getBoundingBox(),transform:{position:t,rotation:s,rotationAxis:[0,1,0]}});for(let i=0;i<e.min.length;i++)e.min[i]=Math.min(e.min[i],n.min[i]),e.max[i]=Math.max(e.max[i],n.max[i])}}else e=this.layout.getBoundingBox();const[i,,s]=e.min,[r,,n]=e.max;return{min:[i-t,s-t],max:[r+t,n+t]}}getElements(t={}){return this.layout?function(t,e){const{items:i,args:s}=za(t.getElementList(),t,e);return $a(i,s)}(this.layout,t):[]}getElementsById(t){return this.layout?function(t,e){const i=t.elementsById[e.id];return(i?$a([i],e):[])[0]||null}(this.layout,t):null}getSpaces(t={}){return this.layout?function(t,e){const{items:i,args:s}=za(t.spaces,t,e);return $a(i,s)}(this.layout,t):[]}getSpacesById(t){return this.layout?function(t,e){const i=t.spacesById[e.id];return(i?$a([i],e):[])[0]||null}(this.layout,t):null}getResourcesFromPosition(t){const e=this.layout?.spaces?.filter(e=>xi(t,e.geometry.polygons))||[],i=[];return e.forEach(e=>{const s=e.getElements("element:asset").filter(e=>{if(e.product.attributes.subCategories.includes("ceilingLight")&&!this.settings.showCeilingLamps)return;const i=e.getBoundingBoxContour();return i?.length?q(t,i):void 0});i.push(...s)}),{spaces:e,assets:i}}destroy(){delete this.layout,delete this.settings}};ql.version="5.4.2";let Jl=ql;function Kl(t){let{length:e,hingeSide:i,doorSide:s,doorAngle:r,doorType:n,frameThickness:o,frameDepth:a}=t.parameters,l=[],h="right"===i,u="side1"===s,c=u?0:a,d=!1,p=0,f=0;if(r<5&&r>-5){r=20;const t=r/180*Math.PI;p=Math.sin(t),f=Math.cos(t),d=!0}if("singleSwing"===n){let t,i,s,n,a=e-2*o;u?h?(t=0,i=r,s=[o,c],n=[s[0]+f*a,s[1]-p*a]):(t=180-r,i=180,s=[e-o,c],n=[s[0]-f*a,s[1]-p*a]):h?(t=-180,i=-180+r,s=[e-o,c],n=[s[0]-f*a,s[1]+p*a]):(t=360-r,i=360,s=[o,c],n=[s[0]+f*a,s[1]+p*a]),l.push({type:"curve:arc",radius:a,position:s,startAngle:t,endAngle:i}),d&&l.push({type:"curve:line",start:s,end:n})}else if("doubleSwing"===n){let t,i,s,n,a,h,m,g,y=e/2-o;u?(t=0,i=r,s=[o,c],m=[e-o,c],a=180-r,h=180,n=[s[0]+f*y,s[1]-p*y],g=[m[0]-f*y,m[1]-p*y]):(t=360-r,i=360,s=[o,c],m=[e-o,c],a=180,h=180+r,n=[s[0]+f*y,s[1]+p*y],g=[m[0]-f*y,m[1]+p*y]),l.push({type:"curve:arc",radius:y,position:s,startAngle:t,endAngle:i}),l.push({type:"curve:arc",radius:y,position:m,startAngle:a,endAngle:h}),d&&(l.push({type:"curve:line",start:s,end:n}),l.push({type:"curve:line",start:m,end:g}))}return l}function Zl(t){let e=[];switch(t.type){case"element:door":e=Kl(t);break;case"element:stairFlight":e=function(t){let e=t.parent?.elements.find(t=>"element:stairFlight"===t.type);if(e?.id!==t.id||"spiral"===t.parameters.stairFlightType)return[];let{width:i,length:s,height:r}=t.parameters,n=s/Math.round(r/.17);return[{type:"curve:polyline",points:[[n/2-.06,i/2+.12],[n/2+.06,i/2],[n/2-.06,i/2-.12]]}]}(t)}return e}function Ql(t){for(const e of Object.keys(ml.programs)){if(ml.programs[e].find(e=>e.name===t))return e}return""}function th(t,e=0){return({"element:door":45,"element:window":45,"element:opening":40,"element:spaceDivider":35,"spatialGraph:edge":35,"element:column":30,"element:wall":30,"element:boundaryWall":30,"element:casework":20,"element:kitchen":20,"element:railing":20,"element:generic":11,"element:asset":10,"element:stairs":5,"element:stairFlight":5,"element:slab":5,"layout:space":1,"annotation:floorPlanDxf":0,"annotation:floorPlanImage":0}[t]||0)+e}function eh(t){if("number"==typeof t)return t;if(Array.isArray(t)||"string"==typeof t&&t.startsWith("#")){const[e,i,s]=function(t){if(Array.isArray(t))return[t[0],t[1],t[2]];if("number"==typeof t)return[t>>16&255,t>>8&255,255&t];if("string"==typeof t&&t.startsWith("#")){const e=t.slice(1);if(3===e.length)return[parseInt(e[0]+e[0],16),parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16)];if(6===e.length)return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}return[0,0,0]}(t);return(e<<16)+(i<<8)+s}}const ih={default:{fill:gl,stroke:xl,strokeWidth:"native",fillOpacity:1},selected:{fill:Al,stroke:xl,strokeWidth:1}};const sh=({settings:t,nodeId:e,parentId:i,nodeType:s})=>{const r=t?.theme;if(!r)return{};return(t=>{const{fill:e,fillOpacity:i,stroke:s,strokeWidth:r,strokeOpacity:n}=t,o={};return e&&(o.fill=eh(e)),s&&(o.stroke=eh(s)),"number"==typeof i&&Number.isFinite(i)&&(o.fillOpacity=Math.max(Math.min(i,1),0)),"number"==typeof n&&Number.isFinite(n)&&(o.strokeOpacity=Math.max(Math.min(n,1),0)),"string"==typeof r?"native"===r&&(o.strokeWidth=r):Number.isFinite(r)&&r>=0&&(o.strokeWidth=r),o})(r.byId?.[e]||r.byResolvedFilter?.[e]||r.byId?.[i]||r.byResolvedFilter?.[i]||r.byType?.[s]||null||{})},rh=t=>{if(t?.layout?.debugIds){let i=/\d+/.exec(t.id)?.[0]||"0",s=(e=parseInt(i),function(){let t=e+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296});return{fill:Math.round(5*s()*16777215)%16777215,fillOpacity:.5}}var e;return{}},nh=({style:t,settings:e,element:i,elementType:s})=>{const r="selected"===t?"selected":"default",n=function({element:t,settings:e,elementType:i,state:s="default"}){const r=e?.theme?.showAssetTextures,n={"element:wall":{default:{fill:vl,stroke:vl},selected:{fill:bl,stroke:Tl,strokeWidth:"native"}},"element:boundaryWall":{default:{fill:vl,stroke:yl},selected:{fill:bl,stroke:Tl}},"element:curtainWall":{default:{fill:wl},selected:{strokeWidth:"native"}},"element:column":{default:{fill:vl,stroke:vl},selected:{fill:bl,stroke:Tl,strokeWidth:"native"}},"element:asset":{default:{fill:r?null:wl},selected:{fill:Al,stroke:Tl,strokeWidth:.5,alignment:0}},"element:stairs":{default:{fill:El},selected:{strokeWidth:"native"}},"element:stairFlight":{default:{fill:El}},"element:slab":{default:{fill:El}},"layout:space":(()=>{const e={default:{fill:gl,stroke:_l},selected:{fill:Al,stroke:_l,strokeWidth:"native"}};if(t&&"layout:space"===t.type){const i="kitchen"!==t.attributes.usage&&Ql(t.attributes.usage),s={care:_l,circulate:El};i&&s[i]&&(e.default.fill=s[i]),"void"===i&&(e.default.fillOpacity=.05)}return e})(),"spatialGraph:edge":{default:{fill:_l,stroke:yl,strokeOpacity:.8,strokeWidth:.5},selected:{stroke:Tl,strokeWidth:.5}},"element:spaceDivider":{default:{fill:_l,stroke:yl,strokeOpacity:.8,strokeWidth:.5},selected:{stroke:Tl,strokeWidth:.5}}}[i]||ih,o=t&&"parent"in t?t.parent?.id:void 0,a=sh({settings:e,nodeId:t?.id,parentId:o,nodeType:i});return"selected"===s?{...ih.default,...n.default,...a,...ih.selected,...n.selected}:{...ih.default,...n.default,...a}}({element:i,elementType:s||i?.type,settings:e,state:r});return{...n,...t?{}:rh(i),..."object"==typeof t?t:{}}};function oh(t,e,i=.5){let s=[e[0]-t[0],e[1]-t[1]];return[t[0]+s[0]*i,t[1]+s[1]*i]}function ah(t,e,i,s=5){const r=[];let n,o,a,l=0;for(let h=0;h<=s;++h)l=h/s,n=oh(t,e,l),o=oh(e,i,l),a=oh(n,o,l),r.push(a);return r}const lh=(t,e)=>{const i=Math.ceil(48/(2*Math.PI)*t*e),s=Math.ceil(12/(2*Math.PI)*t);return Math.min(100,Math.max(s,i))},hh=t=>{const e={type:"curve:polyline",points:[],style:t.style};switch(t.type){case"curve:line":e.points=[t.start,t.end];break;case"curve:arc":const i=t.startAngle/180*Math.PI,s=t.endAngle/180*Math.PI-i,r=t.radius,n=lh(Math.abs(s),r),o=t.position,a=s/n;let l=i;for(let t=0;t<n+1;t++)e.points.push([r*Math.cos(l)+o[0],-r*Math.sin(l)+o[1]]),l+=a;break;case"curve:polyline":e.points=t.points;break;case"curve:quadraticBezier":e.points.push(t.points[0]);for(let h=0;h<=t.points.length-3;h++){let i=t.points[h],s=t.points[h+1],r=t.points[h+2],n=ah(0===h?i:oh(i,s),s,h===t.points.length-3?r:oh(s,r));e.points.push(...n.slice(1))}}return e},uh=(t,e,i=.15)=>{let s,r,n;for(const o of e)if(s=Math.abs(t[0]-o[0]),!(s>i)&&(r=Math.abs(t[1]-o[1]),s<i&&r<i)){n=o;break}return n};function ch(t){const e={10:["ceilingLight","wallLight"],9:["modularMeetingRoom","phoneBooth"],8:["floorLamp","tableLamp","deskDivider","cushion","plant","officeSupply","tableware","decoration","laundry","electronics","kitchen","car"],7:["shelf","cabinet","wardrobe","storageCombination","outdoor","bicycle","people","sink"],6:["highTable","diningTable","conferenceTable","desk"],5:["sofa","armchair","loungeChair","ottoman","sideboard","pedestal"],4:["taskChair","diningChair","conferenceChair","stool","barStool","bench"],3:["shower"],2:["singleBed","doubleBed","daybed","toilet","bathtub"],1:["sideTable","coffeeTable","radiator","nightstand"],0:["rug"]};let i=0;return t.subCategories.forEach(t=>{Object.keys(e).forEach(s=>{let r=parseInt(s);e[s].includes(t)&&r>i&&(i=r)})}),1===i&&t.categories.includes("tables")&&t.boundingBox.max[1]-t.boundingBox.min[1]>.6&&(i=6),i}var dh=/* @__PURE__ */(t=>(t[t.WEBGL_LEGACY=0]="WEBGL_LEGACY",t[t.WEBGL=1]="WEBGL",t[t.WEBGL2=2]="WEBGL2",t))(dh||{}),ph=/* @__PURE__ */(t=>(t[t.UNKNOWN=0]="UNKNOWN",t[t.WEBGL=1]="WEBGL",t[t.CANVAS=2]="CANVAS",t))(ph||{}),fh=/* @__PURE__ */(t=>(t[t.COLOR=16384]="COLOR",t[t.DEPTH=256]="DEPTH",t[t.STENCIL=1024]="STENCIL",t))(fh||{}),mh=/* @__PURE__ */(t=>(t[t.NORMAL=0]="NORMAL",t[t.ADD=1]="ADD",t[t.MULTIPLY=2]="MULTIPLY",t[t.SCREEN=3]="SCREEN",t[t.OVERLAY=4]="OVERLAY",t[t.DARKEN=5]="DARKEN",t[t.LIGHTEN=6]="LIGHTEN",t[t.COLOR_DODGE=7]="COLOR_DODGE",t[t.COLOR_BURN=8]="COLOR_BURN",t[t.HARD_LIGHT=9]="HARD_LIGHT",t[t.SOFT_LIGHT=10]="SOFT_LIGHT",t[t.DIFFERENCE=11]="DIFFERENCE",t[t.EXCLUSION=12]="EXCLUSION",t[t.HUE=13]="HUE",t[t.SATURATION=14]="SATURATION",t[t.COLOR=15]="COLOR",t[t.LUMINOSITY=16]="LUMINOSITY",t[t.NORMAL_NPM=17]="NORMAL_NPM",t[t.ADD_NPM=18]="ADD_NPM",t[t.SCREEN_NPM=19]="SCREEN_NPM",t[t.NONE=20]="NONE",t[t.SRC_OVER=0]="SRC_OVER",t[t.SRC_IN=21]="SRC_IN",t[t.SRC_OUT=22]="SRC_OUT",t[t.SRC_ATOP=23]="SRC_ATOP",t[t.DST_OVER=24]="DST_OVER",t[t.DST_IN=25]="DST_IN",t[t.DST_OUT=26]="DST_OUT",t[t.DST_ATOP=27]="DST_ATOP",t[t.ERASE=26]="ERASE",t[t.SUBTRACT=28]="SUBTRACT",t[t.XOR=29]="XOR",t))(mh||{}),gh=/* @__PURE__ */(t=>(t[t.POINTS=0]="POINTS",t[t.LINES=1]="LINES",t[t.LINE_LOOP=2]="LINE_LOOP",t[t.LINE_STRIP=3]="LINE_STRIP",t[t.TRIANGLES=4]="TRIANGLES",t[t.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",t[t.TRIANGLE_FAN=6]="TRIANGLE_FAN",t))(gh||{}),yh=/* @__PURE__ */(t=>(t[t.RGBA=6408]="RGBA",t[t.RGB=6407]="RGB",t[t.RG=33319]="RG",t[t.RED=6403]="RED",t[t.RGBA_INTEGER=36249]="RGBA_INTEGER",t[t.RGB_INTEGER=36248]="RGB_INTEGER",t[t.RG_INTEGER=33320]="RG_INTEGER",t[t.RED_INTEGER=36244]="RED_INTEGER",t[t.ALPHA=6406]="ALPHA",t[t.LUMINANCE=6409]="LUMINANCE",t[t.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",t[t.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",t[t.DEPTH_STENCIL=34041]="DEPTH_STENCIL",t))(yh||{}),vh=/* @__PURE__ */(t=>(t[t.TEXTURE_2D=3553]="TEXTURE_2D",t[t.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",t[t.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",t[t.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",t[t.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",t[t.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",t[t.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",t))(vh||{}),xh=/* @__PURE__ */(t=>(t[t.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",t[t.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",t[t.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",t[t.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",t[t.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",t[t.UNSIGNED_INT=5125]="UNSIGNED_INT",t[t.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",t[t.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",t[t.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",t[t.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",t[t.BYTE=5120]="BYTE",t[t.SHORT=5122]="SHORT",t[t.INT=5124]="INT",t[t.FLOAT=5126]="FLOAT",t[t.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",t[t.HALF_FLOAT=36193]="HALF_FLOAT",t))(xh||{}),bh=/* @__PURE__ */(t=>(t[t.FLOAT=0]="FLOAT",t[t.INT=1]="INT",t[t.UINT=2]="UINT",t))(bh||{}),wh=/* @__PURE__ */(t=>(t[t.NEAREST=0]="NEAREST",t[t.LINEAR=1]="LINEAR",t))(wh||{}),_h=/* @__PURE__ */(t=>(t[t.CLAMP=33071]="CLAMP",t[t.REPEAT=10497]="REPEAT",t[t.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",t))(_h||{}),Ph=/* @__PURE__ */(t=>(t[t.OFF=0]="OFF",t[t.POW2=1]="POW2",t[t.ON=2]="ON",t[t.ON_MANUAL=3]="ON_MANUAL",t))(Ph||{}),Eh=/* @__PURE__ */(t=>(t[t.NPM=0]="NPM",t[t.UNPACK=1]="UNPACK",t[t.PMA=2]="PMA",t[t.NO_PREMULTIPLIED_ALPHA=0]="NO_PREMULTIPLIED_ALPHA",t[t.PREMULTIPLY_ON_UPLOAD=1]="PREMULTIPLY_ON_UPLOAD",t[t.PREMULTIPLIED_ALPHA=2]="PREMULTIPLIED_ALPHA",t))(Eh||{}),Th=/* @__PURE__ */(t=>(t[t.NO=0]="NO",t[t.YES=1]="YES",t[t.AUTO=2]="AUTO",t[t.BLEND=0]="BLEND",t[t.CLEAR=1]="CLEAR",t[t.BLIT=2]="BLIT",t))(Th||{}),Ah=/* @__PURE__ */(t=>(t[t.AUTO=0]="AUTO",t[t.MANUAL=1]="MANUAL",t))(Ah||{}),Ih=/* @__PURE__ */(t=>(t.LOW="lowp",t.MEDIUM="mediump",t.HIGH="highp",t))(Ih||{}),Sh=/* @__PURE__ */(t=>(t[t.NONE=0]="NONE",t[t.SCISSOR=1]="SCISSOR",t[t.STENCIL=2]="STENCIL",t[t.SPRITE=3]="SPRITE",t[t.COLOR=4]="COLOR",t))(Sh||{}),Ch=/* @__PURE__ */(t=>(t[t.NONE=0]="NONE",t[t.LOW=2]="LOW",t[t.MEDIUM=4]="MEDIUM",t[t.HIGH=8]="HIGH",t))(Ch||{}),Mh=/* @__PURE__ */(t=>(t[t.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",t[t.ARRAY_BUFFER=34962]="ARRAY_BUFFER",t[t.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",t))(Mh||{});const Oh={ADAPTER:{createCanvas:(t,e)=>{const i=document.createElement("canvas");return i.width=t,i.height=e,i},getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(t,e)=>fetch(t,e),parseXML:t=>(new DOMParser).parseFromString(t,"text/xml")},RESOLUTION:1,CREATE_IMAGE_BITMAP:!1,ROUND_PIXELS:!1};var Nh=/iPhone/i,Lh=/iPod/i,Rh=/iPad/i,Bh=/\biOS-universal(?:.+)Mac\b/i,kh=/\bAndroid(?:.+)Mobile\b/i,Fh=/Android/i,Dh=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,Uh=/Silk/i,Gh=/Windows Phone/i,Xh=/\bWindows(?:.+)ARM\b/i,Wh=/BlackBerry/i,Yh=/BB10/i,Hh=/Opera Mini/i,$h=/\b(CriOS|Chrome)(?:.+)Mobile/i,jh=/Mobile(?:.+)Firefox\b/i,zh=function(t){return void 0!==t&&"MacIntel"===t.platform&&"number"==typeof t.maxTouchPoints&&t.maxTouchPoints>1&&"undefined"==typeof MSStream};function Vh(t){var e={userAgent:"",platform:"",maxTouchPoints:0};t||"undefined"==typeof navigator?"string"==typeof t?e.userAgent=t:t&&t.userAgent&&(e={userAgent:t.userAgent,platform:t.platform,maxTouchPoints:t.maxTouchPoints||0}):e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0};var i=e.userAgent,s=i.split("[FBAN");void 0!==s[1]&&(i=s[0]),void 0!==(s=i.split("Twitter"))[1]&&(i=s[0]);var r=function(t){return function(e){return e.test(t)}}(i),n={apple:{phone:r(Nh)&&!r(Gh),ipod:r(Lh),tablet:!r(Nh)&&(r(Rh)||zh(e))&&!r(Gh),universal:r(Bh),device:(r(Nh)||r(Lh)||r(Rh)||r(Bh)||zh(e))&&!r(Gh)},amazon:{phone:r(Dh),tablet:!r(Dh)&&r(Uh),device:r(Dh)||r(Uh)},android:{phone:!r(Gh)&&r(Dh)||!r(Gh)&&r(kh),tablet:!r(Gh)&&!r(Dh)&&!r(kh)&&(r(Uh)||r(Fh)),device:!r(Gh)&&(r(Dh)||r(Uh)||r(kh)||r(Fh))||r(/\bokhttp\b/i)},windows:{phone:r(Gh),tablet:r(Xh),device:r(Gh)||r(Xh)},other:{blackberry:r(Wh),blackberry10:r(Yh),opera:r(Hh),firefox:r(jh),chrome:r($h),device:r(Wh)||r(Yh)||r(Hh)||r(jh)||r($h)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const qh=(Vh.default??Vh)(globalThis.navigator);Oh.RETINA_PREFIX=/@([0-9\.]+)x/,Oh.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT=!1;var Jh,Kh={exports:{}};var Zh=(Jh||(Jh=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,o){if("function"!=typeof s)throw new TypeError("The listener must be a function");var a=new r(s,n||t,o),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],a]:t._events[l].push(a):(t._events[l]=a,t._eventsCount++),t}function o(t,e){0===--t._eventsCount?t._events=new s:delete t._events[e]}function a(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=/* @__PURE__ */Object.create(null),(new s).__proto__||(i=!1)),a.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},a.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,o=new Array(n);r<n;r++)o[r]=s[r].fn;return o},a.prototype.listenerCount=function(t){var e=i?i+t:t,s=this._events[e];return s?s.fn?1:s.length:0},a.prototype.emit=function(t,e,s,r,n,o){var a=i?i+t:t;if(!this._events[a])return!1;var l,h,u=this._events[a],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,s),!0;case 4:return u.fn.call(u.context,e,s,r),!0;case 5:return u.fn.call(u.context,e,s,r,n),!0;case 6:return u.fn.call(u.context,e,s,r,n,o),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];u.fn.apply(u.context,l)}else{var d,p=u.length;for(h=0;h<p;h++)switch(u[h].once&&this.removeListener(t,u[h].fn,void 0,!0),c){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,e);break;case 3:u[h].fn.call(u[h].context,e,s);break;case 4:u[h].fn.call(u[h].context,e,s,r);break;default:if(!l)for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];u[h].fn.apply(u[h].context,l)}}return!0},a.prototype.on=function(t,e,i){return n(this,t,e,i,!1)},a.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},a.prototype.removeListener=function(t,e,s,r){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return o(this,n),this;var a=this._events[n];if(a.fn)a.fn!==e||r&&!a.once||s&&a.context!==s||o(this,n);else{for(var l=0,h=[],u=a.length;l<u;l++)(a[l].fn!==e||r&&!a[l].once||s&&a[l].context!==s)&&h.push(a[l]);h.length?this._events[n]=1===h.length?h[0]:h:o(this,n)}return this},a.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&o(this,e)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,t.exports=a}(Kh)),Kh.exports);const Qh=/* @__PURE__ */It(Zh);var tu,eu,iu,su={},ru={exports:{}},nu=ru.exports;function ou(){return iu?eu:(iu=1,eu=TypeError)}const au=/* @__PURE__ */St(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var lu,hu,uu,cu,du,pu,fu,mu,gu,yu,vu,xu,bu,wu,_u,Pu,Eu,Tu,Au,Iu,Su,Cu,Mu,Ou,Nu,Lu,Ru,Bu,ku,Fu,Du,Uu,Gu,Xu,Wu,Yu,Hu,$u,ju,zu,Vu,qu,Ju,Ku,Zu,Qu,tc,ec,ic,sc,rc,nc,oc,ac,lc,hc,uc,cc,dc,pc,fc,mc,gc,yc,vc,xc,bc,wc,_c,Pc,Ec,Tc,Ac,Ic,Sc,Cc,Mc,Oc,Nc,Lc,Rc,Bc,kc,Fc,Dc,Uc,Gc,Xc,Wc;function Yc(){if(hu)return lu;hu=1;var t="function"==typeof Map&&Map.prototype,e=Object.getOwnPropertyDescriptor&&t?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,i=t&&e&&"function"==typeof e.get?e.get:null,s=t&&Map.prototype.forEach,r="function"==typeof Set&&Set.prototype,n=Object.getOwnPropertyDescriptor&&r?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,o=r&&n&&"function"==typeof n.get?n.get:null,a=r&&Set.prototype.forEach,l="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,h="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,u="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,c=Boolean.prototype.valueOf,d=Object.prototype.toString,p=Function.prototype.toString,f=String.prototype.match,m=String.prototype.slice,g=String.prototype.replace,y=String.prototype.toUpperCase,v=String.prototype.toLowerCase,x=RegExp.prototype.test,b=Array.prototype.concat,w=Array.prototype.join,_=Array.prototype.slice,P=Math.floor,E="function"==typeof BigInt?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,I="function"==typeof Symbol&&"object"==typeof Symbol.iterator,S="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===I||"symbol")?Symbol.toStringTag:null,C=Object.prototype.propertyIsEnumerable,M=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function O(t,e){if(t===1/0||t===-1/0||t!=t||t&&t>-1e3&&t<1e3||x.call(/e/,e))return e;var i=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof t){var s=t<0?-P(-t):P(t);if(s!==t){var r=String(s),n=m.call(e,r.length+1);return g.call(r,i,"$&_")+"."+g.call(g.call(n,/([0-9]{3})/g,"$&_"),/_$/,"")}}return g.call(e,i,"$&_")}var N=au,L=N.custom,R=W(L)?L:null,B={__proto__:null,double:'"',single:"'"},k={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function F(t,e,i){var s=i.quoteStyle||e,r=B[s];return r+t+r}function D(t){return g.call(String(t),/"/g,""")}function U(t){return!S||!("object"==typeof t&&(S in t||void 0!==t[S]))}function G(t){return"[object Array]"===$(t)&&U(t)}function X(t){return"[object RegExp]"===$(t)&&U(t)}function W(t){if(I)return t&&"object"==typeof t&&t instanceof Symbol;if("symbol"==typeof t)return!0;if(!t||"object"!=typeof t||!A)return!1;try{return A.call(t),!0}catch(e){}return!1}lu=function t(e,r,n,d){var y=r||{};if(H(y,"quoteStyle")&&!H(B,y.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(H(y,"maxStringLength")&&("number"==typeof y.maxStringLength?y.maxStringLength<0&&y.maxStringLength!==1/0:null!==y.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var x=!H(y,"customInspect")||y.customInspect;if("boolean"!=typeof x&&"symbol"!==x)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(H(y,"indent")&&null!==y.indent&&"\t"!==y.indent&&!(parseInt(y.indent,10)===y.indent&&y.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(H(y,"numericSeparator")&&"boolean"!=typeof y.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var P=y.numericSeparator;if(void 0===e)return"undefined";if(null===e)return"null";if("boolean"==typeof e)return e?"true":"false";if("string"==typeof e)return z(e,y);if("number"==typeof e){if(0===e)return 1/0/e>0?"0":"-0";var T=String(e);return P?O(e,T):T}if("bigint"==typeof e){var L=String(e)+"n";return P?O(e,L):L}var k=void 0===y.depth?5:y.depth;if(void 0===n&&(n=0),n>=k&&k>0&&"object"==typeof e)return G(e)?"[Array]":"[Object]";var Y=function(t,e){var i;if("\t"===t.indent)i="\t";else{if(!("number"==typeof t.indent&&t.indent>0))return null;i=w.call(Array(t.indent+1)," ")}return{base:i,prev:w.call(Array(e+1),i)}}(y,n);if(void 0===d)d=[];else if(j(d,e)>=0)return"[Circular]";function V(e,i,s){if(i&&(d=_.call(d)).push(i),s){var r={depth:y.depth};return H(y,"quoteStyle")&&(r.quoteStyle=y.quoteStyle),t(e,r,n+1,d)}return t(e,y,n+1,d)}if("function"==typeof e&&!X(e)){var tt=function(t){if(t.name)return t.name;var e=f.call(p.call(t),/^function\s*([\w$]+)/);if(e)return e[1];return null}(e),et=Q(e,V);return"[Function"+(tt?": "+tt:" (anonymous)")+"]"+(et.length>0?" { "+w.call(et,", ")+" }":"")}if(W(e)){var it=I?g.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):A.call(e);return"object"!=typeof e||I?it:q(it)}if(function(t){if(!t||"object"!=typeof t)return!1;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)return!0;return"string"==typeof t.nodeName&&"function"==typeof t.getAttribute}(e)){for(var st="<"+v.call(String(e.nodeName)),rt=e.attributes||[],nt=0;nt<rt.length;nt++)st+=" "+rt[nt].name+"="+F(D(rt[nt].value),"double",y);return st+=">",e.childNodes&&e.childNodes.length&&(st+="..."),st+="</"+v.call(String(e.nodeName))+">"}if(G(e)){if(0===e.length)return"[]";var ot=Q(e,V);return Y&&!function(t){for(var e=0;e<t.length;e++)if(j(t[e],"\n")>=0)return!1;return!0}(ot)?"["+Z(ot,Y)+"]":"[ "+w.call(ot,", ")+" ]"}if(function(t){return"[object Error]"===$(t)&&U(t)}(e)){var at=Q(e,V);return"cause"in Error.prototype||!("cause"in e)||C.call(e,"cause")?0===at.length?"["+String(e)+"]":"{ ["+String(e)+"] "+w.call(at,", ")+" }":"{ ["+String(e)+"] "+w.call(b.call("[cause]: "+V(e.cause),at),", ")+" }"}if("object"==typeof e&&x){if(R&&"function"==typeof e[R]&&N)return N(e,{depth:k-n});if("symbol"!==x&&"function"==typeof e.inspect)return e.inspect()}if(function(t){if(!i||!t||"object"!=typeof t)return!1;try{i.call(t);try{o.call(t)}catch(st){return!0}return t instanceof Map}catch(e){}return!1}(e)){var lt=[];return s&&s.call(e,function(t,i){lt.push(V(i,e,!0)+" => "+V(t,e))}),K("Map",i.call(e),lt,Y)}if(function(t){if(!o||!t||"object"!=typeof t)return!1;try{o.call(t);try{i.call(t)}catch(e){return!0}return t instanceof Set}catch(s){}return!1}(e)){var ht=[];return a&&a.call(e,function(t){ht.push(V(t,e))}),K("Set",o.call(e),ht,Y)}if(function(t){if(!l||!t||"object"!=typeof t)return!1;try{l.call(t,l);try{h.call(t,h)}catch(st){return!0}return t instanceof WeakMap}catch(e){}return!1}(e))return J("WeakMap");if(function(t){if(!h||!t||"object"!=typeof t)return!1;try{h.call(t,h);try{l.call(t,l)}catch(st){return!0}return t instanceof WeakSet}catch(e){}return!1}(e))return J("WeakSet");if(function(t){if(!u||!t||"object"!=typeof t)return!1;try{return u.call(t),!0}catch(e){}return!1}(e))return J("WeakRef");if(function(t){return"[object Number]"===$(t)&&U(t)}(e))return q(V(Number(e)));if(function(t){if(!t||"object"!=typeof t||!E)return!1;try{return E.call(t),!0}catch(e){}return!1}(e))return q(V(E.call(e)));if(function(t){return"[object Boolean]"===$(t)&&U(t)}(e))return q(c.call(e));if(function(t){return"[object String]"===$(t)&&U(t)}(e))return q(V(String(e)));if("undefined"!=typeof window&&e===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&e===globalThis||void 0!==At&&e===At)return"{ [object globalThis] }";if(!function(t){return"[object Date]"===$(t)&&U(t)}(e)&&!X(e)){var ut=Q(e,V),ct=M?M(e)===Object.prototype:e instanceof Object||e.constructor===Object,dt=e instanceof Object?"":"null prototype",pt=!ct&&S&&Object(e)===e&&S in e?m.call($(e),8,-1):dt?"Object":"",ft=(ct||"function"!=typeof e.constructor?"":e.constructor.name?e.constructor.name+" ":"")+(pt||dt?"["+w.call(b.call([],pt||[],dt||[]),": ")+"] ":"");return 0===ut.length?ft+"{}":Y?ft+"{"+Z(ut,Y)+"}":ft+"{ "+w.call(ut,", ")+" }"}return String(e)};var Y=Object.prototype.hasOwnProperty||function(t){return t in this};function H(t,e){return Y.call(t,e)}function $(t){return d.call(t)}function j(t,e){if(t.indexOf)return t.indexOf(e);for(var i=0,s=t.length;i<s;i++)if(t[i]===e)return i;return-1}function z(t,e){if(t.length>e.maxStringLength){var i=t.length-e.maxStringLength,s="... "+i+" more character"+(i>1?"s":"");return z(m.call(t,0,e.maxStringLength),e)+s}var r=k[e.quoteStyle||"single"];return r.lastIndex=0,F(g.call(g.call(t,r,"\\$1"),/[\x00-\x1f]/g,V),"single",e)}function V(t){var e=t.charCodeAt(0),i={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return i?"\\"+i:"\\x"+(e<16?"0":"")+y.call(e.toString(16))}function q(t){return"Object("+t+")"}function J(t){return t+" { ? }"}function K(t,e,i,s){return t+" ("+e+") {"+(s?Z(i,s):w.call(i,", "))+"}"}function Z(t,e){if(0===t.length)return"";var i="\n"+e.prev+e.base;return i+w.call(t,","+i)+"\n"+e.prev}function Q(t,e){var i=G(t),s=[];if(i){s.length=t.length;for(var r=0;r<t.length;r++)s[r]=H(t,r)?e(t[r],t):""}var n,o="function"==typeof T?T(t):[];if(I){n={};for(var a=0;a<o.length;a++)n["$"+o[a]]=o[a]}for(var l in t)H(t,l)&&(i&&String(Number(l))===l&&l<t.length||I&&n["$"+l]instanceof Symbol||(x.call(/[^\w$]/,l)?s.push(e(l,t)+": "+e(t[l],t)):s.push(l+": "+e(t[l],t))));if("function"==typeof T)for(var h=0;h<o.length;h++)C.call(t,o[h])&&s.push("["+e(o[h])+"]: "+e(t[o[h]],t));return s}return lu}function Hc(){if(cu)return uu;cu=1;var t=/* @__PURE__ */Yc(),e=/* @__PURE__ */ou(),i=function(t,e,i){for(var s,r=t;null!=(s=r.next);r=s)if(s.key===e)return r.next=s.next,i||(s.next=t.next,t.next=s),s};return uu=function(){var s,r={assert:function(i){if(!r.has(i))throw new e("Side channel does not contain "+t(i))},delete:function(t){var e=s&&s.next,r=function(t,e){if(t)return i(t,e,!0)}(s,t);return r&&e&&e===r&&(s=void 0),!!r},get:function(t){return function(t,e){if(t){var s=i(t,e);return s&&s.value}}(s,t)},has:function(t){return function(t,e){return!!t&&!!i(t,e)}(s,t)},set:function(t,e){s||(s={next:void 0}),function(t,e,s){var r=i(t,e);r?r.value=s:t.next={key:e,next:t.next,value:s}}(s,t,e)}};return r}}function $c(){return pu?du:(pu=1,du=Object)}function jc(){return mu?fu:(mu=1,fu=Error)}function zc(){return yu?gu:(yu=1,gu=EvalError)}function Vc(){return xu?vu:(xu=1,vu=RangeError)}function qc(){return wu?bu:(wu=1,bu=ReferenceError)}function Jc(){return Pu?_u:(Pu=1,_u=SyntaxError)}function Kc(){return Tu?Eu:(Tu=1,Eu=URIError)}function Zc(){return Iu?Au:(Iu=1,Au=Math.abs)}function Qc(){return Cu?Su:(Cu=1,Su=Math.floor)}function td(){return Ou?Mu:(Ou=1,Mu=Math.max)}function ed(){return Lu?Nu:(Lu=1,Nu=Math.min)}function id(){return Bu?Ru:(Bu=1,Ru=Math.pow)}function sd(){return Fu?ku:(Fu=1,ku=Math.round)}function rd(){return Uu?Du:(Uu=1,Du=Number.isNaN||function(t){return t!=t})}function nd(){if(Xu)return Gu;Xu=1;var t=/* @__PURE__ */rd();return Gu=function(e){return t(e)||0===e?e:e<0?-1:1}}function od(){return Yu?Wu:(Yu=1,Wu=Object.getOwnPropertyDescriptor)}function ad(){if($u)return Hu;$u=1;var t=/* @__PURE__ */od();if(t)try{t([],"length")}catch(e){t=null}return Hu=t}function ld(){if(zu)return ju;zu=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch(e){t=!1}return ju=t}function hd(){if(Ku)return Ju;Ku=1;var t="undefined"!=typeof Symbol&&Symbol,e=qu?Vu:(qu=1,Vu=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var t={},e=/* @__PURE__ */Symbol("test"),i=Object(e);if("string"==typeof e)return!1;if("[object Symbol]"!==Object.prototype.toString.call(e))return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;for(var s in t[e]=42,t)return!1;if("function"==typeof Object.keys&&0!==Object.keys(t).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(t).length)return!1;var r=Object.getOwnPropertySymbols(t);if(1!==r.length||r[0]!==e)return!1;if(!Object.prototype.propertyIsEnumerable.call(t,e))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var n=Object.getOwnPropertyDescriptor(t,e);if(42!==n.value||!0!==n.enumerable)return!1}return!0});return Ju=function(){return"function"==typeof t&&("function"==typeof Symbol&&("symbol"==typeof t("foo")&&("symbol"==typeof/* @__PURE__ */Symbol("bar")&&e())))}}function ud(){return Qu?Zu:(Qu=1,Zu="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function cd(){return ec?tc:(ec=1,tc=/* @__PURE__ */$c().getPrototypeOf||null)}function dd(){if(nc)return rc;nc=1;var t=function(){if(sc)return ic;sc=1;var t=Object.prototype.toString,e=Math.max,i=function(t,e){for(var i=[],s=0;s<t.length;s+=1)i[s]=t[s];for(var r=0;r<e.length;r+=1)i[r+t.length]=e[r];return i};return ic=function(s){var r=this;if("function"!=typeof r||"[object Function]"!==t.apply(r))throw new TypeError("Function.prototype.bind called on incompatible "+r);for(var n,o=function(t){for(var e=[],i=1,s=0;i<t.length;i+=1,s+=1)e[s]=t[i];return e}(arguments),a=e(0,r.length-o.length),l=[],h=0;h<a;h++)l[h]="$"+h;if(n=Function("binder","return function ("+function(t,e){for(var i="",s=0;s<t.length;s+=1)i+=t[s],s+1<t.length&&(i+=e);return i}(l,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof n){var t=r.apply(this,i(o,arguments));return Object(t)===t?t:this}return r.apply(s,i(o,arguments))}),r.prototype){var u=function(){};u.prototype=r.prototype,n.prototype=new u,u.prototype=null}return n},ic}();return rc=Function.prototype.bind||t}function pd(){return ac?oc:(ac=1,oc=Function.prototype.call)}function fd(){return hc?lc:(hc=1,lc=Function.prototype.apply)}function md(){if(pc)return dc;pc=1;var t=dd(),e=fd(),i=pd(),s=cc?uc:(cc=1,uc="undefined"!=typeof Reflect&&Reflect&&Reflect.apply);return dc=s||t.call(i,e)}function gd(){if(mc)return fc;mc=1;var t=dd(),e=/* @__PURE__ */ou(),i=pd(),s=md();return fc=function(r){if(r.length<1||"function"!=typeof r[0])throw new e("a function is required");return s(t,i,r)}}function yd(){if(yc)return gc;yc=1;var t,e=gd(),i=/* @__PURE__ */ad();try{t=[].__proto__===Array.prototype}catch(o){if(!o||"object"!=typeof o||!("code"in o)||"ERR_PROTO_ACCESS"!==o.code)throw o}var s=!!t&&i&&i(Object.prototype,"__proto__"),r=Object,n=r.getPrototypeOf;return gc=s&&"function"==typeof s.get?e([s.get]):"function"==typeof n&&function(t){return n(null==t?t:r(t))}}function vd(){if(wc)return bc;wc=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,i=dd();return bc=i.call(t,e)}function xd(){if(Pc)return _c;var t;Pc=1;var e=/* @__PURE__ */$c(),i=/* @__PURE__ */jc(),s=/* @__PURE__ */zc(),r=/* @__PURE__ */Vc(),n=/* @__PURE__ */qc(),o=/* @__PURE__ */Jc(),a=/* @__PURE__ */ou(),l=/* @__PURE__ */Kc(),h=/* @__PURE__ */Zc(),u=/* @__PURE__ */Qc(),c=/* @__PURE__ */td(),d=/* @__PURE__ */ed(),p=/* @__PURE__ */id(),f=/* @__PURE__ */sd(),m=/* @__PURE__ */nd(),g=Function,y=function(t){try{return g('"use strict"; return ('+t+").constructor;")()}catch(e){}},v=/* @__PURE__ */ad(),x=/* @__PURE__ */ld(),b=function(){throw new a},w=v?function(){try{return b}catch(t){try{return v(arguments,"callee").get}catch(e){return b}}}():b,_=hd()(),P=function(){if(xc)return vc;xc=1;var t=ud(),e=cd(),i=/* @__PURE__ */yd();return vc=t?function(e){return t(e)}:e?function(t){if(!t||"object"!=typeof t&&"function"!=typeof t)throw new TypeError("getProto: not an object");return e(t)}:i?function(t){return i(t)}:null}(),E=cd(),T=ud(),A=fd(),I=pd(),S={},C="undefined"!=typeof Uint8Array&&P?P(Uint8Array):t,M={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?t:ArrayBuffer,"%ArrayIteratorPrototype%":_&&P?P([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":S,"%AsyncGenerator%":S,"%AsyncGeneratorFunction%":S,"%AsyncIteratorPrototype%":S,"%Atomics%":"undefined"==typeof Atomics?t:Atomics,"%BigInt%":"undefined"==typeof BigInt?t:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?t:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":s,"%Float16Array%":"undefined"==typeof Float16Array?t:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?t:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?t:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?t:FinalizationRegistry,"%Function%":g,"%GeneratorFunction%":S,"%Int8Array%":"undefined"==typeof Int8Array?t:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?t:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":_&&P?P(P([][Symbol.iterator]())):t,"%JSON%":"object"==typeof JSON?JSON:t,"%Map%":"undefined"==typeof Map?t:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&_&&P?P(/* @__PURE__ */(new Map)[Symbol.iterator]()):t,"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":v,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?t:Promise,"%Proxy%":"undefined"==typeof Proxy?t:Proxy,"%RangeError%":r,"%ReferenceError%":n,"%Reflect%":"undefined"==typeof Reflect?t:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?t:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&_&&P?P(/* @__PURE__ */(new Set)[Symbol.iterator]()):t,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":_&&P?P(""[Symbol.iterator]()):t,"%Symbol%":_?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":w,"%TypedArray%":C,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?t:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?t:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?t:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?t:Uint32Array,"%URIError%":l,"%WeakMap%":"undefined"==typeof WeakMap?t:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?t:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?t:WeakSet,"%Function.prototype.call%":I,"%Function.prototype.apply%":A,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":h,"%Math.floor%":u,"%Math.max%":c,"%Math.min%":d,"%Math.pow%":p,"%Math.round%":f,"%Math.sign%":m,"%Reflect.getPrototypeOf%":T};if(P)try{null.error}catch(H){var O=P(P(H));M["%Error.prototype%"]=O}var N=function t(e){var i;if("%AsyncFunction%"===e)i=y("async function () {}");else if("%GeneratorFunction%"===e)i=y("function* () {}");else if("%AsyncGeneratorFunction%"===e)i=y("async function* () {}");else if("%AsyncGenerator%"===e){var s=t("%AsyncGeneratorFunction%");s&&(i=s.prototype)}else if("%AsyncIteratorPrototype%"===e){var r=t("%AsyncGenerator%");r&&P&&(i=P(r.prototype))}return M[e]=i,i},L={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},R=dd(),B=/* @__PURE__ */vd(),k=R.call(I,Array.prototype.concat),F=R.call(A,Array.prototype.splice),D=R.call(I,String.prototype.replace),U=R.call(I,String.prototype.slice),G=R.call(I,RegExp.prototype.exec),X=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,W=/\\(\\)?/g,Y=function(t,e){var i,s=t;if(B(L,s)&&(s="%"+(i=L[s])[0]+"%"),B(M,s)){var r=M[s];if(r===S&&(r=N(s)),void 0===r&&!e)throw new a("intrinsic "+t+" exists, but is not available. Please file an issue!");return{alias:i,name:s,value:r}}throw new o("intrinsic "+t+" does not exist!")};return _c=function(t,e){if("string"!=typeof t||0===t.length)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof e)throw new a('"allowMissing" argument must be a boolean');if(null===G(/^%?[^%]*%?$/,t))throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=function(t){var e=U(t,0,1),i=U(t,-1);if("%"===e&&"%"!==i)throw new o("invalid intrinsic syntax, expected closing `%`");if("%"===i&&"%"!==e)throw new o("invalid intrinsic syntax, expected opening `%`");var s=[];return D(t,X,function(t,e,i,r){s[s.length]=i?D(r,W,"$1"):e||t}),s}(t),s=i.length>0?i[0]:"",r=Y("%"+s+"%",e),n=r.name,l=r.value,h=!1,u=r.alias;u&&(s=u[0],F(i,k([0,1],u)));for(var c=1,d=!0;c<i.length;c+=1){var p=i[c],f=U(p,0,1),m=U(p,-1);if(('"'===f||"'"===f||"`"===f||'"'===m||"'"===m||"`"===m)&&f!==m)throw new o("property names with quotes must have matching quotes");if("constructor"!==p&&d||(h=!0),B(M,n="%"+(s+="."+p)+"%"))l=M[n];else if(null!=l){if(!(p in l)){if(!e)throw new a("base intrinsic for "+t+" exists, but the property is not available.");return}if(v&&c+1>=i.length){var g=v(l,p);l=(d=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:l[p]}else d=B(l,p),l=l[p];d&&!h&&(M[n]=l)}}return l},_c}function bd(){if(Tc)return Ec;Tc=1;var t=/* @__PURE__ */xd(),e=gd(),i=e([t("%String.prototype.indexOf%")]);return Ec=function(s,r){var n=t(s,!!r);return"function"==typeof n&&i(s,".prototype.")>-1?e([n]):n}}function wd(){if(Ic)return Ac;Ic=1;var t=/* @__PURE__ */xd(),e=/* @__PURE__ */bd(),i=/* @__PURE__ */Yc(),s=/* @__PURE__ */ou(),r=t("%Map%",!0),n=e("Map.prototype.get",!0),o=e("Map.prototype.set",!0),a=e("Map.prototype.has",!0),l=e("Map.prototype.delete",!0),h=e("Map.prototype.size",!0);return Ac=!!r&&function(){var t,e={assert:function(t){if(!e.has(t))throw new s("Side channel does not contain "+i(t))},delete:function(e){if(t){var i=l(t,e);return 0===h(t)&&(t=void 0),i}return!1},get:function(e){if(t)return n(t,e)},has:function(e){return!!t&&a(t,e)},set:function(e,i){t||(t=new r),o(t,e,i)}};return e}}function _d(){if(Oc)return Mc;Oc=1;var t=/* @__PURE__ */ou(),e=/* @__PURE__ */Yc(),i=Hc(),s=wd(),r=function(){if(Cc)return Sc;Cc=1;var t=/* @__PURE__ */xd(),e=/* @__PURE__ */bd(),i=/* @__PURE__ */Yc(),s=wd(),r=/* @__PURE__ */ou(),n=t("%WeakMap%",!0),o=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),h=e("WeakMap.prototype.delete",!0);return Sc=n?function(){var t,e,u={assert:function(t){if(!u.has(t))throw new r("Side channel does not contain "+i(t))},delete:function(i){if(n&&i&&("object"==typeof i||"function"==typeof i)){if(t)return h(t,i)}else if(s&&e)return e.delete(i);return!1},get:function(i){return n&&i&&("object"==typeof i||"function"==typeof i)&&t?o(t,i):e&&e.get(i)},has:function(i){return n&&i&&("object"==typeof i||"function"==typeof i)&&t?l(t,i):!!e&&e.has(i)},set:function(i,r){n&&i&&("object"==typeof i||"function"==typeof i)?(t||(t=new n),a(t,i,r)):s&&(e||(e=s()),e.set(i,r))}};return u}:s}(),n=r||s||i;return Mc=function(){var i,s={assert:function(i){if(!s.has(i))throw new t("Side channel does not contain "+e(i))},delete:function(t){return!!i&&i.delete(t)},get:function(t){return i&&i.get(t)},has:function(t){return!!i&&i.has(t)},set:function(t,e){i||(i=n()),i.set(t,e)}};return s}}function Pd(){if(Lc)return Nc;Lc=1;var t=String.prototype.replace,e=/%20/g,i="RFC3986";return Nc={default:i,formatters:{RFC1738:function(i){return t.call(i,e,"+")},RFC3986:function(t){return String(t)}},RFC1738:"RFC1738",RFC3986:i}}function Ed(){if(Bc)return Rc;Bc=1;var t=/* @__PURE__ */Pd(),e=Object.prototype.hasOwnProperty,i=Array.isArray,s=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),r=function(t,e){for(var i=e&&e.plainObjects?{__proto__:null}:{},s=0;s<t.length;++s)void 0!==t[s]&&(i[s]=t[s]);return i},n=1024;return Rc={arrayToObject:r,assign:function(t,e){return Object.keys(e).reduce(function(t,i){return t[i]=e[i],t},t)},combine:function(t,e){return[].concat(t,e)},compact:function(t){for(var e=[{obj:{o:t},prop:"o"}],s=[],r=0;r<e.length;++r)for(var n=e[r],o=n.obj[n.prop],a=Object.keys(o),l=0;l<a.length;++l){var h=a[l],u=o[h];"object"==typeof u&&null!==u&&-1===s.indexOf(u)&&(e.push({obj:o,prop:h}),s.push(u))}return function(t){for(;t.length>1;){var e=t.pop(),s=e.obj[e.prop];if(i(s)){for(var r=[],n=0;n<s.length;++n)void 0!==s[n]&&r.push(s[n]);e.obj[e.prop]=r}}}(e),t},decode:function(t,e,i){var s=t.replace(/\+/g," ");if("iso-8859-1"===i)return s.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(s)}catch(r){return s}},encode:function(e,i,r,o,a){if(0===e.length)return e;var l=e;if("symbol"==typeof e?l=Symbol.prototype.toString.call(e):"string"!=typeof e&&(l=String(e)),"iso-8859-1"===r)return escape(l).replace(/%u[0-9a-f]{4}/gi,function(t){return"%26%23"+parseInt(t.slice(2),16)+"%3B"});for(var h="",u=0;u<l.length;u+=n){for(var c=l.length>=n?l.slice(u,u+n):l,d=[],p=0;p<c.length;++p){var f=c.charCodeAt(p);45===f||46===f||95===f||126===f||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||a===t.RFC1738&&(40===f||41===f)?d[d.length]=c.charAt(p):f<128?d[d.length]=s[f]:f<2048?d[d.length]=s[192|f>>6]+s[128|63&f]:f<55296||f>=57344?d[d.length]=s[224|f>>12]+s[128|f>>6&63]+s[128|63&f]:(p+=1,f=65536+((1023&f)<<10|1023&c.charCodeAt(p)),d[d.length]=s[240|f>>18]+s[128|f>>12&63]+s[128|f>>6&63]+s[128|63&f])}h+=d.join("")}return h},isBuffer:function(t){return!(!t||"object"!=typeof t)&&!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))},isRegExp:function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},maybeMap:function(t,e){if(i(t)){for(var s=[],r=0;r<t.length;r+=1)s.push(e(t[r]));return s}return e(t)},merge:function t(s,n,o){if(!n)return s;if("object"!=typeof n&&"function"!=typeof n){if(i(s))s.push(n);else{if(!s||"object"!=typeof s)return[s,n];(o&&(o.plainObjects||o.allowPrototypes)||!e.call(Object.prototype,n))&&(s[n]=!0)}return s}if(!s||"object"!=typeof s)return[s].concat(n);var a=s;return i(s)&&!i(n)&&(a=r(s,o)),i(s)&&i(n)?(n.forEach(function(i,r){if(e.call(s,r)){var n=s[r];n&&"object"==typeof n&&i&&"object"==typeof i?s[r]=t(n,i,o):s.push(i)}else s[r]=i}),s):Object.keys(n).reduce(function(i,s){var r=n[s];return e.call(i,s)?i[s]=t(i[s],r,o):i[s]=r,i},a)}},Rc}function Td(){if(Fc)return kc;Fc=1;var t=_d(),e=/* @__PURE__ */Ed(),i=/* @__PURE__ */Pd(),s=Object.prototype.hasOwnProperty,r={brackets:function(t){return t+"[]"},comma:"comma",indices:function(t,e){return t+"["+e+"]"},repeat:function(t){return t}},n=Array.isArray,o=Array.prototype.push,a=function(t,e){o.apply(t,n(e)?e:[e])},l=Date.prototype.toISOString,h=i.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,filter:void 0,format:h,formatter:i.formatters[h],indices:!1,serializeDate:function(t){return l.call(t)},skipNulls:!1,strictNullHandling:!1},c={},d=function i(s,r,o,l,h,d,p,f,m,g,y,v,x,b,w,_,P,E){for(var T,A=s,I=E,S=0,C=!1;void 0!==(I=I.get(c))&&!C;){var M=I.get(s);if(S+=1,void 0!==M){if(M===S)throw new RangeError("Cyclic object value");C=!0}void 0===I.get(c)&&(S=0)}if("function"==typeof g?A=g(r,A):A instanceof Date?A=x(A):"comma"===o&&n(A)&&(A=e.maybeMap(A,function(t){return t instanceof Date?x(t):t})),null===A){if(d)return m&&!_?m(r,u.encoder,P,"key",b):r;A=""}if("string"==typeof(T=A)||"number"==typeof T||"boolean"==typeof T||"symbol"==typeof T||"bigint"==typeof T||e.isBuffer(A))return m?[w(_?r:m(r,u.encoder,P,"key",b))+"="+w(m(A,u.encoder,P,"value",b))]:[w(r)+"="+w(String(A))];var O,N=[];if(void 0===A)return N;if("comma"===o&&n(A))_&&m&&(A=e.maybeMap(A,m)),O=[{value:A.length>0?A.join(",")||null:void 0}];else if(n(g))O=g;else{var L=Object.keys(A);O=y?L.sort(y):L}var R=f?String(r).replace(/\./g,"%2E"):String(r),B=l&&n(A)&&1===A.length?R+"[]":R;if(h&&n(A)&&0===A.length)return B+"[]";for(var k=0;k<O.length;++k){var F=O[k],D="object"==typeof F&&F&&void 0!==F.value?F.value:A[F];if(!p||null!==D){var U=v&&f?String(F).replace(/\./g,"%2E"):String(F),G=n(A)?"function"==typeof o?o(B,U):B:B+(v?"."+U:"["+U+"]");E.set(s,S);var X=t();X.set(c,E),a(N,i(D,G,o,l,h,d,p,f,"comma"===o&&_&&n(A)?null:m,g,y,v,x,b,w,_,P,X))}}return N};return kc=function(e,o){var l,h=e,c=function(t){if(!t)return u;if(void 0!==t.allowEmptyArrays&&"boolean"!=typeof t.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==t.encodeDotInKeys&&"boolean"!=typeof t.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==t.encoder&&void 0!==t.encoder&&"function"!=typeof t.encoder)throw new TypeError("Encoder has to be a function.");var e=t.charset||u.charset;if(void 0!==t.charset&&"utf-8"!==t.charset&&"iso-8859-1"!==t.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var o=i.default;if(void 0!==t.format){if(!s.call(i.formatters,t.format))throw new TypeError("Unknown format option provided.");o=t.format}var a,l=i.formatters[o],h=u.filter;if(("function"==typeof t.filter||n(t.filter))&&(h=t.filter),a=t.arrayFormat in r?t.arrayFormat:"indices"in t?t.indices?"indices":"repeat":u.arrayFormat,"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var c=void 0===t.allowDots?!0===t.encodeDotInKeys||u.allowDots:!!t.allowDots;return{addQueryPrefix:"boolean"==typeof t.addQueryPrefix?t.addQueryPrefix:u.addQueryPrefix,allowDots:c,allowEmptyArrays:"boolean"==typeof t.allowEmptyArrays?!!t.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:"boolean"==typeof t.charsetSentinel?t.charsetSentinel:u.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:void 0===t.delimiter?u.delimiter:t.delimiter,encode:"boolean"==typeof t.encode?t.encode:u.encode,encodeDotInKeys:"boolean"==typeof t.encodeDotInKeys?t.encodeDotInKeys:u.encodeDotInKeys,encoder:"function"==typeof t.encoder?t.encoder:u.encoder,encodeValuesOnly:"boolean"==typeof t.encodeValuesOnly?t.encodeValuesOnly:u.encodeValuesOnly,filter:h,format:o,formatter:l,serializeDate:"function"==typeof t.serializeDate?t.serializeDate:u.serializeDate,skipNulls:"boolean"==typeof t.skipNulls?t.skipNulls:u.skipNulls,sort:"function"==typeof t.sort?t.sort:null,strictNullHandling:"boolean"==typeof t.strictNullHandling?t.strictNullHandling:u.strictNullHandling}}(o);"function"==typeof c.filter?h=(0,c.filter)("",h):n(c.filter)&&(l=c.filter);var p=[];if("object"!=typeof h||null===h)return"";var f=r[c.arrayFormat],m="comma"===f&&c.commaRoundTrip;l||(l=Object.keys(h)),c.sort&&l.sort(c.sort);for(var g=t(),y=0;y<l.length;++y){var v=l[y],x=h[v];c.skipNulls&&null===x||a(p,d(x,v,f,m,c.allowEmptyArrays,c.strictNullHandling,c.skipNulls,c.encodeDotInKeys,c.encode?c.encoder:null,c.filter,c.sort,c.allowDots,c.serializeDate,c.format,c.formatter,c.encodeValuesOnly,c.charset,g))}var b=p.join(c.delimiter),w=!0===c.addQueryPrefix?"?":"";return c.charsetSentinel&&("iso-8859-1"===c.charset?w+="utf8=%26%2310003%3B&":w+="utf8=%E2%9C%93&"),b.length>0?w+b:""}}function Ad(){if(Uc)return Dc;Uc=1;var t=/* @__PURE__ */Ed(),e=Object.prototype.hasOwnProperty,i=Array.isArray,s={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:t.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1,throwOnLimitExceeded:!1},r=function(t){return t.replace(/&#(\d+);/g,function(t,e){return String.fromCharCode(parseInt(e,10))})},n=function(t,e,i){if(t&&"string"==typeof t&&e.comma&&t.indexOf(",")>-1)return t.split(",");if(e.throwOnLimitExceeded&&i>=e.arrayLimit)throw new RangeError("Array limit exceeded. Only "+e.arrayLimit+" element"+(1===e.arrayLimit?"":"s")+" allowed in an array.");return t},o=function(i,s,r,o){if(i){var a=r.allowDots?i.replace(/\.([^.[]+)/g,"[$1]"):i,l=/(\[[^[\]]*])/g,h=r.depth>0&&/(\[[^[\]]*])/.exec(a),u=h?a.slice(0,h.index):a,c=[];if(u){if(!r.plainObjects&&e.call(Object.prototype,u)&&!r.allowPrototypes)return;c.push(u)}for(var d=0;r.depth>0&&null!==(h=l.exec(a))&&d<r.depth;){if(d+=1,!r.plainObjects&&e.call(Object.prototype,h[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(h[1])}if(h){if(!0===r.strictDepth)throw new RangeError("Input depth exceeded depth option of "+r.depth+" and strictDepth is true");c.push("["+a.slice(h.index)+"]")}return function(e,i,s,r){var o=0;if(e.length>0&&"[]"===e[e.length-1]){var a=e.slice(0,-1).join("");o=Array.isArray(i)&&i[a]?i[a].length:0}for(var l=r?i:n(i,s,o),h=e.length-1;h>=0;--h){var u,c=e[h];if("[]"===c&&s.parseArrays)u=s.allowEmptyArrays&&(""===l||s.strictNullHandling&&null===l)?[]:t.combine([],l);else{u=s.plainObjects?{__proto__:null}:{};var d="["===c.charAt(0)&&"]"===c.charAt(c.length-1)?c.slice(1,-1):c,p=s.decodeDotInKeys?d.replace(/%2E/g,"."):d,f=parseInt(p,10);s.parseArrays||""!==p?!isNaN(f)&&c!==p&&String(f)===p&&f>=0&&s.parseArrays&&f<=s.arrayLimit?(u=[])[f]=l:"__proto__"!==p&&(u[p]=l):u={0:l}}l=u}return l}(c,s,r,o)}};return Dc=function(a,l){var h=function(e){if(!e)return s;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.decodeDotInKeys&&"boolean"!=typeof e.decodeDotInKeys)throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(void 0!==e.throwOnLimitExceeded&&"boolean"!=typeof e.throwOnLimitExceeded)throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var i=void 0===e.charset?s.charset:e.charset,r=void 0===e.duplicates?s.duplicates:e.duplicates;if("combine"!==r&&"first"!==r&&"last"!==r)throw new TypeError("The duplicates option must be either combine, first, or last");return{allowDots:void 0===e.allowDots?!0===e.decodeDotInKeys||s.allowDots:!!e.allowDots,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:s.allowEmptyArrays,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:s.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:s.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:s.arrayLimit,charset:i,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:s.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:s.comma,decodeDotInKeys:"boolean"==typeof e.decodeDotInKeys?e.decodeDotInKeys:s.decodeDotInKeys,decoder:"function"==typeof e.decoder?e.decoder:s.decoder,delimiter:"string"==typeof e.delimiter||t.isRegExp(e.delimiter)?e.delimiter:s.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:s.depth,duplicates:r,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:s.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:s.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:s.plainObjects,strictDepth:"boolean"==typeof e.strictDepth?!!e.strictDepth:s.strictDepth,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:s.strictNullHandling,throwOnLimitExceeded:"boolean"==typeof e.throwOnLimitExceeded&&e.throwOnLimitExceeded}}(l);if(""===a||null==a)return h.plainObjects?{__proto__:null}:{};for(var u="string"==typeof a?function(o,a){var l={__proto__:null},h=a.ignoreQueryPrefix?o.replace(/^\?/,""):o;h=h.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var u=a.parameterLimit===1/0?void 0:a.parameterLimit,c=h.split(a.delimiter,a.throwOnLimitExceeded?u+1:u);if(a.throwOnLimitExceeded&&c.length>u)throw new RangeError("Parameter limit exceeded. Only "+u+" parameter"+(1===u?"":"s")+" allowed.");var d,p=-1,f=a.charset;if(a.charsetSentinel)for(d=0;d<c.length;++d)0===c[d].indexOf("utf8=")&&("utf8=%E2%9C%93"===c[d]?f="utf-8":"utf8=%26%2310003%3B"===c[d]&&(f="iso-8859-1"),p=d,d=c.length);for(d=0;d<c.length;++d)if(d!==p){var m,g,y=c[d],v=y.indexOf("]="),x=-1===v?y.indexOf("="):v+1;-1===x?(m=a.decoder(y,s.decoder,f,"key"),g=a.strictNullHandling?null:""):(m=a.decoder(y.slice(0,x),s.decoder,f,"key"),g=t.maybeMap(n(y.slice(x+1),a,i(l[m])?l[m].length:0),function(t){return a.decoder(t,s.decoder,f,"value")})),g&&a.interpretNumericEntities&&"iso-8859-1"===f&&(g=r(String(g))),y.indexOf("[]=")>-1&&(g=i(g)?[g]:g);var b=e.call(l,m);b&&"combine"===a.duplicates?l[m]=t.combine(l[m],g):b&&"last"!==a.duplicates||(l[m]=g)}return l}(a,h):a,c=h.plainObjects?{__proto__:null}:{},d=Object.keys(u),p=0;p<d.length;++p){var f=d[p],m=o(f,u[f],h,"string"==typeof a);c=t.merge(c,m,h)}return!0===h.allowSparse?c:t.compact(c)}}function Id(){if(Xc)return Gc;Xc=1;var t=/* @__PURE__ */Td(),e=/* @__PURE__ */Ad();return Gc={formats:/* @__PURE__ */Pd(),parse:e,stringify:t}}var Sd=function(){if(Wc)return su;Wc=1;var t=(tu||(tu=1,function(t,e){!function(i){var s=e&&!e.nodeType&&e,r=t&&!t.nodeType&&t,n="object"==typeof At&&At;n.global!==n&&n.window!==n&&n.self!==n||(i=n);var o,a,l=2147483647,h=36,u=/^xn--/,c=/[^\x20-\x7E]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,m=String.fromCharCode;function g(t){throw new RangeError(p[t])}function y(t,e){for(var i=t.length,s=[];i--;)s[i]=e(t[i]);return s}function v(t,e){var i=t.split("@"),s="";return i.length>1&&(s=i[0]+"@",t=i[1]),s+y((t=t.replace(d,".")).split("."),e).join(".")}function x(t){for(var e,i,s=[],r=0,n=t.length;r<n;)(e=t.charCodeAt(r++))>=55296&&e<=56319&&r<n?56320==(64512&(i=t.charCodeAt(r++)))?s.push(((1023&e)<<10)+(1023&i)+65536):(s.push(e),r--):s.push(e);return s}function b(t){return y(t,function(t){var e="";return t>65535&&(e+=m((t-=65536)>>>10&1023|55296),t=56320|1023&t),e+m(t)}).join("")}function w(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:h}function _(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function P(t,e,i){var s=0;for(t=i?f(t/700):t>>1,t+=f(t/e);t>455;s+=h)t=f(t/35);return f(s+36*t/(t+38))}function E(t){var e,i,s,r,n,o,a,u,c,d,p=[],m=t.length,y=0,v=128,x=72;for((i=t.lastIndexOf("-"))<0&&(i=0),s=0;s<i;++s)t.charCodeAt(s)>=128&&g("not-basic"),p.push(t.charCodeAt(s));for(r=i>0?i+1:0;r<m;){for(n=y,o=1,a=h;r>=m&&g("invalid-input"),((u=w(t.charCodeAt(r++)))>=h||u>f((l-y)/o))&&g("overflow"),y+=u*o,!(u<(c=a<=x?1:a>=x+26?26:a-x));a+=h)o>f(l/(d=h-c))&&g("overflow"),o*=d;x=P(y-n,e=p.length+1,0==n),f(y/e)>l-v&&g("overflow"),v+=f(y/e),y%=e,p.splice(y++,0,v)}return b(p)}function T(t){var e,i,s,r,n,o,a,u,c,d,p,y,v,b,w,E=[];for(y=(t=x(t)).length,e=128,i=0,n=72,o=0;o<y;++o)(p=t[o])<128&&E.push(m(p));for(s=r=E.length,r&&E.push("-");s<y;){for(a=l,o=0;o<y;++o)(p=t[o])>=e&&p<a&&(a=p);for(a-e>f((l-i)/(v=s+1))&&g("overflow"),i+=(a-e)*v,e=a,o=0;o<y;++o)if((p=t[o])<e&&++i>l&&g("overflow"),p==e){for(u=i,c=h;!(u<(d=c<=n?1:c>=n+26?26:c-n));c+=h)w=u-d,b=h-d,E.push(m(_(d+w%b,0))),u=f(w/b);E.push(m(_(u,0))),n=P(i,v,s==r),i=0,++s}++i,++e}return E.join("")}if(o={version:"1.4.1",ucs2:{decode:x,encode:b},decode:E,encode:T,toASCII:function(t){return v(t,function(t){return c.test(t)?"xn--"+T(t):t})},toUnicode:function(t){return v(t,function(t){return u.test(t)?E(t.slice(4).toLowerCase()):t})}},s&&r)if(t.exports==s)r.exports=o;else for(a in o)o.hasOwnProperty(a)&&(s[a]=o[a]);else i.punycode=o}(nu)}(ru,ru.exports)),ru.exports);function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var i=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,r=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),o=["'"].concat(n),a=["%","/","?",";","#"].concat(o),l=["/","?","#"],h=/^[+a-z0-9A-Z_-]{0,63}$/,u=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,c={javascript:!0,"javascript:":!0},d={javascript:!0,"javascript:":!0},p={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},f=/* @__PURE__ */Id();function m(t,i,s){if(t&&"object"==typeof t&&t instanceof e)return t;var r=new e;return r.parse(t,i,s),r}return e.prototype.parse=function(e,s,n){if("string"!=typeof e)throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var m=e.indexOf("?"),g=-1!==m&&m<e.indexOf("#")?"?":"#",y=e.split(g);y[0]=y[0].replace(/\\/g,"/");var v=e=y.join(g);if(v=v.trim(),!n&&1===e.split("#").length){var x=r.exec(v);if(x)return this.path=v,this.href=v,this.pathname=x[1],x[2]?(this.search=x[2],this.query=s?f.parse(this.search.substr(1)):this.search.substr(1)):s&&(this.search="",this.query={}),this}var b=i.exec(v);if(b){var w=(b=b[0]).toLowerCase();this.protocol=w,v=v.substr(b.length)}if(n||b||v.match(/^\/\/[^@/]+@[^@/]+/)){var _="//"===v.substr(0,2);!_||b&&d[b]||(v=v.substr(2),this.slashes=!0)}if(!d[b]&&(_||b&&!p[b])){for(var P,E,T=-1,A=0;A<l.length;A++){-1!==(I=v.indexOf(l[A]))&&(-1===T||I<T)&&(T=I)}-1!==(E=-1===T?v.lastIndexOf("@"):v.lastIndexOf("@",T))&&(P=v.slice(0,E),v=v.slice(E+1),this.auth=decodeURIComponent(P)),T=-1;for(A=0;A<a.length;A++){var I;-1!==(I=v.indexOf(a[A]))&&(-1===T||I<T)&&(T=I)}-1===T&&(T=v.length),this.host=v.slice(0,T),v=v.slice(T),this.parseHost(),this.hostname=this.hostname||"";var S="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!S)for(var C=this.hostname.split(/\./),M=(A=0,C.length);A<M;A++){var O=C[A];if(O&&!O.match(h)){for(var N="",L=0,R=O.length;L<R;L++)O.charCodeAt(L)>127?N+="x":N+=O[L];if(!N.match(h)){var B=C.slice(0,A),k=C.slice(A+1),F=O.match(u);F&&(B.push(F[1]),k.unshift(F[2])),k.length&&(v="/"+k.join(".")+v),this.hostname=B.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),S||(this.hostname=t.toASCII(this.hostname));var D=this.port?":"+this.port:"",U=this.hostname||"";this.host=U+D,this.href+=this.host,S&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==v[0]&&(v="/"+v))}if(!c[w])for(A=0,M=o.length;A<M;A++){var G=o[A];if(-1!==v.indexOf(G)){var X=encodeURIComponent(G);X===G&&(X=escape(G)),v=v.split(G).join(X)}}var W=v.indexOf("#");-1!==W&&(this.hash=v.substr(W),v=v.slice(0,W));var Y=v.indexOf("?");if(-1!==Y?(this.search=v.substr(Y),this.query=v.substr(Y+1),s&&(this.query=f.parse(this.query)),v=v.slice(0,Y)):s&&(this.search="",this.query={}),v&&(this.pathname=v),p[w]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){D=this.pathname||"";var H=this.search||"";this.path=D+H}return this.href=this.format(),this},e.prototype.format=function(){var t=this.auth||"";t&&(t=(t=encodeURIComponent(t)).replace(/%3A/i,":"),t+="@");var e=this.protocol||"",i=this.pathname||"",s=this.hash||"",r=!1,n="";this.host?r=t+this.host:this.hostname&&(r=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(r+=":"+this.port)),this.query&&"object"==typeof this.query&&Object.keys(this.query).length&&(n=f.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var o=this.search||n&&"?"+n||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||p[e])&&!1!==r?(r="//"+(r||""),i&&"/"!==i.charAt(0)&&(i="/"+i)):r||(r=""),s&&"#"!==s.charAt(0)&&(s="#"+s),o&&"?"!==o.charAt(0)&&(o="?"+o),e+r+(i=i.replace(/[?#]/g,function(t){return encodeURIComponent(t)}))+(o=o.replace("#","%23"))+s},e.prototype.resolve=function(t){return this.resolveObject(m(t,!1,!0)).format()},e.prototype.resolveObject=function(t){if("string"==typeof t){var i=new e;i.parse(t,!1,!0),t=i}for(var s=new e,r=Object.keys(this),n=0;n<r.length;n++){var o=r[n];s[o]=this[o]}if(s.hash=t.hash,""===t.href)return s.href=s.format(),s;if(t.slashes&&!t.protocol){for(var a=Object.keys(t),l=0;l<a.length;l++){var h=a[l];"protocol"!==h&&(s[h]=t[h])}return p[s.protocol]&&s.hostname&&!s.pathname&&(s.pathname="/",s.path=s.pathname),s.href=s.format(),s}if(t.protocol&&t.protocol!==s.protocol){if(!p[t.protocol]){for(var u=Object.keys(t),c=0;c<u.length;c++){var f=u[c];s[f]=t[f]}return s.href=s.format(),s}if(s.protocol=t.protocol,t.host||d[t.protocol])s.pathname=t.pathname;else{for(var m=(t.pathname||"").split("/");m.length&&!(t.host=m.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==m[0]&&m.unshift(""),m.length<2&&m.unshift(""),s.pathname=m.join("/")}if(s.search=t.search,s.query=t.query,s.host=t.host||"",s.auth=t.auth,s.hostname=t.hostname||t.host,s.port=t.port,s.pathname||s.search){var g=s.pathname||"",y=s.search||"";s.path=g+y}return s.slashes=s.slashes||t.slashes,s.href=s.format(),s}var v=s.pathname&&"/"===s.pathname.charAt(0),x=t.host||t.pathname&&"/"===t.pathname.charAt(0),b=x||v||s.host&&t.pathname,w=b,_=s.pathname&&s.pathname.split("/")||[],P=(m=t.pathname&&t.pathname.split("/")||[],s.protocol&&!p[s.protocol]);if(P&&(s.hostname="",s.port=null,s.host&&(""===_[0]?_[0]=s.host:_.unshift(s.host)),s.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===m[0]?m[0]=t.host:m.unshift(t.host)),t.host=null),b=b&&(""===m[0]||""===_[0])),x)s.host=t.host||""===t.host?t.host:s.host,s.hostname=t.hostname||""===t.hostname?t.hostname:s.hostname,s.search=t.search,s.query=t.query,_=m;else if(m.length)_||(_=[]),_.pop(),_=_.concat(m),s.search=t.search,s.query=t.query;else if(null!=t.search){if(P)s.host=_.shift(),s.hostname=s.host,(S=!!(s.host&&s.host.indexOf("@")>0)&&s.host.split("@"))&&(s.auth=S.shift(),s.hostname=S.shift(),s.host=s.hostname);return s.search=t.search,s.query=t.query,null===s.pathname&&null===s.search||(s.path=(s.pathname?s.pathname:"")+(s.search?s.search:"")),s.href=s.format(),s}if(!_.length)return s.pathname=null,s.search?s.path="/"+s.search:s.path=null,s.href=s.format(),s;for(var E=_.slice(-1)[0],T=(s.host||t.host||_.length>1)&&("."===E||".."===E)||""===E,A=0,I=_.length;I>=0;I--)"."===(E=_[I])?_.splice(I,1):".."===E?(_.splice(I,1),A++):A&&(_.splice(I,1),A--);if(!b&&!w)for(;A--;A)_.unshift("..");!b||""===_[0]||_[0]&&"/"===_[0].charAt(0)||_.unshift(""),T&&"/"!==_.join("/").substr(-1)&&_.push("");var S,C=""===_[0]||_[0]&&"/"===_[0].charAt(0);P&&(s.hostname=C?"":_.length?_.shift():"",s.host=s.hostname,(S=!!(s.host&&s.host.indexOf("@")>0)&&s.host.split("@"))&&(s.auth=S.shift(),s.hostname=S.shift(),s.host=s.hostname));return(b=b||s.host&&_.length)&&!C&&_.unshift(""),_.length>0?s.pathname=_.join("/"):(s.pathname=null,s.path=null),null===s.pathname&&null===s.search||(s.path=(s.pathname?s.pathname:"")+(s.search?s.search:"")),s.auth=t.auth||s.auth,s.slashes=s.slashes||t.slashes,s.href=s.format(),s},e.prototype.parseHost=function(){var t=this.host,e=s.exec(t);e&&(":"!==(e=e[0])&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)},su.parse=m,su.resolve=function(t,e){return m(t,!1,!0).resolve(e)},su.resolveObject=function(t,e){return t?m(t,!1,!0).resolveObject(e):e},su.format=function(t){return"string"==typeof t&&(t=m(t)),t instanceof e?t.format():e.prototype.format.call(t)},su.Url=e,su}();const Cd={};function Md(t,e,i=3){if(Cd[e])return;let s=(new Error).stack;typeof s>"u"?console.warn("PixiJS Deprecation Warning: ",`${e}\nDeprecated since v${t}`):(s=s.split("\n").splice(i).join("\n"),console.groupCollapsed?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",`${e}\nDeprecated since v${t}`),console.warn(s),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",`${e}\nDeprecated since v${t}`),console.warn(s))),Cd[e]=!0}const Od={get parse(){return Md("7.3.0","utils.url.parse is deprecated, use native URL API instead."),Sd.parse},get format(){return Md("7.3.0","utils.url.format is deprecated, use native URL API instead."),Sd.format},get resolve(){return Md("7.3.0","utils.url.resolve is deprecated, use native URL API instead."),Sd.resolve}};function Nd(t){if("string"!=typeof t)throw new TypeError(`Path must be a string. Received ${JSON.stringify(t)}`)}function Ld(t){return t.split("?")[0].split("#")[0]}const Rd={toPosix(t){return e="\\",i="/",t.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),i);var e,i},isUrl(t){return/^https?:/.test(this.toPosix(t))},isDataUrl:t=>/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(t),isBlobUrl:t=>t.startsWith("blob:"),hasProtocol(t){return/^[^/:]+:/.test(this.toPosix(t))},getProtocol(t){Nd(t),t=this.toPosix(t);const e=/^file:\/\/\//.exec(t);if(e)return e[0];const i=/^[^/:]+:\/{0,2}/.exec(t);return i?i[0]:""},toAbsolute(t,e,i){if(Nd(t),this.isDataUrl(t)||this.isBlobUrl(t))return t;const s=Ld(this.toPosix(e??Oh.ADAPTER.getBaseUrl())),r=Ld(this.toPosix(i??this.rootname(s)));return(t=this.toPosix(t)).startsWith("/")?Rd.join(r,t.slice(1)):this.isAbsolute(t)?t:this.join(s,t)},normalize(t){if(Nd(t),0===t.length)return".";if(this.isDataUrl(t)||this.isBlobUrl(t))return t;let e="";const i=(t=this.toPosix(t)).startsWith("/");this.hasProtocol(t)&&(e=this.rootname(t),t=t.slice(e.length));const s=t.endsWith("/");return(t=function(t){let e="",i=0,s=-1,r=0,n=-1;for(let o=0;o<=t.length;++o){if(o<t.length)n=t.charCodeAt(o);else{if(47===n)break;n=47}if(47===n){if(s!==o-1&&1!==r)if(s!==o-1&&2===r){if(e.length<2||2!==i||46!==e.charCodeAt(e.length-1)||46!==e.charCodeAt(e.length-2))if(e.length>2){const t=e.lastIndexOf("/");if(t!==e.length-1){-1===t?(e="",i=0):(e=e.slice(0,t),i=e.length-1-e.lastIndexOf("/")),s=o,r=0;continue}}else if(2===e.length||1===e.length){e="",i=0,s=o,r=0;continue}}else e.length>0?e+=`/${t.slice(s+1,o)}`:e=t.slice(s+1,o),i=o-s-1;s=o,r=0}else 46===n&&-1!==r?++r:r=-1}return e}(t)).length>0&&s&&(t+="/"),i?`/${t}`:e+t},isAbsolute(t){return Nd(t),t=this.toPosix(t),!!this.hasProtocol(t)||t.startsWith("/")},join(...t){if(0===t.length)return".";let e;for(let i=0;i<t.length;++i){const s=t[i];if(Nd(s),s.length>0)if(void 0===e)e=s;else{const r=t[i-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?e+=`/../${s}`:e+=`/${s}`}}return void 0===e?".":this.normalize(e)},dirname(t){if(Nd(t),0===t.length)return".";let e=(t=this.toPosix(t)).charCodeAt(0);const i=47===e;let s=-1,r=!0;const n=this.getProtocol(t),o=t;for(let a=(t=t.slice(n.length)).length-1;a>=1;--a)if(e=t.charCodeAt(a),47===e){if(!r){s=a;break}}else r=!1;return-1===s?i?"/":this.isUrl(o)?n+t:n:i&&1===s?"//":n+t.slice(0,s)},rootname(t){Nd(t);let e="";if(e=(t=this.toPosix(t)).startsWith("/")?"/":this.getProtocol(t),this.isUrl(t)){const i=t.indexOf("/",e.length);e=-1!==i?t.slice(0,i):t,e.endsWith("/")||(e+="/")}return e},basename(t,e){Nd(t),e&&Nd(e),t=Ld(this.toPosix(t));let i,s=0,r=-1,n=!0;if(void 0!==e&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";let o=e.length-1,a=-1;for(i=t.length-1;i>=0;--i){const l=t.charCodeAt(i);if(47===l){if(!n){s=i+1;break}}else-1===a&&(n=!1,a=i+1),o>=0&&(l===e.charCodeAt(o)?-1===--o&&(r=i):(o=-1,r=a))}return s===r?r=a:-1===r&&(r=t.length),t.slice(s,r)}for(i=t.length-1;i>=0;--i)if(47===t.charCodeAt(i)){if(!n){s=i+1;break}}else-1===r&&(n=!1,r=i+1);return-1===r?"":t.slice(s,r)},extname(t){Nd(t);let e=-1,i=0,s=-1,r=!0,n=0;for(let o=(t=Ld(this.toPosix(t))).length-1;o>=0;--o){const a=t.charCodeAt(o);if(47!==a)-1===s&&(r=!1,s=o+1),46===a?-1===e?e=o:1!==n&&(n=1):-1!==e&&(n=-1);else if(!r){i=o+1;break}}return-1===e||-1===s||0===n||1===n&&e===s-1&&e===i+1?"":t.slice(e,s)},parse(t){Nd(t);const e={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return e;let i=(t=Ld(this.toPosix(t))).charCodeAt(0);const s=this.isAbsolute(t);let r;e.root=this.rootname(t),r=s||this.hasProtocol(t)?1:0;let n=-1,o=0,a=-1,l=!0,h=t.length-1,u=0;for(;h>=r;--h)if(i=t.charCodeAt(h),47!==i)-1===a&&(l=!1,a=h+1),46===i?-1===n?n=h:1!==u&&(u=1):-1!==n&&(u=-1);else if(!l){o=h+1;break}return-1===n||-1===a||0===u||1===u&&n===a-1&&n===o+1?-1!==a&&(e.base=e.name=0===o&&s?t.slice(1,a):t.slice(o,a)):(0===o&&s?(e.name=t.slice(1,n),e.base=t.slice(1,a)):(e.name=t.slice(o,n),e.base=t.slice(o,a)),e.ext=t.slice(n,a)),e.dir=this.dirname(t),e},sep:"/",delimiter:":",joinExtensions:[".html"]};let Bd,kd;function Fd(){return typeof kd>"u"&&(kd=function(){const t={stencil:!0,failIfMajorPerformanceCaveat:Oh.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT};try{if(!Oh.ADAPTER.getWebGLRenderingContext())return!1;const e=Oh.ADAPTER.createCanvas();let i=e.getContext("webgl",t)||e.getContext("experimental-webgl",t);const s=!!i?.getContextAttributes()?.stencil;if(i){const t=i.getExtension("WEBGL_lose_context");t&&t.loseContext()}return i=null,s}catch{return!1}}()),kd}var Dd,Ud={grad:.9,turn:360,rad:360/(2*Math.PI)},Gd=function(t){return"string"==typeof t?t.length>0:"number"==typeof t},Xd=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=Math.pow(10,e)),Math.round(i*t)/i+0},Wd=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=1),t>i?i:t>e?t:e},Yd=function(t){return(t=isFinite(t)?t%360:0)>0?t:t+360},Hd=function(t){return{r:Wd(t.r,0,255),g:Wd(t.g,0,255),b:Wd(t.b,0,255),a:Wd(t.a)}},$d=function(t){return{r:Xd(t.r),g:Xd(t.g),b:Xd(t.b),a:Xd(t.a,3)}},jd=/^#([0-9a-f]{3,8})$/i,zd=function(t){var e=t.toString(16);return e.length<2?"0"+e:e},Vd=function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=Math.max(e,i,s),o=n-Math.min(e,i,s),a=o?n===e?(i-s)/o:n===i?2+(s-e)/o:4+(e-i)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},qd=function(t){var e=t.h,i=t.s,s=t.v,r=t.a;e=e/360*6,i/=100,s/=100;var n=Math.floor(e),o=s*(1-i),a=s*(1-(e-n)*i),l=s*(1-(1-e+n)*i),h=n%6;return{r:255*[s,a,o,o,l,s][h],g:255*[l,s,s,a,o,o][h],b:255*[o,o,l,s,s,a][h],a:r}},Jd=function(t){return{h:Yd(t.h),s:Wd(t.s,0,100),l:Wd(t.l,0,100),a:Wd(t.a)}},Kd=function(t){return{h:Xd(t.h),s:Xd(t.s),l:Xd(t.l),a:Xd(t.a,3)}},Zd=function(t){return qd((i=(e=t).s,{h:e.h,s:(i*=((s=e.l)<50?s:100-s)/100)>0?2*i/(s+i)*100:0,v:s+i,a:e.a}));var e,i,s},Qd=function(t){return{h:(e=Vd(t)).h,s:(r=(200-(i=e.s))*(s=e.v)/100)>0&&r<200?i*s/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,i,s,r},tp=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,ep=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,ip=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,sp=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,rp={string:[[function(t){var e=jd.exec(t);return e?(t=e[1]).length<=4?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16),a:4===t.length?Xd(parseInt(t[3]+t[3],16)/255,2):1}:6===t.length||8===t.length?{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16),a:8===t.length?Xd(parseInt(t.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(t){var e=ip.exec(t)||sp.exec(t);return e?e[2]!==e[4]||e[4]!==e[6]?null:Hd({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:void 0===e[7]?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(t){var e=tp.exec(t)||ep.exec(t);if(!e)return null;var i,s,r=Jd({h:(i=e[1],s=e[2],void 0===s&&(s="deg"),Number(i)*(Ud[s]||1)),s:Number(e[3]),l:Number(e[4]),a:void 0===e[5]?1:Number(e[5])/(e[6]?100:1)});return Zd(r)},"hsl"]],object:[[function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=void 0===r?1:r;return Gd(e)&&Gd(i)&&Gd(s)?Hd({r:Number(e),g:Number(i),b:Number(s),a:Number(n)}):null},"rgb"],[function(t){var e=t.h,i=t.s,s=t.l,r=t.a,n=void 0===r?1:r;if(!Gd(e)||!Gd(i)||!Gd(s))return null;var o=Jd({h:Number(e),s:Number(i),l:Number(s),a:Number(n)});return Zd(o)},"hsl"],[function(t){var e=t.h,i=t.s,s=t.v,r=t.a,n=void 0===r?1:r;if(!Gd(e)||!Gd(i)||!Gd(s))return null;var o,a=(o={h:Number(e),s:Number(i),v:Number(s),a:Number(n)},{h:Yd(o.h),s:Wd(o.s,0,100),v:Wd(o.v,0,100),a:Wd(o.a)});return qd(a)},"hsv"]]},np=function(t,e){for(var i=0;i<e.length;i++){var s=e[i][0](t);if(s)return[s,e[i][1]]}return[null,void 0]},op=function(t,e){var i=Qd(t);return{h:i.h,s:Wd(i.s+100*e,0,100),l:i.l,a:i.a}},ap=function(t){return(299*t.r+587*t.g+114*t.b)/1e3/255},lp=function(t,e){var i=Qd(t);return{h:i.h,s:i.s,l:Wd(i.l+100*e,0,100),a:i.a}},hp=function(){function t(t){this.parsed=function(t){return"string"==typeof t?np(t.trim(),rp.string):"object"==typeof t&&null!==t?np(t,rp.object):[null,void 0]}(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return t.prototype.isValid=function(){return null!==this.parsed},t.prototype.brightness=function(){return Xd(ap(this.rgba),2)},t.prototype.isDark=function(){return ap(this.rgba)<.5},t.prototype.isLight=function(){return ap(this.rgba)>=.5},t.prototype.toHex=function(){return e=(t=$d(this.rgba)).r,i=t.g,s=t.b,n=(r=t.a)<1?zd(Xd(255*r)):"","#"+zd(e)+zd(i)+zd(s)+n;var t,e,i,s,r,n},t.prototype.toRgb=function(){return $d(this.rgba)},t.prototype.toRgbString=function(){return e=(t=$d(this.rgba)).r,i=t.g,s=t.b,(r=t.a)<1?"rgba("+e+", "+i+", "+s+", "+r+")":"rgb("+e+", "+i+", "+s+")";var t,e,i,s,r},t.prototype.toHsl=function(){return Kd(Qd(this.rgba))},t.prototype.toHslString=function(){return e=(t=Kd(Qd(this.rgba))).h,i=t.s,s=t.l,(r=t.a)<1?"hsla("+e+", "+i+"%, "+s+"%, "+r+")":"hsl("+e+", "+i+"%, "+s+"%)";var t,e,i,s,r},t.prototype.toHsv=function(){return t=Vd(this.rgba),{h:Xd(t.h),s:Xd(t.s),v:Xd(t.v),a:Xd(t.a,3)};var t},t.prototype.invert=function(){return up({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},t.prototype.saturate=function(t){return void 0===t&&(t=.1),up(op(this.rgba,t))},t.prototype.desaturate=function(t){return void 0===t&&(t=.1),up(op(this.rgba,-t))},t.prototype.grayscale=function(){return up(op(this.rgba,-1))},t.prototype.lighten=function(t){return void 0===t&&(t=.1),up(lp(this.rgba,t))},t.prototype.darken=function(t){return void 0===t&&(t=.1),up(lp(this.rgba,-t))},t.prototype.rotate=function(t){return void 0===t&&(t=15),this.hue(this.hue()+t)},t.prototype.alpha=function(t){return"number"==typeof t?up({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):Xd(this.rgba.a,3);var e},t.prototype.hue=function(t){var e=Qd(this.rgba);return"number"==typeof t?up({h:t,s:e.s,l:e.l,a:e.a}):Xd(e.h)},t.prototype.isEqual=function(t){return this.toHex()===up(t).toHex()},t}(),up=function(t){return t instanceof hp?t:new hp(t)},cp=[];Dd=[function(t,e){var i={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},s={};for(var r in i)s[i[r]]=r;var n={};t.prototype.toName=function(e){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var r,o,a=s[this.toHex()];if(a)return a;if(null==e?void 0:e.closest){var l=this.toRgb(),h=1/0,u="black";if(!n.length)for(var c in i)n[c]=new t(i[c]).toRgb();for(var d in i){var p=(r=l,o=n[d],Math.pow(r.r-o.r,2)+Math.pow(r.g-o.g,2)+Math.pow(r.b-o.b,2));p<h&&(h=p,u=d)}return u}},e.string.push([function(e){var s=e.toLowerCase(),r="transparent"===s?"#0000":i[s];return r?new t(r).toRgb():null},"name"])}],Dd.forEach(function(t){cp.indexOf(t)<0&&(t(hp,rp),cp.push(t))});const dp=class t{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(t){return this.value=t,this}set value(e){if(e instanceof t)this._value=this.cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(null===e)throw new Error("Cannot set PIXI.Color#value to null");(null===this._value||!this.isSourceEqual(this._value,e))&&(this.normalize(e),this._value=this.cloneSource(e))}}get value(){return this._value}cloneSource(t){return"string"==typeof t||"number"==typeof t||t instanceof Number||null===t?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):"object"==typeof t&&null!==t?{...t}:t}isSourceEqual(t,e){const i=typeof t;if(i!==typeof e)return!1;if("number"===i||"string"===i||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length===e.length&&t.every((t,i)=>t===e[i]);if(null!==t&&null!==e){const i=Object.keys(t),s=Object.keys(e);return i.length===s.length&&i.every(i=>t[i]===e[i])}return t===e}toRgba(){const[t,e,i,s]=this._components;return{r:t,g:e,b:i,a:s}}toRgb(){const[t,e,i]=this._components;return{r:t,g:e,b:i}}toRgbaString(){const[t,e,i]=this.toUint8RgbArray();return`rgba(${t},${e},${i},${this.alpha})`}toUint8RgbArray(t){const[e,i,s]=this._components;return(t=t??[])[0]=Math.round(255*e),t[1]=Math.round(255*i),t[2]=Math.round(255*s),t}toRgbArray(t){t=t??[];const[e,i,s]=this._components;return t[0]=e,t[1]=i,t[2]=s,t}toNumber(){return this._int}toLittleEndianNumber(){const t=this._int;return(t>>16)+(65280&t)+((255&t)<<16)}multiply(e){const[i,s,r,n]=t.temp.setValue(e)._components;return this._components[0]*=i,this._components[1]*=s,this._components[2]*=r,this._components[3]*=n,this.refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this.refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(1===t)return(255<<24)+this._int;if(0===t)return e?0:this._int;let i=this._int>>16&255,s=this._int>>8&255,r=255&this._int;return e&&(i=i*t+.5|0,s=s*t+.5|0,r=r*t+.5|0),(255*t<<24)+(i<<16)+(s<<8)+r}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const t=Math.round(255*this._components[3]).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(t){return this._components[3]=this._clamp(t),this}round(t){const[e,i,s]=this._components;return this._components[0]=Math.round(e*t)/t,this._components[1]=Math.round(i*t)/t,this._components[2]=Math.round(s*t)/t,this.refreshInt(),this._value=null,this}toArray(t){t=t??[];const[e,i,s,r]=this._components;return t[0]=e,t[1]=i,t[2]=s,t[3]=r,t}normalize(e){let i,s,r,n;if(("number"==typeof e||e instanceof Number)&&e>=0&&e<=16777215){i=(e>>16&255)/255,s=(e>>8&255)/255,r=(255&e)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[i,s,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[i,s,r,n=255]=e,i/=255,s/=255,r/=255,n/=255;else if("string"==typeof e||"object"==typeof e){if("string"==typeof e){const i=t.HEX_PATTERN.exec(e);i&&(e=`#${i[2]}`)}const o=up(e);o.isValid()&&(({r:i,g:s,b:r,a:n}=o.rgba),i/=255,s/=255,r/=255)}if(void 0===i)throw new Error(`Unable to convert color ${e}`);this._components[0]=i,this._components[1]=s,this._components[2]=r,this._components[3]=n,this.refreshInt()}refreshInt(){this._clamp(this._components);const[t,e,i]=this._components;this._int=(255*t<<16)+(255*e<<8)+(255*i|0)}_clamp(t,e=0,i=1){return"number"==typeof t?Math.min(Math.max(t,e),i):(t.forEach((s,r)=>{t[r]=Math.min(Math.max(s,e),i)}),t)}};dp.shared=new dp,dp.temp=new dp,dp.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let pp=dp;const fp=function(){const t=[],e=[];for(let s=0;s<32;s++)t[s]=s,e[s]=s;t[mh.NORMAL_NPM]=mh.NORMAL,t[mh.ADD_NPM]=mh.ADD,t[mh.SCREEN_NPM]=mh.SCREEN,e[mh.NORMAL]=mh.NORMAL_NPM,e[mh.ADD]=mh.ADD_NPM,e[mh.SCREEN]=mh.SCREEN_NPM;const i=[];return i.push(e),i.push(t),i}();const mp=/^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i;function gp(t){if(4===t.BYTES_PER_ELEMENT)return t instanceof Float32Array?"Float32Array":t instanceof Uint32Array?"Uint32Array":"Int32Array";if(2===t.BYTES_PER_ELEMENT){if(t instanceof Uint16Array)return"Uint16Array"}else if(1===t.BYTES_PER_ELEMENT&&t instanceof Uint8Array)return"Uint8Array";return null}const yp={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array};function vp(t){return t+=0===t?1:0,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1}function xp(t){return!(t&t-1||!t)}function bp(t){let e=(t>65535?1:0)<<4,i=((t>>>=e)>255?1:0)<<3;return e|=i,i=((t>>>=i)>15?1:0)<<2,e|=i,i=((t>>>=i)>3?1:0)<<1,e|=i,e|(t>>>=i)>>1}function wp(t,e,i){const s=t.length;let r;if(e>=s||0===i)return;const n=s-(i=e+i>s?s-e:i);for(r=e;r<n;++r)t[r]=t[r+i];t.length=n}function _p(t){return 0===t?0:t<0?-1:1}let Pp=0;function Ep(){return++Pp}const Tp=class{constructor(t,e,i,s){this.left=t,this.top=e,this.right=i,this.bottom=s}get width(){return this.right-this.left}get height(){return this.bottom-this.top}isEmpty(){return this.left===this.right||this.top===this.bottom}};Tp.EMPTY=new Tp(0,0,0,0);let Ap=Tp;const Ip={},Sp=/* @__PURE__ */Object.create(null),Cp=/* @__PURE__ */Object.create(null);function Mp(){let t;for(t in Sp)delete Sp[t];for(t in Cp)delete Cp[t]}class Op{constructor(t,e,i){this._canvas=Oh.ADAPTER.createCanvas(),this._context=this._canvas.getContext("2d"),this.resolution=i||Oh.RESOLUTION,this.resize(t,e)}clear(){this._checkDestroyed(),this._context.setTransform(1,0,0,1,0,0),this._context.clearRect(0,0,this._canvas.width,this._canvas.height)}resize(t,e){this._checkDestroyed(),this._canvas.width=Math.round(t*this.resolution),this._canvas.height=Math.round(e*this.resolution)}destroy(){this._context=null,this._canvas=null}get width(){return this._checkDestroyed(),this._canvas.width}set width(t){this._checkDestroyed(),this._canvas.width=Math.round(t)}get height(){return this._checkDestroyed(),this._canvas.height}set height(t){this._checkDestroyed(),this._canvas.height=Math.round(t)}get canvas(){return this._checkDestroyed(),this._canvas}get context(){return this._checkDestroyed(),this._context}_checkDestroyed(){if(null===this._canvas)throw new TypeError("The CanvasRenderTarget has already been destroyed")}}function Np(t,e,i){for(let s=0,r=4*i*e;s<e;++s,r+=4)if(0!==t[r+3])return!1;return!0}function Lp(t,e,i,s,r){const n=4*e;for(let o=s,a=s*n+4*i;o<=r;++o,a+=n)if(0!==t[a+3])return!1;return!0}function Rp(t){const{width:e,height:i}=t,s=t.getContext("2d",{willReadFrequently:!0});if(null===s)throw new TypeError("Failed to get canvas 2D context");const r=s.getImageData(0,0,e,i).data;let n=0,o=0,a=e-1,l=i-1;for(;o<i&&Np(r,e,o);)++o;if(o===i)return Ap.EMPTY;for(;Np(r,e,l);)--l;for(;Lp(r,e,n,o,l);)++n;for(;Lp(r,e,a,o,l);)--a;return++a,++l,new Ap(n,o,a,l)}function Bp(t){const e=Rp(t),{width:i,height:s}=e;let r=null;if(!e.isEmpty()){const n=t.getContext("2d");if(null===n)throw new TypeError("Failed to get canvas 2D context");r=n.getImageData(e.left,e.top,i,s)}return{width:i,height:s,data:r}}function kp(t,e=globalThis.location){if(t.startsWith("data:"))return"";e=e||globalThis.location;const i=new URL(t,document.baseURI);return i.hostname!==e.hostname||i.port!==e.port||i.protocol!==e.protocol?"anonymous":""}function Fp(t,e=1){const i=Oh.RETINA_PREFIX?.exec(t);return i?parseFloat(i[1]):e}const Dp=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,BaseTextureCache:Cp,BoundingBox:Ap,CanvasRenderTarget:Op,DATA_URI:mp,EventEmitter:Qh,ProgramCache:Ip,TextureCache:Sp,clearTextureCache:Mp,correctBlendMode:function(t,e){return fp[e?1:0][t]},createIndicesForQuads:function(t,e=null){const i=6*t;if((e=e||new Uint16Array(i)).length!==i)throw new Error(`Out buffer length is incorrect, got ${e.length} and expected ${i}`);for(let s=0,r=0;s<i;s+=6,r+=4)e[s+0]=r+0,e[s+1]=r+1,e[s+2]=r+2,e[s+3]=r+0,e[s+4]=r+2,e[s+5]=r+3;return e},decomposeDataUri:function(t){const e=mp.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,charset:e[3]?e[3].toLowerCase():void 0,encoding:e[4]?e[4].toLowerCase():void 0,data:e[5]}},deprecation:Md,destroyTextureCache:function(){let t;for(t in Sp)Sp[t].destroy();for(t in Cp)Cp[t].destroy()},detectVideoAlphaMode:async function(){return Bd??(Bd=(async()=>{const t=document.createElement("canvas").getContext("webgl");if(!t)return Eh.UNPACK;const e=await new Promise(t=>{const e=document.createElement("video");e.onloadeddata=()=>t(e),e.onerror=()=>t(null),e.autoplay=!1,e.crossOrigin="anonymous",e.preload="auto",e.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",e.load()});if(!e)return Eh.UNPACK;const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i);const s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.NONE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e);const r=new Uint8Array(4);return t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,r),t.deleteFramebuffer(s),t.deleteTexture(i),t.getExtension("WEBGL_lose_context")?.loseContext(),r[0]<=r[3]?Eh.PMA:Eh.UNPACK})()),Bd},determineCrossOrigin:kp,earcut:Nt,getBufferType:gp,getCanvasBoundingBox:Rp,getResolutionOfUrl:Fp,hex2rgb:function(t,e=[]){return Md("7.2.0","utils.hex2rgb is deprecated, use Color#toRgbArray instead"),pp.shared.setValue(t).toRgbArray(e)},hex2string:function(t){return Md("7.2.0","utils.hex2string is deprecated, use Color#toHex instead"),pp.shared.setValue(t).toHex()},interleaveTypedArrays:function(t,e){let i=0,s=0;const r={};for(let l=0;l<t.length;l++)s+=e[l],i+=t[l].length;const n=new ArrayBuffer(4*i);let o=null,a=0;for(let l=0;l<t.length;l++){const i=e[l],h=t[l],u=gp(h);r[u]||(r[u]=new yp[u](n)),o=r[u];for(let t=0;t<h.length;t++){o[(t/i|0)*s+a+t%i]=h[t]}a+=i}return new Float32Array(n)},isMobile:qh,isPow2:xp,isWebGLSupported:Fd,log2:bp,nextPow2:vp,path:Rd,premultiplyBlendMode:fp,premultiplyRgba:function(t,e,i,s=!0){return Md("7.2.0","utils.premultiplyRgba has moved to Color.premultiply"),pp.shared.setValue(t).premultiply(e,s).toArray(i??new Float32Array(4))},premultiplyTint:function(t,e){return Md("7.2.0","utils.premultiplyTint has moved to Color.toPremultiplied"),pp.shared.setValue(t).toPremultiplied(e)},premultiplyTintToRgba:function(t,e,i,s=!0){return Md("7.2.0","utils.premultiplyTintToRgba has moved to Color.premultiply"),pp.shared.setValue(t).premultiply(e,s).toArray(i??new Float32Array(4))},removeItems:wp,rgb2hex:function(t){return Md("7.2.0","utils.rgb2hex is deprecated, use Color#toNumber instead"),pp.shared.setValue(t).toNumber()},sayHello:function(){Md("7.0.0",'sayHello is deprecated, please use Renderer\'s "hello" option')},sign:_p,skipHello:function(){Md("7.0.0","skipHello is deprecated, please use settings.RENDER_OPTIONS.hello")},string2hex:function(t){return Md("7.2.0","utils.string2hex is deprecated, use Color#toNumber instead"),pp.shared.setValue(t).toNumber()},trimCanvas:Bp,uid:Ep,url:Od},Symbol.toStringTag,{value:"Module"}));var Up=/* @__PURE__ */(t=>(t.Renderer="renderer",t.Application="application",t.RendererSystem="renderer-webgl-system",t.RendererPlugin="renderer-webgl-plugin",t.CanvasRendererSystem="renderer-canvas-system",t.CanvasRendererPlugin="renderer-canvas-plugin",t.Asset="asset",t.LoadParser="load-parser",t.ResolveParser="resolve-parser",t.CacheParser="cache-parser",t.DetectionParser="detection-parser",t))(Up||{});const Gp=t=>{if("function"==typeof t||"object"==typeof t&&t.extension){if(!t.extension)throw new Error("Extension class must have an extension object");t={..."object"!=typeof t.extension?{type:t.extension}:t.extension,ref:t}}if("object"!=typeof t)throw new Error("Invalid extension type");return"string"==typeof(t={...t}).type&&(t.type=[t.type]),t},Xp=(t,e)=>Gp(t).priority??e,Wp={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...t){return t.map(Gp).forEach(t=>{t.type.forEach(e=>this._removeHandlers[e]?.(t))}),this},add(...t){return t.map(Gp).forEach(t=>{t.type.forEach(e=>{const i=this._addHandlers,s=this._queue;i[e]?i[e]?.(t):(s[e]=s[e]||[],s[e]?.push(t))})}),this},handle(t,e,i){const s=this._addHandlers,r=this._removeHandlers;if(s[t]||r[t])throw new Error(`Extension type ${t} already has a handler`);s[t]=e,r[t]=i;const n=this._queue;return n[t]&&(n[t]?.forEach(t=>e(t)),delete n[t]),this},handleByMap(t,e){return this.handle(t,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByList(t,e,i=-1){return this.handle(t,t=>{e.includes(t.ref)||(e.push(t.ref),e.sort((t,e)=>Xp(e,i)-Xp(t,i)))},t=>{const i=e.indexOf(t.ref);-1!==i&&e.splice(i,1)})}};class Yp{constructor(t){"number"==typeof t?this.rawBinaryData=new ArrayBuffer(t):t instanceof Uint8Array?this.rawBinaryData=t.buffer:this.rawBinaryData=t,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData)}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get uint16View(){return this._uint16View||(this._uint16View=new Uint16Array(this.rawBinaryData)),this._uint16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}view(t){return this[`${t}View`]}destroy(){this.rawBinaryData=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._uint16View=null,this._int32View=null,this.uint32View=null,this.float32View=null}static sizeOf(t){switch(t){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${t} isn't a valid view type`)}}}const Hp=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join("\n");function $p(t){let e="";for(let i=0;i<t;++i)i>0&&(e+="\nelse "),i<t-1&&(e+=`if(test == ${i}.0){}`);return e}class jp{constructor(){this.data=0,this.blendMode=mh.NORMAL,this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(1&this.data)}set blend(t){!!(1&this.data)!==t&&(this.data^=1)}get offsets(){return!!(2&this.data)}set offsets(t){!!(2&this.data)!==t&&(this.data^=2)}get culling(){return!!(4&this.data)}set culling(t){!!(4&this.data)!==t&&(this.data^=4)}get depthTest(){return!!(8&this.data)}set depthTest(t){!!(8&this.data)!==t&&(this.data^=8)}get depthMask(){return!!(32&this.data)}set depthMask(t){!!(32&this.data)!==t&&(this.data^=32)}get clockwiseFrontFace(){return!!(16&this.data)}set clockwiseFrontFace(t){!!(16&this.data)!==t&&(this.data^=16)}get blendMode(){return this._blendMode}set blendMode(t){this.blend=t!==mh.NONE,this._blendMode=t}get polygonOffset(){return this._polygonOffset}set polygonOffset(t){this.offsets=!!t,this._polygonOffset=t}static for2d(){const t=new jp;return t.depthTest=!1,t.blend=!0,t}}jp.prototype.toString=function(){return`[@pixi/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`};const zp=[];function Vp(t,e){if(!t)return null;let i="";if("string"==typeof t){const e=/\.(\w{3,4})(?:$|\?|#)/i.exec(t);e&&(i=e[1].toLowerCase())}for(let s=zp.length-1;s>=0;--s){const r=zp[s];if(r.test&&r.test(t,i))return new r(t,e)}throw new Error("Unrecognized source type to auto-detect Resource")}class qp{constructor(t){this.items=[],this._name=t,this._aliasCount=0}emit(t,e,i,s,r,n,o,a){if(arguments.length>8)throw new Error("max arguments reached");const{name:l,items:h}=this;this._aliasCount++;for(let u=0,c=h.length;u<c;u++)h[u][l](t,e,i,s,r,n,o,a);return h===this.items&&this._aliasCount--,this}ensureNonAliasedItems(){this._aliasCount>0&&this.items.length>1&&(this._aliasCount=0,this.items=this.items.slice(0))}add(t){return t[this._name]&&(this.ensureNonAliasedItems(),this.remove(t),this.items.push(t)),this}remove(t){const e=this.items.indexOf(t);return-1!==e&&(this.ensureNonAliasedItems(),this.items.splice(e,1)),this}contains(t){return this.items.includes(t)}removeAll(){return this.ensureNonAliasedItems(),this.items.length=0,this}destroy(){this.removeAll(),this.items.length=0,this._name=""}get empty(){return 0===this.items.length}get name(){return this._name}}Object.defineProperties(qp.prototype,{dispatch:{value:qp.prototype.emit},run:{value:qp.prototype.emit}});class Jp{constructor(t=0,e=0){this._width=t,this._height=e,this.destroyed=!1,this.internal=!1,this.onResize=new qp("setRealSize"),this.onUpdate=new qp("update"),this.onError=new qp("onError")}bind(t){this.onResize.add(t),this.onUpdate.add(t),this.onError.add(t),(this._width||this._height)&&this.onResize.emit(this._width,this._height)}unbind(t){this.onResize.remove(t),this.onUpdate.remove(t),this.onError.remove(t)}resize(t,e){(t!==this._width||e!==this._height)&&(this._width=t,this._height=e,this.onResize.emit(t,e))}get valid(){return!!this._width&&!!this._height}update(){this.destroyed||this.onUpdate.emit()}load(){return Promise.resolve(this)}get width(){return this._width}get height(){return this._height}style(t,e,i){return!1}dispose(){}destroy(){this.destroyed||(this.destroyed=!0,this.dispose(),this.onError.removeAll(),this.onError=null,this.onResize.removeAll(),this.onResize=null,this.onUpdate.removeAll(),this.onUpdate=null)}static test(t,e){return!1}}class Kp extends Jp{constructor(t,e){const{width:i,height:s}=e||{};if(!i||!s)throw new Error("BufferResource width or height invalid");super(i,s),this.data=t,this.unpackAlignment=e.unpackAlignment??4}upload(t,e,i){const s=t.gl;s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.alphaMode===Eh.UNPACK);const r=e.realWidth,n=e.realHeight;return i.width===r&&i.height===n?s.texSubImage2D(e.target,0,0,0,r,n,e.format,i.type,this.data):(i.width=r,i.height=n,s.texImage2D(e.target,0,i.internalFormat,r,n,0,e.format,i.type,this.data)),!0}dispose(){this.data=null}static test(t){return null===t||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array}}const Zp={scaleMode:wh.NEAREST,alphaMode:Eh.NPM},Qp=class t extends Qh{constructor(e=null,i=null){super(),i=Object.assign({},t.defaultOptions,i);const{alphaMode:s,mipmap:r,anisotropicLevel:n,scaleMode:o,width:a,height:l,wrapMode:h,format:u,type:c,target:d,resolution:p,resourceOptions:f}=i;e&&!(e instanceof Jp)&&((e=Vp(e,f)).internal=!0),this.resolution=p||Oh.RESOLUTION,this.width=Math.round((a||0)*this.resolution)/this.resolution,this.height=Math.round((l||0)*this.resolution)/this.resolution,this._mipmap=r,this.anisotropicLevel=n,this._wrapMode=h,this._scaleMode=o,this.format=u,this.type=c,this.target=d,this.alphaMode=s,this.uid=Ep(),this.touched=0,this.isPowerOfTwo=!1,this._refreshPOT(),this._glTextures={},this.dirtyId=0,this.dirtyStyleId=0,this.cacheId=null,this.valid=a>0&&l>0,this.textureCacheIds=[],this.destroyed=!1,this.resource=null,this._batchEnabled=0,this._batchLocation=0,this.parentTextureArray=null,this.setResource(e)}get realWidth(){return Math.round(this.width*this.resolution)}get realHeight(){return Math.round(this.height*this.resolution)}get mipmap(){return this._mipmap}set mipmap(t){this._mipmap!==t&&(this._mipmap=t,this.dirtyStyleId++)}get scaleMode(){return this._scaleMode}set scaleMode(t){this._scaleMode!==t&&(this._scaleMode=t,this.dirtyStyleId++)}get wrapMode(){return this._wrapMode}set wrapMode(t){this._wrapMode!==t&&(this._wrapMode=t,this.dirtyStyleId++)}setStyle(t,e){let i;return void 0!==t&&t!==this.scaleMode&&(this.scaleMode=t,i=!0),void 0!==e&&e!==this.mipmap&&(this.mipmap=e,i=!0),i&&this.dirtyStyleId++,this}setSize(t,e,i){return i=i||this.resolution,this.setRealSize(t*i,e*i,i)}setRealSize(t,e,i){return this.resolution=i||this.resolution,this.width=Math.round(t)/this.resolution,this.height=Math.round(e)/this.resolution,this._refreshPOT(),this.update(),this}_refreshPOT(){this.isPowerOfTwo=xp(this.realWidth)&&xp(this.realHeight)}setResolution(t){const e=this.resolution;return e===t||(this.resolution=t,this.valid&&(this.width=Math.round(this.width*e)/t,this.height=Math.round(this.height*e)/t,this.emit("update",this)),this._refreshPOT()),this}setResource(t){if(this.resource===t)return this;if(this.resource)throw new Error("Resource can be set only once");return t.bind(this),this.resource=t,this}update(){this.valid?(this.dirtyId++,this.dirtyStyleId++,this.emit("update",this)):this.width>0&&this.height>0&&(this.valid=!0,this.emit("loaded",this),this.emit("update",this))}onError(t){this.emit("error",this,t)}destroy(){this.resource&&(this.resource.unbind(this),this.resource.internal&&this.resource.destroy(),this.resource=null),this.cacheId&&(delete Cp[this.cacheId],delete Sp[this.cacheId],this.cacheId=null),this.valid=!1,this.dispose(),t.removeFromCache(this),this.textureCacheIds=null,this.destroyed=!0,this.emit("destroyed",this),this.removeAllListeners()}dispose(){this.emit("dispose",this)}castToBaseTexture(){return this}static from(e,i,s=Oh.STRICT_TEXTURE_CACHE){const r="string"==typeof e;let n=null;if(r)n=e;else{if(!e._pixiId){const t=i?.pixiIdPrefix||"pixiid";e._pixiId=`${t}_${Ep()}`}n=e._pixiId}let o=Cp[n];if(r&&s&&!o)throw new Error(`The cacheId "${n}" does not exist in BaseTextureCache.`);return o||(o=new t(e,i),o.cacheId=n,t.addToCache(o,n)),o}static fromBuffer(e,i,s,r){e=e||new Float32Array(i*s*4);const n=new Kp(e,{width:i,height:s,...r?.resourceOptions});let o,a;return e instanceof Float32Array?(o=yh.RGBA,a=xh.FLOAT):e instanceof Int32Array?(o=yh.RGBA_INTEGER,a=xh.INT):e instanceof Uint32Array?(o=yh.RGBA_INTEGER,a=xh.UNSIGNED_INT):e instanceof Int16Array?(o=yh.RGBA_INTEGER,a=xh.SHORT):e instanceof Uint16Array?(o=yh.RGBA_INTEGER,a=xh.UNSIGNED_SHORT):e instanceof Int8Array?(o=yh.RGBA,a=xh.BYTE):(o=yh.RGBA,a=xh.UNSIGNED_BYTE),n.internal=!0,new t(n,Object.assign({},Zp,{type:a,format:o},r))}static addToCache(t,e){e&&(t.textureCacheIds.includes(e)||t.textureCacheIds.push(e),Cp[e]&&Cp[e]!==t&&console.warn(`BaseTexture added to the cache with an id [${e}] that already had an entry`),Cp[e]=t)}static removeFromCache(t){if("string"==typeof t){const e=Cp[t];if(e){const i=e.textureCacheIds.indexOf(t);return i>-1&&e.textureCacheIds.splice(i,1),delete Cp[t],e}}else if(t?.textureCacheIds){for(let e=0;e<t.textureCacheIds.length;++e)delete Cp[t.textureCacheIds[e]];return t.textureCacheIds.length=0,t}return null}};Qp.defaultOptions={mipmap:Ph.POW2,anisotropicLevel:0,scaleMode:wh.LINEAR,wrapMode:_h.CLAMP,alphaMode:Eh.UNPACK,target:vh.TEXTURE_2D,format:yh.RGBA,type:xh.UNSIGNED_BYTE},Qp._globalBatch=0;let tf=Qp;class ef{constructor(){this.texArray=null,this.blend=0,this.type=gh.TRIANGLES,this.start=0,this.size=0,this.data=null}}let sf=0;class rf{constructor(t,e=!0,i=!1){this.data=t||new Float32Array(1),this._glBuffers={},this._updateID=0,this.index=i,this.static=e,this.id=sf++,this.disposeRunner=new qp("disposeBuffer")}update(t){t instanceof Array&&(t=new Float32Array(t)),this.data=t||this.data,this._updateID++}dispose(){this.disposeRunner.emit(this,!1)}destroy(){this.dispose(),this.data=null}set index(t){this.type=t?Mh.ELEMENT_ARRAY_BUFFER:Mh.ARRAY_BUFFER}get index(){return this.type===Mh.ELEMENT_ARRAY_BUFFER}static from(t){return t instanceof Array&&(t=new Float32Array(t)),new rf(t)}}class nf{constructor(t,e=0,i=!1,s=xh.FLOAT,r,n,o,a=1){this.buffer=t,this.size=e,this.normalized=i,this.type=s,this.stride=r,this.start=n,this.instance=o,this.divisor=a}destroy(){this.buffer=null}static from(t,e,i,s,r){return new nf(t,e,i,s,r)}}const of={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array};const af={5126:4,5123:2,5121:1};let lf=0;const hf={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Uint16Array:Uint16Array};class uf{constructor(t=[],e={}){this.buffers=t,this.indexBuffer=null,this.attributes=e,this.glVertexArrayObjects={},this.id=lf++,this.instanced=!1,this.instanceCount=1,this.disposeRunner=new qp("disposeGeometry"),this.refCount=0}addAttribute(t,e,i=0,s=!1,r,n,o,a=!1){if(!e)throw new Error("You must pass a buffer when creating an attribute");e instanceof rf||(e instanceof Array&&(e=new Float32Array(e)),e=new rf(e));const l=t.split("|");if(l.length>1){for(let t=0;t<l.length;t++)this.addAttribute(l[t],e,i,s,r);return this}let h=this.buffers.indexOf(e);return-1===h&&(this.buffers.push(e),h=this.buffers.length-1),this.attributes[t]=new nf(h,i,s,r,n,o,a),this.instanced=this.instanced||a,this}getAttribute(t){return this.attributes[t]}getBuffer(t){return this.buffers[this.getAttribute(t).buffer]}addIndex(t){return t instanceof rf||(t instanceof Array&&(t=new Uint16Array(t)),t=new rf(t)),t.type=Mh.ELEMENT_ARRAY_BUFFER,this.indexBuffer=t,this.buffers.includes(t)||this.buffers.push(t),this}getIndex(){return this.indexBuffer}interleave(){if(1===this.buffers.length||2===this.buffers.length&&this.indexBuffer)return this;const t=[],e=[],i=new rf;let s;for(s in this.attributes){const i=this.attributes[s],r=this.buffers[i.buffer];t.push(r.data),e.push(i.size*af[i.type]/4),i.buffer=0}for(i.data=function(t,e){let i=0,s=0;const r={};for(let l=0;l<t.length;l++)s+=e[l],i+=t[l].length;const n=new ArrayBuffer(4*i);let o=null,a=0;for(let l=0;l<t.length;l++){const i=e[l],h=t[l],u=gp(h);r[u]||(r[u]=new of[u](n)),o=r[u];for(let t=0;t<h.length;t++)o[(t/i|0)*s+a+t%i]=h[t];a+=i}return new Float32Array(n)}(t,e),s=0;s<this.buffers.length;s++)this.buffers[s]!==this.indexBuffer&&this.buffers[s].destroy();return this.buffers=[i],this.indexBuffer&&this.buffers.push(this.indexBuffer),this}getSize(){for(const t in this.attributes){const e=this.attributes[t];return this.buffers[e.buffer].data.length/(e.stride/4||e.size)}return 0}dispose(){this.disposeRunner.emit(this,!1)}destroy(){this.dispose(),this.buffers=null,this.indexBuffer=null,this.attributes=null}clone(){const t=new uf;for(let e=0;e<this.buffers.length;e++)t.buffers[e]=new rf(this.buffers[e].data.slice(0));for(const e in this.attributes){const i=this.attributes[e];t.attributes[e]=new nf(i.buffer,i.size,i.normalized,i.type,i.stride,i.start,i.instance)}return this.indexBuffer&&(t.indexBuffer=t.buffers[this.buffers.indexOf(this.indexBuffer)],t.indexBuffer.type=Mh.ELEMENT_ARRAY_BUFFER),t}static merge(t){const e=new uf,i=[],s=[],r=[];let n;for(let o=0;o<t.length;o++){n=t[o];for(let t=0;t<n.buffers.length;t++)s[t]=s[t]||0,s[t]+=n.buffers[t].data.length,r[t]=0}for(let o=0;o<n.buffers.length;o++)i[o]=new(hf[gp(n.buffers[o].data)])(s[o]),e.buffers[o]=new rf(i[o]);for(let o=0;o<t.length;o++){n=t[o];for(let t=0;t<n.buffers.length;t++)i[t].set(n.buffers[t].data,r[t]),r[t]+=n.buffers[t].data.length}if(e.attributes=n.attributes,n.indexBuffer){e.indexBuffer=e.buffers[n.buffers.indexOf(n.indexBuffer)],e.indexBuffer.type=Mh.ELEMENT_ARRAY_BUFFER;let i=0,s=0,r=0,o=0;for(let t=0;t<n.buffers.length;t++)if(n.buffers[t]!==n.indexBuffer){o=t;break}for(const t in n.attributes){const e=n.attributes[t];(0|e.buffer)===o&&(s+=e.size*af[e.type]/4)}for(let n=0;n<t.length;n++){const a=t[n].indexBuffer.data;for(let t=0;t<a.length;t++)e.indexBuffer.data[t+r]+=i;i+=t[n].buffers[o].data.length/s,r+=a.length}}return e}}class cf extends uf{constructor(t=!1){super(),this._buffer=new rf(null,t,!1),this._indexBuffer=new rf(null,t,!0),this.addAttribute("aVertexPosition",this._buffer,2,!1,xh.FLOAT).addAttribute("aTextureCoord",this._buffer,2,!1,xh.FLOAT).addAttribute("aColor",this._buffer,4,!0,xh.UNSIGNED_BYTE).addAttribute("aTextureId",this._buffer,1,!0,xh.FLOAT).addIndex(this._indexBuffer)}}const df=2*Math.PI,pf=180/Math.PI,ff=Math.PI/180;var mf=/* @__PURE__ */(t=>(t[t.POLY=0]="POLY",t[t.RECT=1]="RECT",t[t.CIRC=2]="CIRC",t[t.ELIP=3]="ELIP",t[t.RREC=4]="RREC",t))(mf||{});class gf{constructor(t=0,e=0){this.x=0,this.y=0,this.x=t,this.y=e}clone(){return new gf(this.x,this.y)}copyFrom(t){return this.set(t.x,t.y),this}copyTo(t){return t.set(this.x,this.y),t}equals(t){return t.x===this.x&&t.y===this.y}set(t=0,e=t){return this.x=t,this.y=e,this}}gf.prototype.toString=function(){return`[@pixi/math:Point x=${this.x} y=${this.y}]`};const yf=[new gf,new gf,new gf,new gf];class vf{constructor(t=0,e=0,i=0,s=0){this.x=Number(t),this.y=Number(e),this.width=Number(i),this.height=Number(s),this.type=mf.RECT}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}static get EMPTY(){return new vf(0,0,0,0)}clone(){return new vf(this.x,this.y,this.width,this.height)}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t}contains(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t<this.x+this.width&&e>=this.y&&e<this.y+this.height)}intersects(t,e){if(!e){const e=this.x<t.x?t.x:this.x;if((this.right>t.right?t.right:this.right)<=e)return!1;const i=this.y<t.y?t.y:this.y;return(this.bottom>t.bottom?t.bottom:this.bottom)>i}const i=this.left,s=this.right,r=this.top,n=this.bottom;if(s<=i||n<=r)return!1;const o=yf[0].set(t.left,t.top),a=yf[1].set(t.left,t.bottom),l=yf[2].set(t.right,t.top),h=yf[3].set(t.right,t.bottom);if(l.x<=o.x||a.y<=o.y)return!1;const u=Math.sign(e.a*e.d-e.b*e.c);if(0===u||(e.apply(o,o),e.apply(a,a),e.apply(l,l),e.apply(h,h),Math.max(o.x,a.x,l.x,h.x)<=i||Math.min(o.x,a.x,l.x,h.x)>=s||Math.max(o.y,a.y,l.y,h.y)<=r||Math.min(o.y,a.y,l.y,h.y)>=n))return!1;const c=u*(a.y-o.y),d=u*(o.x-a.x),p=c*i+d*r,f=c*s+d*r,m=c*i+d*n,g=c*s+d*n;if(Math.max(p,f,m,g)<=c*o.x+d*o.y||Math.min(p,f,m,g)>=c*h.x+d*h.y)return!1;const y=u*(o.y-l.y),v=u*(l.x-o.x),x=y*i+v*r,b=y*s+v*r,w=y*i+v*n,_=y*s+v*n;return!(Math.max(x,b,w,_)<=y*o.x+v*o.y||Math.min(x,b,w,_)>=y*h.x+v*h.y)}pad(t=0,e=t){return this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e,this}fit(t){const e=Math.max(this.x,t.x),i=Math.min(this.x+this.width,t.x+t.width),s=Math.max(this.y,t.y),r=Math.min(this.y+this.height,t.y+t.height);return this.x=e,this.width=Math.max(i-e,0),this.y=s,this.height=Math.max(r-s,0),this}ceil(t=1,e=.001){const i=Math.ceil((this.x+this.width-e)*t)/t,s=Math.ceil((this.y+this.height-e)*t)/t;return this.x=Math.floor((this.x+e)*t)/t,this.y=Math.floor((this.y+e)*t)/t,this.width=i-this.x,this.height=s-this.y,this}enlarge(t){const e=Math.min(this.x,t.x),i=Math.max(this.x+this.width,t.x+t.width),s=Math.min(this.y,t.y),r=Math.max(this.y+this.height,t.y+t.height);return this.x=e,this.width=i-e,this.y=s,this.height=r-s,this}}vf.prototype.toString=function(){return`[@pixi/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`};class xf{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.radius=i,this.type=mf.CIRC}clone(){return new xf(this.x,this.y,this.radius)}contains(t,e){if(this.radius<=0)return!1;const i=this.radius*this.radius;let s=this.x-t,r=this.y-e;return s*=s,r*=r,s+r<=i}getBounds(){return new vf(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}}xf.prototype.toString=function(){return`[@pixi/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`};class bf{constructor(t=0,e=0,i=0,s=0){this.x=t,this.y=e,this.width=i,this.height=s,this.type=mf.ELIP}clone(){return new bf(this.x,this.y,this.width,this.height)}contains(t,e){if(this.width<=0||this.height<=0)return!1;let i=(t-this.x)/this.width,s=(e-this.y)/this.height;return i*=i,s*=s,i+s<=1}getBounds(){return new vf(this.x-this.width,this.y-this.height,this.width,this.height)}}bf.prototype.toString=function(){return`[@pixi/math:Ellipse x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`};class wf{constructor(...t){let e=Array.isArray(t[0])?t[0]:t;if("number"!=typeof e[0]){const t=[];for(let i=0,s=e.length;i<s;i++)t.push(e[i].x,e[i].y);e=t}this.points=e,this.type=mf.POLY,this.closeStroke=!0}clone(){const t=this.points.slice(),e=new wf(t);return e.closeStroke=this.closeStroke,e}contains(t,e){let i=!1;const s=this.points.length/2;for(let r=0,n=s-1;r<s;n=r++){const s=this.points[2*r],o=this.points[2*r+1],a=this.points[2*n],l=this.points[2*n+1];o>e!=l>e&&t<(e-o)/(l-o)*(a-s)+s&&(i=!i)}return i}}wf.prototype.toString=function(){return`[@pixi/math:PolygoncloseStroke=${this.closeStroke}points=${this.points.reduce((t,e)=>`${t}, ${e}`,"")}]`};class _f{constructor(t=0,e=0,i=0,s=0,r=20){this.x=t,this.y=e,this.width=i,this.height=s,this.radius=r,this.type=mf.RREC}clone(){return new _f(this.x,this.y,this.width,this.height,this.radius)}contains(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(e>=this.y+i&&e<=this.y+this.height-i||t>=this.x+i&&t<=this.x+this.width-i)return!0;let s=t-(this.x+i),r=e-(this.y+i);const n=i*i;if(s*s+r*r<=n||(s=t-(this.x+this.width-i),s*s+r*r<=n)||(r=e-(this.y+this.height-i),s*s+r*r<=n)||(s=t-(this.x+i),s*s+r*r<=n))return!0}return!1}}_f.prototype.toString=function(){return`[@pixi/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`};class Pf{constructor(t=1,e=0,i=0,s=1,r=0,n=0){this.array=null,this.a=t,this.b=e,this.c=i,this.d=s,this.tx=r,this.ty=n}fromArray(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]}set(t,e,i,s,r,n){return this.a=t,this.b=e,this.c=i,this.d=s,this.tx=r,this.ty=n,this}toArray(t,e){this.array||(this.array=new Float32Array(9));const i=e||this.array;return t?(i[0]=this.a,i[1]=this.b,i[2]=0,i[3]=this.c,i[4]=this.d,i[5]=0,i[6]=this.tx,i[7]=this.ty,i[8]=1):(i[0]=this.a,i[1]=this.c,i[2]=this.tx,i[3]=this.b,i[4]=this.d,i[5]=this.ty,i[6]=0,i[7]=0,i[8]=1),i}apply(t,e){e=e||new gf;const i=t.x,s=t.y;return e.x=this.a*i+this.c*s+this.tx,e.y=this.b*i+this.d*s+this.ty,e}applyInverse(t,e){e=e||new gf;const i=1/(this.a*this.d+this.c*-this.b),s=t.x,r=t.y;return e.x=this.d*i*s+-this.c*i*r+(this.ty*this.c-this.tx*this.d)*i,e.y=this.a*i*r+-this.b*i*s+(-this.ty*this.a+this.tx*this.b)*i,e}translate(t,e){return this.tx+=t,this.ty+=e,this}scale(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this}rotate(t){const e=Math.cos(t),i=Math.sin(t),s=this.a,r=this.c,n=this.tx;return this.a=s*e-this.b*i,this.b=s*i+this.b*e,this.c=r*e-this.d*i,this.d=r*i+this.d*e,this.tx=n*e-this.ty*i,this.ty=n*i+this.ty*e,this}append(t){const e=this.a,i=this.b,s=this.c,r=this.d;return this.a=t.a*e+t.b*s,this.b=t.a*i+t.b*r,this.c=t.c*e+t.d*s,this.d=t.c*i+t.d*r,this.tx=t.tx*e+t.ty*s+this.tx,this.ty=t.tx*i+t.ty*r+this.ty,this}setTransform(t,e,i,s,r,n,o,a,l){return this.a=Math.cos(o+l)*r,this.b=Math.sin(o+l)*r,this.c=-Math.sin(o-a)*n,this.d=Math.cos(o-a)*n,this.tx=t-(i*this.a+s*this.c),this.ty=e-(i*this.b+s*this.d),this}prepend(t){const e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){const e=this.a,i=this.c;this.a=e*t.a+this.b*t.c,this.b=e*t.b+this.b*t.d,this.c=i*t.a+this.d*t.c,this.d=i*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this}decompose(t){const e=this.a,i=this.b,s=this.c,r=this.d,n=t.pivot,o=-Math.atan2(-s,r),a=Math.atan2(i,e),l=Math.abs(o+a);return l<1e-5||Math.abs(df-l)<1e-5?(t.rotation=a,t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=o,t.skew.y=a),t.scale.x=Math.sqrt(e*e+i*i),t.scale.y=Math.sqrt(s*s+r*r),t.position.x=this.tx+(n.x*e+n.y*s),t.position.y=this.ty+(n.x*i+n.y*r),t}invert(){const t=this.a,e=this.b,i=this.c,s=this.d,r=this.tx,n=t*s-e*i;return this.a=s/n,this.b=-e/n,this.c=-i/n,this.d=t/n,this.tx=(i*this.ty-s*r)/n,this.ty=-(t*this.ty-e*r)/n,this}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const t=new Pf;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyTo(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyFrom(t){return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.tx=t.tx,this.ty=t.ty,this}static get IDENTITY(){return new Pf}static get TEMP_MATRIX(){return new Pf}}Pf.prototype.toString=function(){return`[@pixi/math:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`};const Ef=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],Tf=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],Af=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],If=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Sf=[],Cf=[],Mf=Math.sign;!function(){for(let t=0;t<16;t++){const e=[];Sf.push(e);for(let i=0;i<16;i++){const s=Mf(Ef[t]*Ef[i]+Af[t]*Tf[i]),r=Mf(Tf[t]*Ef[i]+If[t]*Tf[i]),n=Mf(Ef[t]*Af[i]+Af[t]*If[i]),o=Mf(Tf[t]*Af[i]+If[t]*If[i]);for(let t=0;t<16;t++)if(Ef[t]===s&&Tf[t]===r&&Af[t]===n&&If[t]===o){e.push(t);break}}}for(let t=0;t<16;t++){const e=new Pf;e.set(Ef[t],Tf[t],Af[t],If[t],0,0),Cf.push(e)}}();const Of={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:t=>Ef[t],uY:t=>Tf[t],vX:t=>Af[t],vY:t=>If[t],inv:t=>8&t?15&t:7&-t,add:(t,e)=>Sf[t][e],sub:(t,e)=>Sf[t][Of.inv(e)],rotate180:t=>4^t,isVertical:t=>2==(3&t),byDirection:(t,e)=>2*Math.abs(t)<=Math.abs(e)?e>=0?Of.S:Of.N:2*Math.abs(e)<=Math.abs(t)?t>0?Of.E:Of.W:e>0?t>0?Of.SE:Of.SW:t>0?Of.NE:Of.NW,matrixAppendRotationInv:(t,e,i=0,s=0)=>{const r=Cf[Of.inv(e)];r.tx=i,r.ty=s,t.append(r)}};class Nf{constructor(t,e,i=0,s=0){this._x=i,this._y=s,this.cb=t,this.scope=e}clone(t=this.cb,e=this.scope){return new Nf(t,e,this._x,this._y)}set(t=0,e=t){return(this._x!==t||this._y!==e)&&(this._x=t,this._y=e,this.cb.call(this.scope)),this}copyFrom(t){return(this._x!==t.x||this._y!==t.y)&&(this._x=t.x,this._y=t.y,this.cb.call(this.scope)),this}copyTo(t){return t.set(this._x,this._y),t}equals(t){return t.x===this._x&&t.y===this._y}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}Nf.prototype.toString=function(){return`[@pixi/math:ObservablePoint x=${this.x} y=${this.y} scope=${this.scope}]`};const Lf=class{constructor(){this.worldTransform=new Pf,this.localTransform=new Pf,this.position=new Nf(this.onChange,this,0,0),this.scale=new Nf(this.onChange,this,1,1),this.pivot=new Nf(this.onChange,this,0,0),this.skew=new Nf(this.updateSkew,this,0,0),this._rotation=0,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._localID=0,this._currentLocalID=0,this._worldID=0,this._parentID=0}onChange(){this._localID++}updateSkew(){this._cx=Math.cos(this._rotation+this.skew.y),this._sx=Math.sin(this._rotation+this.skew.y),this._cy=-Math.sin(this._rotation-this.skew.x),this._sy=Math.cos(this._rotation-this.skew.x),this._localID++}updateLocalTransform(){const t=this.localTransform;this._localID!==this._currentLocalID&&(t.a=this._cx*this.scale.x,t.b=this._sx*this.scale.x,t.c=this._cy*this.scale.y,t.d=this._sy*this.scale.y,t.tx=this.position.x-(this.pivot.x*t.a+this.pivot.y*t.c),t.ty=this.position.y-(this.pivot.x*t.b+this.pivot.y*t.d),this._currentLocalID=this._localID,this._parentID=-1)}updateTransform(t){const e=this.localTransform;if(this._localID!==this._currentLocalID&&(e.a=this._cx*this.scale.x,e.b=this._sx*this.scale.x,e.c=this._cy*this.scale.y,e.d=this._sy*this.scale.y,e.tx=this.position.x-(this.pivot.x*e.a+this.pivot.y*e.c),e.ty=this.position.y-(this.pivot.x*e.b+this.pivot.y*e.d),this._currentLocalID=this._localID,this._parentID=-1),this._parentID!==t._worldID){const i=t.worldTransform,s=this.worldTransform;s.a=e.a*i.a+e.b*i.c,s.b=e.a*i.b+e.b*i.d,s.c=e.c*i.a+e.d*i.c,s.d=e.c*i.b+e.d*i.d,s.tx=e.tx*i.a+e.ty*i.c+i.tx,s.ty=e.tx*i.b+e.ty*i.d+i.ty,this._parentID=t._worldID,this._worldID++}}setFromMatrix(t){t.decompose(this),this._localID++}get rotation(){return this._rotation}set rotation(t){this._rotation!==t&&(this._rotation=t,this.updateSkew())}};Lf.IDENTITY=new Lf;let Rf=Lf;Rf.prototype.toString=function(){return`[@pixi/math:Transform position=(${this.position.x}, ${this.position.y}) rotation=${this.rotation} scale=(${this.scale.x}, ${this.scale.y}) skew=(${this.skew.x}, ${this.skew.y}) ]`};function Bf(t,e,i){const s=t.createShader(e);return t.shaderSource(s,i),t.compileShader(s),s}function kf(t){const e=new Array(t);for(let i=0;i<e.length;i++)e[i]=!1;return e}function Ff(t,e){switch(t){case"float":case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"vec2":return new Float32Array(2*e);case"vec3":return new Float32Array(3*e);case"vec4":return new Float32Array(4*e);case"ivec2":return new Int32Array(2*e);case"ivec3":return new Int32Array(3*e);case"ivec4":return new Int32Array(4*e);case"uvec2":return new Uint32Array(2*e);case"uvec3":return new Uint32Array(3*e);case"uvec4":return new Uint32Array(4*e);case"bool":return!1;case"bvec2":return kf(2*e);case"bvec3":return kf(3*e);case"bvec4":return kf(4*e);case"mat2":return new Float32Array([1,0,0,1]);case"mat3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const Df=[{test:t=>"float"===t.type&&1===t.size&&!t.isArray,code:t=>`\n if(uv["${t}"] !== ud["${t}"].value)\n {\n ud["${t}"].value = uv["${t}"]\n gl.uniform1f(ud["${t}"].location, uv["${t}"])\n }\n `},{test:(t,e)=>!("sampler2D"!==t.type&&"samplerCube"!==t.type&&"sampler2DArray"!==t.type||1!==t.size||t.isArray||null!=e&&void 0===e.castToBaseTexture),code:t=>`t = syncData.textureCount++;\n\n renderer.texture.bind(uv["${t}"], t);\n\n if(ud["${t}"].value !== t)\n {\n ud["${t}"].value = t;\n gl.uniform1i(ud["${t}"].location, t);\n; // eslint-disable-line max-len\n }`},{test:(t,e)=>"mat3"===t.type&&1===t.size&&!t.isArray&&void 0!==e.a,code:t=>`\n gl.uniformMatrix3fv(ud["${t}"].location, false, uv["${t}"].toArray(true));\n `,codeUbo:t=>`\n var ${t}_matrix = uv.${t}.toArray(true);\n\n data[offset] = ${t}_matrix[0];\n data[offset+1] = ${t}_matrix[1];\n data[offset+2] = ${t}_matrix[2];\n \n data[offset + 4] = ${t}_matrix[3];\n data[offset + 5] = ${t}_matrix[4];\n data[offset + 6] = ${t}_matrix[5];\n \n data[offset + 8] = ${t}_matrix[6];\n data[offset + 9] = ${t}_matrix[7];\n data[offset + 10] = ${t}_matrix[8];\n `},{test:(t,e)=>"vec2"===t.type&&1===t.size&&!t.isArray&&void 0!==e.x,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud["${t}"].location, v.x, v.y);\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n `},{test:t=>"vec2"===t.type&&1===t.size&&!t.isArray,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud["${t}"].location, v[0], v[1]);\n }\n `},{test:(t,e)=>"vec4"===t.type&&1===t.size&&!t.isArray&&void 0!==e.width,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud["${t}"].location, v.x, v.y, v.width, v.height)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n data[offset+2] = v.width;\n data[offset+3] = v.height;\n `},{test:(t,e)=>"vec4"===t.type&&1===t.size&&!t.isArray&&void 0!==e.red,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.alpha)\n {\n cv[0] = v.red;\n cv[1] = v.green;\n cv[2] = v.blue;\n cv[3] = v.alpha;\n gl.uniform4f(ud["${t}"].location, v.red, v.green, v.blue, v.alpha)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.red;\n data[offset+1] = v.green;\n data[offset+2] = v.blue;\n data[offset+3] = v.alpha;\n `},{test:(t,e)=>"vec3"===t.type&&1===t.size&&!t.isArray&&void 0!==e.red,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.a)\n {\n cv[0] = v.red;\n cv[1] = v.green;\n cv[2] = v.blue;\n \n gl.uniform3f(ud["${t}"].location, v.red, v.green, v.blue)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.red;\n data[offset+1] = v.green;\n data[offset+2] = v.blue;\n `},{test:t=>"vec4"===t.type&&1===t.size&&!t.isArray,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud["${t}"].location, v[0], v[1], v[2], v[3])\n }`}],Uf={float:"\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1f(location, v);\n }",vec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2f(location, v[0], v[1])\n }",vec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }",vec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(location, v[0], v[1], v[2], v[3]);\n }",int:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",ivec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }",ivec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }",ivec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }",uint:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1ui(location, v);\n }",uvec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2ui(location, v[0], v[1]);\n }",uvec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3ui(location, v[0], v[1], v[2]);\n }",uvec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4ui(location, v[0], v[1], v[2], v[3]);\n }",bool:"\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1i(location, v);\n }",bvec2:"\n if (cv[0] != v[0] || cv[1] != v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }",bvec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }",bvec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }",mat2:"gl.uniformMatrix2fv(location, false, v)",mat3:"gl.uniformMatrix3fv(location, false, v)",mat4:"gl.uniformMatrix4fv(location, false, v)",sampler2D:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",samplerCube:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",sampler2DArray:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }"},Gf={float:"gl.uniform1fv(location, v)",vec2:"gl.uniform2fv(location, v)",vec3:"gl.uniform3fv(location, v)",vec4:"gl.uniform4fv(location, v)",mat4:"gl.uniformMatrix4fv(location, false, v)",mat3:"gl.uniformMatrix3fv(location, false, v)",mat2:"gl.uniformMatrix2fv(location, false, v)",int:"gl.uniform1iv(location, v)",ivec2:"gl.uniform2iv(location, v)",ivec3:"gl.uniform3iv(location, v)",ivec4:"gl.uniform4iv(location, v)",uint:"gl.uniform1uiv(location, v)",uvec2:"gl.uniform2uiv(location, v)",uvec3:"gl.uniform3uiv(location, v)",uvec4:"gl.uniform4uiv(location, v)",bool:"gl.uniform1iv(location, v)",bvec2:"gl.uniform2iv(location, v)",bvec3:"gl.uniform3iv(location, v)",bvec4:"gl.uniform4iv(location, v)",sampler2D:"gl.uniform1iv(location, v)",samplerCube:"gl.uniform1iv(location, v)",sampler2DArray:"gl.uniform1iv(location, v)"};const Xf={};let Wf,Yf=Xf;function Hf(){if(!Wf){Wf=Ih.MEDIUM;const t=function(){if(Yf===Xf||Yf?.isContextLost()){const t=Oh.ADAPTER.createCanvas();let e;Oh.PREFER_ENV>=dh.WEBGL2&&(e=t.getContext("webgl2",{})),e||(e=t.getContext("webgl",{})||t.getContext("experimental-webgl",{}),e?e.getExtension("WEBGL_draw_buffers"):e=null),Yf=e}return Yf}();if(t&&t.getShaderPrecisionFormat){const e=t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT);e&&(Wf=e.precision?Ih.HIGH:Ih.MEDIUM)}}return Wf}function $f(t,e){const i=t.getShaderSource(e).split("\n").map((t,e)=>`${e}: ${t}`),s=t.getShaderInfoLog(e),r=s.split("\n"),n={},o=r.map(t=>parseFloat(t.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(t=>!(!t||n[t])&&(n[t]=!0,!0)),a=[""];o.forEach(t=>{i[t-1]=`%c${i[t-1]}%c`,a.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const l=i.join("\n");a[0]=l,console.error(s),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}const jf={float:1,vec2:2,vec3:3,vec4:4,int:1,ivec2:2,ivec3:3,ivec4:4,uint:1,uvec2:2,uvec3:3,uvec4:4,bool:1,bvec2:2,bvec3:3,bvec4:4,mat2:4,mat3:9,mat4:16,sampler2D:1};function zf(t){return jf[t]}let Vf=null;const qf={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"};function Jf(t,e){if(!Vf){const e=Object.keys(qf);Vf={};for(let i=0;i<e.length;++i){const s=e[i];Vf[t[s]]=qf[s]}}return Vf[e]}function Kf(t,e,i){if("precision"!==t.substring(0,9)){let s=e;return e===Ih.HIGH&&i!==Ih.HIGH&&(s=Ih.MEDIUM),`precision ${s} float;\n${t}`}return i!==Ih.HIGH&&"precision highp"===t.substring(0,15)?t.replace("precision highp","precision mediump"):t}let Zf;let Qf=0;const tm={},em=class t{constructor(e,i,s="pixi-shader",r={}){this.extra={},this.id=Qf++,this.vertexSrc=e||t.defaultVertexSrc,this.fragmentSrc=i||t.defaultFragmentSrc,this.vertexSrc=this.vertexSrc.trim(),this.fragmentSrc=this.fragmentSrc.trim(),this.extra=r,"#version"!==this.vertexSrc.substring(0,8)&&(s=s.replace(/\s+/g,"-"),tm[s]?(tm[s]++,s+=`-${tm[s]}`):tm[s]=1,this.vertexSrc=`#define SHADER_NAME ${s}\n${this.vertexSrc}`,this.fragmentSrc=`#define SHADER_NAME ${s}\n${this.fragmentSrc}`,this.vertexSrc=Kf(this.vertexSrc,t.defaultVertexPrecision,Ih.HIGH),this.fragmentSrc=Kf(this.fragmentSrc,t.defaultFragmentPrecision,Hf())),this.glPrograms={},this.syncUniforms=null}static get defaultVertexSrc(){return"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"}static get defaultFragmentSrc(){return"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"}static from(e,i,s){const r=e+i;let n=Ip[r];return n||(Ip[r]=n=new t(e,i,s)),n}};em.defaultVertexPrecision=Ih.HIGH,em.defaultFragmentPrecision=qh.apple.device?Ih.HIGH:Ih.MEDIUM;let im=em,sm=0;class rm{constructor(t,e,i){this.group=!0,this.syncUniforms={},this.dirtyId=0,this.id=sm++,this.static=!!e,this.ubo=!!i,t instanceof rf?(this.buffer=t,this.buffer.type=Mh.UNIFORM_BUFFER,this.autoManage=!1,this.ubo=!0):(this.uniforms=t,this.ubo&&(this.buffer=new rf(new Float32Array(1)),this.buffer.type=Mh.UNIFORM_BUFFER,this.autoManage=!0))}update(){this.dirtyId++,!this.autoManage&&this.buffer&&this.buffer.update()}add(t,e,i){if(this.ubo)throw new Error("[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them");this.uniforms[t]=new rm(e,i)}static from(t,e,i){return new rm(t,e,i)}static uboFrom(t,e){return new rm(t,e??!0,!0)}}class nm{constructor(t,e){this.uniformBindCount=0,this.program=t,this.uniformGroup=e?e instanceof rm?e:new rm(e):new rm({}),this.disposeRunner=new qp("disposeShader")}checkUniformExists(t,e){if(e.uniforms[t])return!0;for(const i in e.uniforms){const s=e.uniforms[i];if(!0===s.group&&this.checkUniformExists(t,s))return!0}return!1}destroy(){this.uniformGroup=null,this.disposeRunner.emit(this),this.disposeRunner.destroy()}get uniforms(){return this.uniformGroup.uniforms}static from(t,e,i){const s=im.from(t,e);return new nm(s,i)}}class om{constructor(t,e){if(this.vertexSrc=t,this.fragTemplate=e,this.programCache={},this.defaultGroupCache={},!e.includes("%count%"))throw new Error('Fragment template must contain "%count%".');if(!e.includes("%forloop%"))throw new Error('Fragment template must contain "%forloop%".')}generateShader(t){if(!this.programCache[t]){const e=new Int32Array(t);for(let s=0;s<t;s++)e[s]=s;this.defaultGroupCache[t]=rm.from({uSamplers:e},!0);let i=this.fragTemplate;i=i.replace(/%count%/gi,`${t}`),i=i.replace(/%forloop%/gi,this.generateSampleSrc(t)),this.programCache[t]=new im(this.vertexSrc,i)}const e={tint:new Float32Array([1,1,1,1]),translationMatrix:new Pf,default:this.defaultGroupCache[t]};return new nm(this.programCache[t],e)}generateSampleSrc(t){let e="";e+="\n",e+="\n";for(let i=0;i<t;i++)i>0&&(e+="\nelse "),i<t-1&&(e+=`if(vTextureId < ${i}.5)`),e+="\n{",e+=`\n\tcolor = texture2D(uSamplers[${i}], vTextureCoord);`,e+="\n}";return e+="\n",e+="\n",e}}class am{constructor(){this.elements=[],this.ids=[],this.count=0}clear(){for(let t=0;t<this.count;t++)this.elements[t]=null;this.count=0}}class lm{constructor(t){this.renderer=t}flush(){}destroy(){this.renderer=null}start(){}stop(){this.flush()}render(t){}}const hm=class t extends lm{constructor(e){super(e),this.setShaderGenerator(),this.geometryClass=cf,this.vertexSize=6,this.state=jp.for2d(),this.size=4*t.defaultBatchSize,this._vertexCount=0,this._indexCount=0,this._bufferedElements=[],this._bufferedTextures=[],this._bufferSize=0,this._shader=null,this._packedGeometries=[],this._packedGeometryPoolSize=2,this._flushId=0,this._aBuffers={},this._iBuffers={},this.maxTextures=1,this.renderer.on("prerender",this.onPrerender,this),e.runners.contextChange.add(this),this._dcIndex=0,this._aIndex=0,this._iIndex=0,this._attributeBuffer=null,this._indexBuffer=null,this._tempBoundTextures=[]}static get defaultMaxTextures(){return this._defaultMaxTextures=this._defaultMaxTextures??function(t){let e=!0;const i=Oh.ADAPTER.getNavigator();if(qh.tablet||qh.phone){if(qh.apple.device){const t=i.userAgent.match(/OS (\d+)_(\d+)?/);t&&parseInt(t[1],10)<11&&(e=!1)}if(qh.android.device){const t=i.userAgent.match(/Android\s([0-9.]*)/);t&&parseInt(t[1],10)<7&&(e=!1)}}return e?t:4}(32),this._defaultMaxTextures}static set defaultMaxTextures(t){this._defaultMaxTextures=t}static get canUploadSameBuffer(){return this._canUploadSameBuffer=this._canUploadSameBuffer??!qh.apple.device,this._canUploadSameBuffer}static set canUploadSameBuffer(t){this._canUploadSameBuffer=t}get MAX_TEXTURES(){return Md("7.1.0","BatchRenderer#MAX_TEXTURES renamed to BatchRenderer#maxTextures"),this.maxTextures}static get defaultVertexSrc(){return"precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"}static get defaultFragmentTemplate(){return"varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"}setShaderGenerator({vertex:e=t.defaultVertexSrc,fragment:i=t.defaultFragmentTemplate}={}){this.shaderGenerator=new om(e,i)}contextChange(){const e=this.renderer.gl;Oh.PREFER_ENV===dh.WEBGL_LEGACY?this.maxTextures=1:(this.maxTextures=Math.min(e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),t.defaultMaxTextures),this.maxTextures=function(t,e){if(0===t)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const i=e.createShader(e.FRAGMENT_SHADER);for(;;){const s=Hp.replace(/%forloop%/gi,$p(t));if(e.shaderSource(i,s),e.compileShader(i),e.getShaderParameter(i,e.COMPILE_STATUS))break;t=t/2|0}return t}(this.maxTextures,e)),this._shader=this.shaderGenerator.generateShader(this.maxTextures);for(let t=0;t<this._packedGeometryPoolSize;t++)this._packedGeometries[t]=new this.geometryClass;this.initFlushBuffers()}initFlushBuffers(){const{_drawCallPool:e,_textureArrayPool:i}=t,s=this.size/4,r=Math.floor(s/this.maxTextures)+1;for(;e.length<s;)e.push(new ef);for(;i.length<r;)i.push(new am);for(let t=0;t<this.maxTextures;t++)this._tempBoundTextures[t]=null}onPrerender(){this._flushId=0}render(t){t._texture.valid&&(this._vertexCount+t.vertexData.length/2>this.size&&this.flush(),this._vertexCount+=t.vertexData.length/2,this._indexCount+=t.indices.length,this._bufferedTextures[this._bufferSize]=t._texture.baseTexture,this._bufferedElements[this._bufferSize++]=t)}buildTexturesAndDrawCalls(){const{_bufferedTextures:e,maxTextures:i}=this,s=t._textureArrayPool,r=this.renderer.batch,n=this._tempBoundTextures,o=this.renderer.textureGC.count;let a=++tf._globalBatch,l=0,h=s[0],u=0;r.copyBoundTextures(n,i);for(let t=0;t<this._bufferSize;++t){const c=e[t];e[t]=null,c._batchEnabled!==a&&(h.count>=i&&(r.boundArray(h,n,a,i),this.buildDrawCalls(h,u,t),u=t,h=s[++l],++a),c._batchEnabled=a,c.touched=o,h.elements[h.count++]=c)}h.count>0&&(r.boundArray(h,n,a,i),this.buildDrawCalls(h,u,this._bufferSize),++l,++a);for(let t=0;t<n.length;t++)n[t]=null;tf._globalBatch=a}buildDrawCalls(e,i,s){const{_bufferedElements:r,_attributeBuffer:n,_indexBuffer:o,vertexSize:a}=this,l=t._drawCallPool;let h=this._dcIndex,u=this._aIndex,c=this._iIndex,d=l[h];d.start=this._iIndex,d.texArray=e;for(let t=i;t<s;++t){const s=r[t],p=s._texture.baseTexture,f=fp[p.alphaMode?1:0][s.blendMode];r[t]=null,i<t&&d.blend!==f&&(d.size=c-d.start,i=t,d=l[++h],d.texArray=e,d.start=c),this.packInterleavedGeometry(s,n,o,u,c),u+=s.vertexData.length/2*a,c+=s.indices.length,d.blend=f}i<s&&(d.size=c-d.start,++h),this._dcIndex=h,this._aIndex=u,this._iIndex=c}bindAndClearTexArray(t){const e=this.renderer.texture;for(let i=0;i<t.count;i++)e.bind(t.elements[i],t.ids[i]),t.elements[i]=null;t.count=0}updateGeometry(){const{_packedGeometries:e,_attributeBuffer:i,_indexBuffer:s}=this;t.canUploadSameBuffer?(e[this._flushId]._buffer.update(i.rawBinaryData),e[this._flushId]._indexBuffer.update(s),this.renderer.geometry.updateBuffers()):(this._packedGeometryPoolSize<=this._flushId&&(this._packedGeometryPoolSize++,e[this._flushId]=new this.geometryClass),e[this._flushId]._buffer.update(i.rawBinaryData),e[this._flushId]._indexBuffer.update(s),this.renderer.geometry.bind(e[this._flushId]),this.renderer.geometry.updateBuffers(),this._flushId++)}drawBatches(){const e=this._dcIndex,{gl:i,state:s}=this.renderer,r=t._drawCallPool;let n=null;for(let t=0;t<e;t++){const{texArray:e,type:o,size:a,start:l,blend:h}=r[t];n!==e&&(n=e,this.bindAndClearTexArray(e)),this.state.blendMode=h,s.set(this.state),i.drawElements(o,a,i.UNSIGNED_SHORT,2*l)}}flush(){0!==this._vertexCount&&(this._attributeBuffer=this.getAttributeBuffer(this._vertexCount),this._indexBuffer=this.getIndexBuffer(this._indexCount),this._aIndex=0,this._iIndex=0,this._dcIndex=0,this.buildTexturesAndDrawCalls(),this.updateGeometry(),this.drawBatches(),this._bufferSize=0,this._vertexCount=0,this._indexCount=0)}start(){this.renderer.state.set(this.state),this.renderer.texture.ensureSamplerType(this.maxTextures),this.renderer.shader.bind(this._shader),t.canUploadSameBuffer&&this.renderer.geometry.bind(this._packedGeometries[this._flushId])}stop(){this.flush()}destroy(){for(let t=0;t<this._packedGeometryPoolSize;t++)this._packedGeometries[t]&&this._packedGeometries[t].destroy();this.renderer.off("prerender",this.onPrerender,this),this._aBuffers=null,this._iBuffers=null,this._packedGeometries=null,this._attributeBuffer=null,this._indexBuffer=null,this._shader&&(this._shader.destroy(),this._shader=null),super.destroy()}getAttributeBuffer(t){const e=vp(Math.ceil(t/8)),i=bp(e),s=8*e;this._aBuffers.length<=i&&(this._iBuffers.length=i+1);let r=this._aBuffers[s];return r||(this._aBuffers[s]=r=new Yp(s*this.vertexSize*4)),r}getIndexBuffer(t){const e=vp(Math.ceil(t/12)),i=bp(e),s=12*e;this._iBuffers.length<=i&&(this._iBuffers.length=i+1);let r=this._iBuffers[i];return r||(this._iBuffers[i]=r=new Uint16Array(s)),r}packInterleavedGeometry(t,e,i,s,r){const{uint32View:n,float32View:o}=e,a=s/this.vertexSize,l=t.uvs,h=t.indices,u=t.vertexData,c=t._texture.baseTexture._batchLocation,d=Math.min(t.worldAlpha,1),p=pp.shared.setValue(t._tintRGB).toPremultiplied(d,t._texture.baseTexture.alphaMode>0);for(let f=0;f<u.length;f+=2)o[s++]=u[f],o[s++]=u[f+1],o[s++]=l[f],o[s++]=l[f+1],n[s++]=p,o[s++]=c;for(let f=0;f<h.length;f++)i[r++]=a+h[f]}};hm.defaultBatchSize=4096,hm.extension={name:"batch",type:Up.RendererPlugin},hm._drawCallPool=[],hm._textureArrayPool=[];let um=hm;Wp.add(um);const cm=class t extends nm{constructor(e,i,s){super(im.from(e||t.defaultVertexSrc,i||t.defaultFragmentSrc),s),this.padding=0,this.resolution=t.defaultResolution,this.multisample=t.defaultMultisample,this.enabled=!0,this.autoFit=!0,this.state=new jp}apply(t,e,i,s,r){t.applyFilter(this,e,i,s)}get blendMode(){return this.state.blendMode}set blendMode(t){this.state.blendMode=t}get resolution(){return this._resolution}set resolution(t){this._resolution=t}static get defaultVertexSrc(){return"attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"}static get defaultFragmentSrc(){return"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"}};cm.defaultResolution=1,cm.defaultMultisample=Ch.NONE;let dm=cm;class pm{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new pp(0),this.alpha=1}init(t){this.clearBeforeRender=t.clearBeforeRender;const{backgroundColor:e,background:i,backgroundAlpha:s}=t,r=i??e;void 0!==r&&(this.color=r),this.alpha=s}get color(){return this._backgroundColor.value}set color(t){this._backgroundColor.setValue(t)}get alpha(){return this._backgroundColor.alpha}set alpha(t){this._backgroundColor.setAlpha(t)}get backgroundColor(){return this._backgroundColor}destroy(){}}pm.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0},pm.extension={type:[Up.RendererSystem,Up.CanvasRendererSystem],name:"background"},Wp.add(pm);class fm{constructor(t){this.renderer=t,this.emptyRenderer=new lm(t),this.currentRenderer=this.emptyRenderer}setObjectRenderer(t){this.currentRenderer!==t&&(this.currentRenderer.stop(),this.currentRenderer=t,this.currentRenderer.start())}flush(){this.setObjectRenderer(this.emptyRenderer)}reset(){this.setObjectRenderer(this.emptyRenderer)}copyBoundTextures(t,e){const{boundTextures:i}=this.renderer.texture;for(let s=e-1;s>=0;--s)t[s]=i[s]||null,t[s]&&(t[s]._batchLocation=s)}boundArray(t,e,i,s){const{elements:r,ids:n,count:o}=t;let a=0;for(let l=0;l<o;l++){const t=r[l],o=t._batchLocation;if(o>=0&&o<s&&e[o]===t)n[l]=o;else for(;a<s;){const s=e[a];if(!s||s._batchEnabled!==i||s._batchLocation!==a){n[l]=a,t._batchLocation=a,e[a]=t;break}a++}}}destroy(){this.renderer=null}}fm.extension={type:Up.RendererSystem,name:"batch"},Wp.add(fm);let mm=0;class gm{constructor(t){this.renderer=t,this.webGLVersion=1,this.extensions={},this.supports={uint32Indices:!1},this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(t){this.gl=t,this.renderer.gl=t,this.renderer.CONTEXT_UID=mm++}init(t){if(t.context)this.initFromContext(t.context);else{const e=this.renderer.background.alpha<1,i=t.premultipliedAlpha;this.preserveDrawingBuffer=t.preserveDrawingBuffer,this.useContextAlpha=t.useContextAlpha,this.powerPreference=t.powerPreference,this.initFromOptions({alpha:e,premultipliedAlpha:i,antialias:t.antialias,stencil:!0,preserveDrawingBuffer:t.preserveDrawingBuffer,powerPreference:t.powerPreference})}}initFromContext(t){this.gl=t,this.validateContext(t),this.renderer.gl=t,this.renderer.CONTEXT_UID=mm++,this.renderer.runners.contextChange.emit(t);const e=this.renderer.view;void 0!==e.addEventListener&&(e.addEventListener("webglcontextlost",this.handleContextLost,!1),e.addEventListener("webglcontextrestored",this.handleContextRestored,!1))}initFromOptions(t){const e=this.createContext(this.renderer.view,t);this.initFromContext(e)}createContext(t,e){let i;if(Oh.PREFER_ENV>=dh.WEBGL2&&(i=t.getContext("webgl2",e)),i)this.webGLVersion=2;else if(this.webGLVersion=1,i=t.getContext("webgl",e)||t.getContext("experimental-webgl",e),!i)throw new Error("This browser does not support WebGL. Try using the canvas renderer");return this.gl=i,this.getExtensions(),this.gl}getExtensions(){const{gl:t}=this,e={loseContext:t.getExtension("WEBGL_lose_context"),anisotropicFiltering:t.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),s3tc:t.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:t.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:t.getExtension("WEBGL_compressed_texture_etc"),etc1:t.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:t.getExtension("WEBGL_compressed_texture_atc"),astc:t.getExtension("WEBGL_compressed_texture_astc"),bptc:t.getExtension("EXT_texture_compression_bptc")};1===this.webGLVersion?Object.assign(this.extensions,e,{drawBuffers:t.getExtension("WEBGL_draw_buffers"),depthTexture:t.getExtension("WEBGL_depth_texture"),vertexArrayObject:t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:t.getExtension("OES_element_index_uint"),floatTexture:t.getExtension("OES_texture_float"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),textureHalfFloat:t.getExtension("OES_texture_half_float"),textureHalfFloatLinear:t.getExtension("OES_texture_half_float_linear")}):2===this.webGLVersion&&Object.assign(this.extensions,e,{colorBufferFloat:t.getExtension("EXT_color_buffer_float")})}handleContextLost(t){t.preventDefault(),setTimeout(()=>{this.gl.isContextLost()&&this.extensions.loseContext&&this.extensions.loseContext.restoreContext()},0)}handleContextRestored(){this.renderer.runners.contextChange.emit(this.gl)}destroy(){const t=this.renderer.view;this.renderer=null,void 0!==t.removeEventListener&&(t.removeEventListener("webglcontextlost",this.handleContextLost),t.removeEventListener("webglcontextrestored",this.handleContextRestored)),this.gl.useProgram(null),this.extensions.loseContext&&this.extensions.loseContext.loseContext()}postrender(){this.renderer.objectRenderer.renderingToScreen&&this.gl.flush()}validateContext(t){const e=t.getContextAttributes(),i="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext;i&&(this.webGLVersion=2),e&&!e.stencil&&console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const s=i||!!t.getExtension("OES_element_index_uint");this.supports.uint32Indices=s,s||console.warn("Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly")}}gm.defaultOptions={context:null,antialias:!1,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:"default"},gm.extension={type:Up.RendererSystem,name:"context"},Wp.add(gm);class ym{constructor(t,e){if(this.width=Math.round(t),this.height=Math.round(e),!this.width||!this.height)throw new Error("Framebuffer width or height is zero");this.stencil=!1,this.depth=!1,this.dirtyId=0,this.dirtyFormat=0,this.dirtySize=0,this.depthTexture=null,this.colorTextures=[],this.glFramebuffers={},this.disposeRunner=new qp("disposeFramebuffer"),this.multisample=Ch.NONE}get colorTexture(){return this.colorTextures[0]}addColorTexture(t=0,e){return this.colorTextures[t]=e||new tf(null,{scaleMode:wh.NEAREST,resolution:1,mipmap:Ph.OFF,width:this.width,height:this.height}),this.dirtyId++,this.dirtyFormat++,this}addDepthTexture(t){return this.depthTexture=t||new tf(null,{scaleMode:wh.NEAREST,resolution:1,width:this.width,height:this.height,mipmap:Ph.OFF,format:yh.DEPTH_COMPONENT,type:xh.UNSIGNED_SHORT}),this.dirtyId++,this.dirtyFormat++,this}enableDepth(){return this.depth=!0,this.dirtyId++,this.dirtyFormat++,this}enableStencil(){return this.stencil=!0,this.dirtyId++,this.dirtyFormat++,this}resize(t,e){if(t=Math.round(t),e=Math.round(e),!t||!e)throw new Error("Framebuffer width and height must not be zero");if(t!==this.width||e!==this.height){this.width=t,this.height=e,this.dirtyId++,this.dirtySize++;for(let i=0;i<this.colorTextures.length;i++){const s=this.colorTextures[i],r=s.resolution;s.setSize(t/r,e/r)}if(this.depthTexture){const i=this.depthTexture.resolution;this.depthTexture.setSize(t/i,e/i)}}}dispose(){this.disposeRunner.emit(this,!1)}destroyDepthTexture(){this.depthTexture&&(this.depthTexture.destroy(),this.depthTexture=null,++this.dirtyId,++this.dirtyFormat)}}class vm extends tf{constructor(t={}){if("number"==typeof t){t={width:arguments[0],height:arguments[1],scaleMode:arguments[2],resolution:arguments[3]}}t.width=t.width??100,t.height=t.height??100,t.multisample??(t.multisample=Ch.NONE),super(null,t),this.mipmap=Ph.OFF,this.valid=!0,this._clear=new pp([0,0,0,0]),this.framebuffer=new ym(this.realWidth,this.realHeight).addColorTexture(0,this),this.framebuffer.multisample=t.multisample,this.maskStack=[],this.filterStack=[{}]}set clearColor(t){this._clear.setValue(t)}get clearColor(){return this._clear.value}get clear(){return this._clear}get multisample(){return this.framebuffer.multisample}set multisample(t){this.framebuffer.multisample=t}resize(t,e){this.framebuffer.resize(t*this.resolution,e*this.resolution),this.setRealSize(this.framebuffer.width,this.framebuffer.height)}dispose(){this.framebuffer.dispose(),super.dispose()}destroy(){super.destroy(),this.framebuffer.destroyDepthTexture(),this.framebuffer=null}}class xm extends Jp{constructor(t){const e=t;super(e.naturalWidth||e.videoWidth||e.displayWidth||e.width,e.naturalHeight||e.videoHeight||e.displayHeight||e.height),this.source=t,this.noSubImage=!1}static crossOrigin(t,e,i){void 0!==i||e.startsWith("data:")?!1!==i&&(t.crossOrigin="string"==typeof i?i:"anonymous"):t.crossOrigin=kp(e)}upload(t,e,i,s){const r=t.gl,n=e.realWidth,o=e.realHeight;if(s=s||this.source,typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement){if(!s.complete||0===s.naturalWidth)return!1}else if(typeof HTMLVideoElement<"u"&&s instanceof HTMLVideoElement&&s.readyState<=1)return!1;return r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.alphaMode===Eh.UNPACK),this.noSubImage||e.target!==r.TEXTURE_2D||i.width!==n||i.height!==o?(i.width=n,i.height=o,r.texImage2D(e.target,0,i.internalFormat,e.format,i.type,s)):r.texSubImage2D(r.TEXTURE_2D,0,0,0,e.format,i.type,s),!0}update(){if(this.destroyed)return;const t=this.source,e=t.naturalWidth||t.videoWidth||t.width,i=t.naturalHeight||t.videoHeight||t.height;this.resize(e,i),super.update()}dispose(){this.source=null}}class bm extends xm{constructor(t,e){if(e=e||{},"string"==typeof t){const i=new Image;xm.crossOrigin(i,t,e.crossorigin),i.src=t,t=i}super(t),!t.complete&&this._width&&this._height&&(this._width=0,this._height=0),this.url=t.src,this._process=null,this.preserveBitmap=!1,this.createBitmap=(e.createBitmap??Oh.CREATE_IMAGE_BITMAP)&&!!globalThis.createImageBitmap,this.alphaMode="number"==typeof e.alphaMode?e.alphaMode:null,this.bitmap=null,this._load=null,!1!==e.autoLoad&&this.load()}load(t){return this._load||(void 0!==t&&(this.createBitmap=t),this._load=new Promise((t,e)=>{const i=this.source;this.url=i.src;const s=()=>{this.destroyed||(i.onload=null,i.onerror=null,this.update(),this._load=null,this.createBitmap?t(this.process()):t(this))};i.complete&&i.src?s():(i.onload=s,i.onerror=t=>{e(t),this.onError.emit(t)})})),this._load}process(){const t=this.source;if(null!==this._process)return this._process;if(null!==this.bitmap||!globalThis.createImageBitmap)return Promise.resolve(this);const e=globalThis.createImageBitmap,i=!t.crossOrigin||"anonymous"===t.crossOrigin;return this._process=fetch(t.src,{mode:i?"cors":"no-cors"}).then(t=>t.blob()).then(i=>e(i,0,0,t.width,t.height,{premultiplyAlpha:null===this.alphaMode||this.alphaMode===Eh.UNPACK?"premultiply":"none"})).then(t=>this.destroyed?Promise.reject():(this.bitmap=t,this.update(),this._process=null,Promise.resolve(this))),this._process}upload(t,e,i){if("number"==typeof this.alphaMode&&(e.alphaMode=this.alphaMode),!this.createBitmap)return super.upload(t,e,i);if(!this.bitmap&&(this.process(),!this.bitmap))return!1;if(super.upload(t,e,i,this.bitmap),!this.preserveBitmap){let t=!0;const s=e._glTextures;for(const r in s){const n=s[r];if(n!==i&&n.dirtyId!==e.dirtyId){t=!1;break}}t&&(this.bitmap.close&&this.bitmap.close(),this.bitmap=null)}return!0}dispose(){this.source.onload=null,this.source.onerror=null,super.dispose(),this.bitmap&&(this.bitmap.close(),this.bitmap=null),this._process=null,this._load=null}static test(t){return typeof HTMLImageElement<"u"&&("string"==typeof t||t instanceof HTMLImageElement)}}class wm{constructor(){this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsFloat32=new Float32Array(8)}set(t,e,i){const s=e.width,r=e.height;if(i){const e=t.width/2/s,n=t.height/2/r,o=t.x/s+e,a=t.y/r+n;i=Of.add(i,Of.NW),this.x0=o+e*Of.uX(i),this.y0=a+n*Of.uY(i),i=Of.add(i,2),this.x1=o+e*Of.uX(i),this.y1=a+n*Of.uY(i),i=Of.add(i,2),this.x2=o+e*Of.uX(i),this.y2=a+n*Of.uY(i),i=Of.add(i,2),this.x3=o+e*Of.uX(i),this.y3=a+n*Of.uY(i)}else this.x0=t.x/s,this.y0=t.y/r,this.x1=(t.x+t.width)/s,this.y1=t.y/r,this.x2=(t.x+t.width)/s,this.y2=(t.y+t.height)/r,this.x3=t.x/s,this.y3=(t.y+t.height)/r;this.uvsFloat32[0]=this.x0,this.uvsFloat32[1]=this.y0,this.uvsFloat32[2]=this.x1,this.uvsFloat32[3]=this.y1,this.uvsFloat32[4]=this.x2,this.uvsFloat32[5]=this.y2,this.uvsFloat32[6]=this.x3,this.uvsFloat32[7]=this.y3}}wm.prototype.toString=function(){return`[@pixi/core:TextureUvs x0=${this.x0} y0=${this.y0} x1=${this.x1} y1=${this.y1} x2=${this.x2} y2=${this.y2} x3=${this.x3} y3=${this.y3}]`};const _m=new wm;function Pm(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}class Em extends Qh{constructor(t,e,i,s,r,n,o){if(super(),this.noFrame=!1,e||(this.noFrame=!0,e=new vf(0,0,1,1)),t instanceof Em&&(t=t.baseTexture),this.baseTexture=t,this._frame=e,this.trim=s,this.valid=!1,this.destroyed=!1,this._uvs=_m,this.uvMatrix=null,this.orig=i||e,this._rotate=Number(r||0),!0===r)this._rotate=2;else if(this._rotate%2!=0)throw new Error("attempt to use diamond-shaped UVs. If you are sure, set rotation manually");this.defaultAnchor=n?new gf(n.x,n.y):new gf(0,0),this.defaultBorders=o,this._updateID=0,this.textureCacheIds=[],t.valid?this.noFrame?t.valid&&this.onBaseTextureUpdated(t):this.frame=e:t.once("loaded",this.onBaseTextureUpdated,this),this.noFrame&&t.on("update",this.onBaseTextureUpdated,this)}update(){this.baseTexture.resource&&this.baseTexture.resource.update()}onBaseTextureUpdated(t){if(this.noFrame){if(!this.baseTexture.valid)return;this._frame.width=t.width,this._frame.height=t.height,this.valid=!0,this.updateUvs()}else this.frame=this._frame;this.emit("update",this)}destroy(t){if(this.baseTexture){if(t){const{resource:t}=this.baseTexture;t?.url&&Sp[t.url]&&Em.removeFromCache(t.url),this.baseTexture.destroy()}this.baseTexture.off("loaded",this.onBaseTextureUpdated,this),this.baseTexture.off("update",this.onBaseTextureUpdated,this),this.baseTexture=null}this._frame=null,this._uvs=null,this.trim=null,this.orig=null,this.valid=!1,Em.removeFromCache(this),this.textureCacheIds=null,this.destroyed=!0,this.emit("destroyed",this),this.removeAllListeners()}clone(){const t=this._frame.clone(),e=this._frame===this.orig?t:this.orig.clone(),i=new Em(this.baseTexture,!this.noFrame&&t,e,this.trim?.clone(),this.rotate,this.defaultAnchor,this.defaultBorders);return this.noFrame&&(i._frame=t),i}updateUvs(){this._uvs===_m&&(this._uvs=new wm),this._uvs.set(this._frame,this.baseTexture,this.rotate),this._updateID++}static from(t,e={},i=Oh.STRICT_TEXTURE_CACHE){const s="string"==typeof t;let r=null;if(s)r=t;else if(t instanceof tf){if(!t.cacheId){const i=e?.pixiIdPrefix||"pixiid";t.cacheId=`${i}-${Ep()}`,tf.addToCache(t,t.cacheId)}r=t.cacheId}else{if(!t._pixiId){const i=e?.pixiIdPrefix||"pixiid";t._pixiId=`${i}_${Ep()}`}r=t._pixiId}let n=Sp[r];if(s&&i&&!n)throw new Error(`The cacheId "${r}" does not exist in TextureCache.`);return n||t instanceof tf?!n&&t instanceof tf&&(n=new Em(t),Em.addToCache(n,r)):(e.resolution||(e.resolution=Fp(t)),n=new Em(new tf(t,e)),n.baseTexture.cacheId=r,tf.addToCache(n.baseTexture,r),Em.addToCache(n,r)),n}static fromURL(t,e){const i=Object.assign({autoLoad:!1},e?.resourceOptions),s=Em.from(t,Object.assign({resourceOptions:i},e),!1),r=s.baseTexture.resource;return s.baseTexture.valid?Promise.resolve(s):r.load().then(()=>Promise.resolve(s))}static fromBuffer(t,e,i,s){return new Em(tf.fromBuffer(t,e,i,s))}static fromLoader(t,e,i,s){const r=new tf(t,Object.assign({scaleMode:tf.defaultOptions.scaleMode,resolution:Fp(e)},s)),{resource:n}=r;n instanceof bm&&(n.url=e);const o=new Em(r);return i||(i=e),tf.addToCache(o.baseTexture,i),Em.addToCache(o,i),i!==e&&(tf.addToCache(o.baseTexture,e),Em.addToCache(o,e)),o.baseTexture.valid?Promise.resolve(o):new Promise(t=>{o.baseTexture.once("loaded",()=>t(o))})}static addToCache(t,e){e&&(t.textureCacheIds.includes(e)||t.textureCacheIds.push(e),Sp[e]&&Sp[e]!==t&&console.warn(`Texture added to the cache with an id [${e}] that already had an entry`),Sp[e]=t)}static removeFromCache(t){if("string"==typeof t){const e=Sp[t];if(e){const i=e.textureCacheIds.indexOf(t);return i>-1&&e.textureCacheIds.splice(i,1),delete Sp[t],e}}else if(t?.textureCacheIds){for(let e=0;e<t.textureCacheIds.length;++e)Sp[t.textureCacheIds[e]]===t&&delete Sp[t.textureCacheIds[e]];return t.textureCacheIds.length=0,t}return null}get resolution(){return this.baseTexture.resolution}get frame(){return this._frame}set frame(t){this._frame=t,this.noFrame=!1;const{x:e,y:i,width:s,height:r}=t,n=e+s>this.baseTexture.width,o=i+r>this.baseTexture.height;if(n||o){const t=n&&o?"and":"or",a=`X: ${e} + ${s} = ${e+s} > ${this.baseTexture.width}`,l=`Y: ${i} + ${r} = ${i+r} > ${this.baseTexture.height}`;throw new Error(`Texture Error: frame does not fit inside the base Texture dimensions: ${a} ${t} ${l}`)}this.valid=s&&r&&this.baseTexture.valid,!this.trim&&!this.rotate&&(this.orig=t),this.valid&&this.updateUvs()}get rotate(){return this._rotate}set rotate(t){this._rotate=t,this.valid&&this.updateUvs()}get width(){return this.orig.width}get height(){return this.orig.height}castToBaseTexture(){return this.baseTexture}static get EMPTY(){return Em._EMPTY||(Em._EMPTY=new Em(new tf),Pm(Em._EMPTY),Pm(Em._EMPTY.baseTexture)),Em._EMPTY}static get WHITE(){if(!Em._WHITE){const t=Oh.ADAPTER.createCanvas(16,16),e=t.getContext("2d");t.width=16,t.height=16,e.fillStyle="white",e.fillRect(0,0,16,16),Em._WHITE=new Em(tf.from(t)),Pm(Em._WHITE),Pm(Em._WHITE.baseTexture)}return Em._WHITE}}class Tm extends Em{constructor(t,e){super(t,e),this.valid=!0,this.filterFrame=null,this.filterPoolKey=null,this.updateUvs()}get framebuffer(){return this.baseTexture.framebuffer}get multisample(){return this.framebuffer.multisample}set multisample(t){this.framebuffer.multisample=t}resize(t,e,i=!0){const s=this.baseTexture.resolution,r=Math.round(t*s)/s,n=Math.round(e*s)/s;this.valid=r>0&&n>0,this._frame.width=this.orig.width=r,this._frame.height=this.orig.height=n,i&&this.baseTexture.resize(r,n),this.updateUvs()}setResolution(t){const{baseTexture:e}=this;e.resolution!==t&&(e.setResolution(t),this.resize(e.width,e.height,!1))}static create(t){return new Tm(new vm(t))}}class Am{constructor(t){this.texturePool={},this.textureOptions=t||{},this.enableFullScreen=!1,this._pixelsWidth=0,this._pixelsHeight=0}createTexture(t,e,i=Ch.NONE){const s=new vm(Object.assign({width:t,height:e,resolution:1,multisample:i},this.textureOptions));return new Tm(s)}getOptimalTexture(t,e,i=1,s=Ch.NONE){let r;t=Math.max(Math.ceil(t*i-1e-6),1),e=Math.max(Math.ceil(e*i-1e-6),1),this.enableFullScreen&&t===this._pixelsWidth&&e===this._pixelsHeight?r=s>1?-s:-1:(r=((65535&(t=vp(t)))<<16|65535&(e=vp(e)))>>>0,s>1&&(r+=4294967296*s)),this.texturePool[r]||(this.texturePool[r]=[]);let n=this.texturePool[r].pop();return n||(n=this.createTexture(t,e,s)),n.filterPoolKey=r,n.setResolution(i),n}getFilterTexture(t,e,i){const s=this.getOptimalTexture(t.width,t.height,e||t.resolution,i||Ch.NONE);return s.filterFrame=t.filterFrame,s}returnTexture(t){const e=t.filterPoolKey;t.filterFrame=null,this.texturePool[e].push(t)}returnFilterTexture(t){this.returnTexture(t)}clear(t){if(t=!1!==t)for(const e in this.texturePool){const t=this.texturePool[e];if(t)for(let e=0;e<t.length;e++)t[e].destroy(!0)}this.texturePool={}}setScreenSize(t){if(t.width!==this._pixelsWidth||t.height!==this._pixelsHeight){this.enableFullScreen=t.width>0&&t.height>0;for(const t in this.texturePool){if(!(Number(t)<0))continue;const e=this.texturePool[t];if(e)for(let t=0;t<e.length;t++)e[t].destroy(!0);this.texturePool[t]=[]}this._pixelsWidth=t.width,this._pixelsHeight=t.height}}}Am.SCREEN_KEY=-1;class Im extends uf{constructor(){super(),this.addAttribute("aVertexPosition",new Float32Array([0,0,1,0,1,1,0,1])).addIndex([0,1,3,2])}}class Sm extends uf{constructor(){super(),this.vertices=new Float32Array([-1,-1,1,-1,1,1,-1,1]),this.uvs=new Float32Array([0,0,1,0,1,1,0,1]),this.vertexBuffer=new rf(this.vertices),this.uvBuffer=new rf(this.uvs),this.addAttribute("aVertexPosition",this.vertexBuffer).addAttribute("aTextureCoord",this.uvBuffer).addIndex([0,1,2,0,2,3])}map(t,e){let i=0,s=0;return this.uvs[0]=i,this.uvs[1]=s,this.uvs[2]=i+e.width/t.width,this.uvs[3]=s,this.uvs[4]=i+e.width/t.width,this.uvs[5]=s+e.height/t.height,this.uvs[6]=i,this.uvs[7]=s+e.height/t.height,i=e.x,s=e.y,this.vertices[0]=i,this.vertices[1]=s,this.vertices[2]=i+e.width,this.vertices[3]=s,this.vertices[4]=i+e.width,this.vertices[5]=s+e.height,this.vertices[6]=i,this.vertices[7]=s+e.height,this.invalidate(),this}invalidate(){return this.vertexBuffer._updateID++,this.uvBuffer._updateID++,this}}class Cm{constructor(){this.renderTexture=null,this.target=null,this.legacy=!1,this.resolution=1,this.multisample=Ch.NONE,this.sourceFrame=new vf,this.destinationFrame=new vf,this.bindingSourceFrame=new vf,this.bindingDestinationFrame=new vf,this.filters=[],this.transform=null}clear(){this.target=null,this.filters=null,this.renderTexture=null}}const Mm=[new gf,new gf,new gf,new gf],Om=new Pf;class Nm{constructor(t){this.renderer=t,this.defaultFilterStack=[{}],this.texturePool=new Am,this.statePool=[],this.quad=new Im,this.quadUv=new Sm,this.tempRect=new vf,this.activeState={},this.globalUniforms=new rm({outputFrame:new vf,inputSize:new Float32Array(4),inputPixel:new Float32Array(4),inputClamp:new Float32Array(4),resolution:1,filterArea:new Float32Array(4),filterClamp:new Float32Array(4)},!0),this.forceClear=!1,this.useMaxPadding=!1}init(){this.texturePool.setScreenSize(this.renderer.view)}push(t,e){const i=this.renderer,s=this.defaultFilterStack,r=this.statePool.pop()||new Cm,n=i.renderTexture;let o,a;if(n.current){const t=n.current;o=t.resolution,a=t.multisample}else o=i.resolution,a=i.multisample;let l=e[0].resolution||o,h=e[0].multisample??a,u=e[0].padding,c=e[0].autoFit,d=e[0].legacy??!0;for(let m=1;m<e.length;m++){const t=e[m];l=Math.min(l,t.resolution||o),h=Math.min(h,t.multisample??a),u=this.useMaxPadding?Math.max(u,t.padding):u+t.padding,c=c&&t.autoFit,d=d||(t.legacy??!0)}1===s.length&&(this.defaultFilterStack[0].renderTexture=n.current),s.push(r),r.resolution=l,r.multisample=h,r.legacy=d,r.target=t,r.sourceFrame.copyFrom(t.filterArea||t.getBounds(!0)),r.sourceFrame.pad(u);const p=this.tempRect.copyFrom(n.sourceFrame);i.projection.transform&&this.transformAABB(Om.copyFrom(i.projection.transform).invert(),p),c?(r.sourceFrame.fit(p),(r.sourceFrame.width<=0||r.sourceFrame.height<=0)&&(r.sourceFrame.width=0,r.sourceFrame.height=0)):r.sourceFrame.intersects(p)||(r.sourceFrame.width=0,r.sourceFrame.height=0),this.roundFrame(r.sourceFrame,n.current?n.current.resolution:i.resolution,n.sourceFrame,n.destinationFrame,i.projection.transform),r.renderTexture=this.getOptimalFilterTexture(r.sourceFrame.width,r.sourceFrame.height,l,h),r.filters=e,r.destinationFrame.width=r.renderTexture.width,r.destinationFrame.height=r.renderTexture.height;const f=this.tempRect;f.x=0,f.y=0,f.width=r.sourceFrame.width,f.height=r.sourceFrame.height,r.renderTexture.filterFrame=r.sourceFrame,r.bindingSourceFrame.copyFrom(n.sourceFrame),r.bindingDestinationFrame.copyFrom(n.destinationFrame),r.transform=i.projection.transform,i.projection.transform=null,n.bind(r.renderTexture,r.sourceFrame,f),i.framebuffer.clear(0,0,0,0)}pop(){const t=this.defaultFilterStack,e=t.pop(),i=e.filters;this.activeState=e;const s=this.globalUniforms.uniforms;s.outputFrame=e.sourceFrame,s.resolution=e.resolution;const r=s.inputSize,n=s.inputPixel,o=s.inputClamp;if(r[0]=e.destinationFrame.width,r[1]=e.destinationFrame.height,r[2]=1/r[0],r[3]=1/r[1],n[0]=Math.round(r[0]*e.resolution),n[1]=Math.round(r[1]*e.resolution),n[2]=1/n[0],n[3]=1/n[1],o[0]=.5*n[2],o[1]=.5*n[3],o[2]=e.sourceFrame.width*r[2]-.5*n[2],o[3]=e.sourceFrame.height*r[3]-.5*n[3],e.legacy){const t=s.filterArea;t[0]=e.destinationFrame.width,t[1]=e.destinationFrame.height,t[2]=e.sourceFrame.x,t[3]=e.sourceFrame.y,s.filterClamp=s.inputClamp}this.globalUniforms.update();const a=t[t.length-1];if(this.renderer.framebuffer.blit(),1===i.length)i[0].apply(this,e.renderTexture,a.renderTexture,Th.BLEND,e),this.returnFilterTexture(e.renderTexture);else{let t=e.renderTexture,s=this.getOptimalFilterTexture(t.width,t.height,e.resolution);s.filterFrame=t.filterFrame;let r=0;for(r=0;r<i.length-1;++r){1===r&&e.multisample>1&&(s=this.getOptimalFilterTexture(t.width,t.height,e.resolution),s.filterFrame=t.filterFrame),i[r].apply(this,t,s,Th.CLEAR,e);const n=t;t=s,s=n}i[r].apply(this,t,a.renderTexture,Th.BLEND,e),r>1&&e.multisample>1&&this.returnFilterTexture(e.renderTexture),this.returnFilterTexture(t),this.returnFilterTexture(s)}e.clear(),this.statePool.push(e)}bindAndClear(t,e=Th.CLEAR){const{renderTexture:i,state:s}=this.renderer;if(t===this.defaultFilterStack[this.defaultFilterStack.length-1].renderTexture?this.renderer.projection.transform=this.activeState.transform:this.renderer.projection.transform=null,t?.filterFrame){const e=this.tempRect;e.x=0,e.y=0,e.width=t.filterFrame.width,e.height=t.filterFrame.height,i.bind(t,t.filterFrame,e)}else t!==this.defaultFilterStack[this.defaultFilterStack.length-1].renderTexture?i.bind(t):this.renderer.renderTexture.bind(t,this.activeState.bindingSourceFrame,this.activeState.bindingDestinationFrame);const r=1&s.stateId||this.forceClear;(e===Th.CLEAR||e===Th.BLIT&&r)&&this.renderer.framebuffer.clear(0,0,0,0)}applyFilter(t,e,i,s){const r=this.renderer;r.state.set(t.state),this.bindAndClear(i,s),t.uniforms.uSampler=e,t.uniforms.filterGlobals=this.globalUniforms,r.shader.bind(t),t.legacy=!!t.program.attributeData.aTextureCoord,t.legacy?(this.quadUv.map(e._frame,e.filterFrame),r.geometry.bind(this.quadUv),r.geometry.draw(gh.TRIANGLES)):(r.geometry.bind(this.quad),r.geometry.draw(gh.TRIANGLE_STRIP))}calculateSpriteMatrix(t,e){const{sourceFrame:i,destinationFrame:s}=this.activeState,{orig:r}=e._texture,n=t.set(s.width,0,0,s.height,i.x,i.y),o=e.worldTransform.copyTo(Pf.TEMP_MATRIX);return o.invert(),n.prepend(o),n.scale(1/r.width,1/r.height),n.translate(e.anchor.x,e.anchor.y),n}destroy(){this.renderer=null,this.texturePool.clear(!1)}getOptimalFilterTexture(t,e,i=1,s=Ch.NONE){return this.texturePool.getOptimalTexture(t,e,i,s)}getFilterTexture(t,e,i){if("number"==typeof t){const i=t;t=e,e=i}t=t||this.activeState.renderTexture;const s=this.texturePool.getOptimalTexture(t.width,t.height,e||t.resolution,i||Ch.NONE);return s.filterFrame=t.filterFrame,s}returnFilterTexture(t){this.texturePool.returnTexture(t)}emptyPool(){this.texturePool.clear(!0)}resize(){this.texturePool.setScreenSize(this.renderer.view)}transformAABB(t,e){const i=Mm[0],s=Mm[1],r=Mm[2],n=Mm[3];i.set(e.left,e.top),s.set(e.left,e.bottom),r.set(e.right,e.top),n.set(e.right,e.bottom),t.apply(i,i),t.apply(s,s),t.apply(r,r),t.apply(n,n);const o=Math.min(i.x,s.x,r.x,n.x),a=Math.min(i.y,s.y,r.y,n.y),l=Math.max(i.x,s.x,r.x,n.x),h=Math.max(i.y,s.y,r.y,n.y);e.x=o,e.y=a,e.width=l-o,e.height=h-a}roundFrame(t,e,i,s,r){if(!(t.width<=0||t.height<=0||i.width<=0||i.height<=0)){if(r){const{a:t,b:e,c:i,d:s}=r;if((Math.abs(e)>1e-4||Math.abs(i)>1e-4)&&(Math.abs(t)>1e-4||Math.abs(s)>1e-4))return}(r=r?Om.copyFrom(r):Om.identity()).translate(-i.x,-i.y).scale(s.width/i.width,s.height/i.height).translate(s.x,s.y),this.transformAABB(r,t),t.ceil(e),this.transformAABB(r.invert(),t)}}}Nm.extension={type:Up.RendererSystem,name:"filter"},Wp.add(Nm);class Lm{constructor(t){this.framebuffer=t,this.stencil=null,this.dirtyId=-1,this.dirtyFormat=-1,this.dirtySize=-1,this.multisample=Ch.NONE,this.msaaBuffer=null,this.blitFramebuffer=null,this.mipLevel=0}}const Rm=new vf;class Bm{constructor(t){this.renderer=t,this.managedFramebuffers=[],this.unknownFramebuffer=new ym(10,10),this.msaaSamples=null}contextChange(){this.disposeAll(!0);const t=this.gl=this.renderer.gl;if(this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.current=this.unknownFramebuffer,this.viewport=new vf,this.hasMRT=!0,this.writeDepthTexture=!0,1===this.renderer.context.webGLVersion){let e=this.renderer.context.extensions.drawBuffers,i=this.renderer.context.extensions.depthTexture;Oh.PREFER_ENV===dh.WEBGL_LEGACY&&(e=null,i=null),e?t.drawBuffers=t=>e.drawBuffersWEBGL(t):(this.hasMRT=!1,t.drawBuffers=()=>{}),i||(this.writeDepthTexture=!1)}else this.msaaSamples=t.getInternalformatParameter(t.RENDERBUFFER,t.RGBA8,t.SAMPLES)}bind(t,e,i=0){const{gl:s}=this;if(t){const r=t.glFramebuffers[this.CONTEXT_UID]||this.initFramebuffer(t);this.current!==t&&(this.current=t,s.bindFramebuffer(s.FRAMEBUFFER,r.framebuffer)),r.mipLevel!==i&&(t.dirtyId++,t.dirtyFormat++,r.mipLevel=i),r.dirtyId!==t.dirtyId&&(r.dirtyId=t.dirtyId,r.dirtyFormat!==t.dirtyFormat?(r.dirtyFormat=t.dirtyFormat,r.dirtySize=t.dirtySize,this.updateFramebuffer(t,i)):r.dirtySize!==t.dirtySize&&(r.dirtySize=t.dirtySize,this.resizeFramebuffer(t)));for(let e=0;e<t.colorTextures.length;e++){const i=t.colorTextures[e];this.renderer.texture.unbind(i.parentTextureArray||i)}if(t.depthTexture&&this.renderer.texture.unbind(t.depthTexture),e){const t=e.width>>i,s=e.height>>i,r=t/e.width;this.setViewport(e.x*r,e.y*r,t,s)}else{const e=t.width>>i,s=t.height>>i;this.setViewport(0,0,e,s)}}else this.current&&(this.current=null,s.bindFramebuffer(s.FRAMEBUFFER,null)),e?this.setViewport(e.x,e.y,e.width,e.height):this.setViewport(0,0,this.renderer.width,this.renderer.height)}setViewport(t,e,i,s){const r=this.viewport;t=Math.round(t),e=Math.round(e),i=Math.round(i),s=Math.round(s),(r.width!==i||r.height!==s||r.x!==t||r.y!==e)&&(r.x=t,r.y=e,r.width=i,r.height=s,this.gl.viewport(t,e,i,s))}get size(){return this.current?{x:0,y:0,width:this.current.width,height:this.current.height}:{x:0,y:0,width:this.renderer.width,height:this.renderer.height}}clear(t,e,i,s,r=fh.COLOR|fh.DEPTH){const{gl:n}=this;n.clearColor(t,e,i,s),n.clear(r)}initFramebuffer(t){const{gl:e}=this,i=new Lm(e.createFramebuffer());return i.multisample=this.detectSamples(t.multisample),t.glFramebuffers[this.CONTEXT_UID]=i,this.managedFramebuffers.push(t),t.disposeRunner.add(this),i}resizeFramebuffer(t){const{gl:e}=this,i=t.glFramebuffers[this.CONTEXT_UID];if(i.stencil){let s;e.bindRenderbuffer(e.RENDERBUFFER,i.stencil),s=1===this.renderer.context.webGLVersion?e.DEPTH_STENCIL:t.depth&&t.stencil?e.DEPTH24_STENCIL8:t.depth?e.DEPTH_COMPONENT24:e.STENCIL_INDEX8,i.msaaBuffer?e.renderbufferStorageMultisample(e.RENDERBUFFER,i.multisample,s,t.width,t.height):e.renderbufferStorage(e.RENDERBUFFER,s,t.width,t.height)}const s=t.colorTextures;let r=s.length;e.drawBuffers||(r=Math.min(r,1));for(let n=0;n<r;n++){const r=s[n],o=r.parentTextureArray||r;this.renderer.texture.bind(o,0),0===n&&i.msaaBuffer&&(e.bindRenderbuffer(e.RENDERBUFFER,i.msaaBuffer),e.renderbufferStorageMultisample(e.RENDERBUFFER,i.multisample,o._glTextures[this.CONTEXT_UID].internalFormat,t.width,t.height))}t.depthTexture&&this.writeDepthTexture&&this.renderer.texture.bind(t.depthTexture,0)}updateFramebuffer(t,e){const{gl:i}=this,s=t.glFramebuffers[this.CONTEXT_UID],r=t.colorTextures;let n=r.length;i.drawBuffers||(n=Math.min(n,1)),s.multisample>1&&this.canMultisampleFramebuffer(t)?s.msaaBuffer=s.msaaBuffer||i.createRenderbuffer():s.msaaBuffer&&(i.deleteRenderbuffer(s.msaaBuffer),s.msaaBuffer=null,s.blitFramebuffer&&(s.blitFramebuffer.dispose(),s.blitFramebuffer=null));const o=[];for(let a=0;a<n;a++){const n=r[a],l=n.parentTextureArray||n;this.renderer.texture.bind(l,0),0===a&&s.msaaBuffer?(i.bindRenderbuffer(i.RENDERBUFFER,s.msaaBuffer),i.renderbufferStorageMultisample(i.RENDERBUFFER,s.multisample,l._glTextures[this.CONTEXT_UID].internalFormat,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,s.msaaBuffer)):(i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+a,n.target,l._glTextures[this.CONTEXT_UID].texture,e),o.push(i.COLOR_ATTACHMENT0+a))}if(o.length>1&&i.drawBuffers(o),t.depthTexture&&this.writeDepthTexture){const s=t.depthTexture;this.renderer.texture.bind(s,0),i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,s._glTextures[this.CONTEXT_UID].texture,e)}if(!t.stencil&&!t.depth||t.depthTexture&&this.writeDepthTexture)s.stencil&&(i.deleteRenderbuffer(s.stencil),s.stencil=null);else{let e,r;s.stencil=s.stencil||i.createRenderbuffer(),1===this.renderer.context.webGLVersion?(e=i.DEPTH_STENCIL_ATTACHMENT,r=i.DEPTH_STENCIL):t.depth&&t.stencil?(e=i.DEPTH_STENCIL_ATTACHMENT,r=i.DEPTH24_STENCIL8):t.depth?(e=i.DEPTH_ATTACHMENT,r=i.DEPTH_COMPONENT24):(e=i.STENCIL_ATTACHMENT,r=i.STENCIL_INDEX8),i.bindRenderbuffer(i.RENDERBUFFER,s.stencil),s.msaaBuffer?i.renderbufferStorageMultisample(i.RENDERBUFFER,s.multisample,r,t.width,t.height):i.renderbufferStorage(i.RENDERBUFFER,r,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,e,i.RENDERBUFFER,s.stencil)}}canMultisampleFramebuffer(t){return 1!==this.renderer.context.webGLVersion&&t.colorTextures.length<=1&&!t.depthTexture}detectSamples(t){const{msaaSamples:e}=this;let i=Ch.NONE;if(t<=1||null===e)return i;for(let s=0;s<e.length;s++)if(e[s]<=t){i=e[s];break}return 1===i&&(i=Ch.NONE),i}blit(t,e,i){const{current:s,renderer:r,gl:n,CONTEXT_UID:o}=this;if(2!==r.context.webGLVersion||!s)return;const a=s.glFramebuffers[o];if(!a)return;if(!t){if(!a.msaaBuffer)return;const e=s.colorTextures[0];if(!e)return;a.blitFramebuffer||(a.blitFramebuffer=new ym(s.width,s.height),a.blitFramebuffer.addColorTexture(0,e)),(t=a.blitFramebuffer).colorTextures[0]!==e&&(t.colorTextures[0]=e,t.dirtyId++,t.dirtyFormat++),(t.width!==s.width||t.height!==s.height)&&(t.width=s.width,t.height=s.height,t.dirtyId++,t.dirtySize++)}e||((e=Rm).width=s.width,e.height=s.height),i||(i=e);const l=e.width===i.width&&e.height===i.height;this.bind(t),n.bindFramebuffer(n.READ_FRAMEBUFFER,a.framebuffer),n.blitFramebuffer(e.left,e.top,e.right,e.bottom,i.left,i.top,i.right,i.bottom,n.COLOR_BUFFER_BIT,l?n.NEAREST:n.LINEAR),n.bindFramebuffer(n.READ_FRAMEBUFFER,t.glFramebuffers[this.CONTEXT_UID].framebuffer)}disposeFramebuffer(t,e){const i=t.glFramebuffers[this.CONTEXT_UID],s=this.gl;if(!i)return;delete t.glFramebuffers[this.CONTEXT_UID];const r=this.managedFramebuffers.indexOf(t);r>=0&&this.managedFramebuffers.splice(r,1),t.disposeRunner.remove(this),e||(s.deleteFramebuffer(i.framebuffer),i.msaaBuffer&&s.deleteRenderbuffer(i.msaaBuffer),i.stencil&&s.deleteRenderbuffer(i.stencil)),i.blitFramebuffer&&this.disposeFramebuffer(i.blitFramebuffer,e)}disposeAll(t){const e=this.managedFramebuffers;this.managedFramebuffers=[];for(let i=0;i<e.length;i++)this.disposeFramebuffer(e[i],t)}forceStencil(){const t=this.current;if(!t)return;const e=t.glFramebuffers[this.CONTEXT_UID];if(!e||e.stencil&&t.stencil)return;t.stencil=!0;const i=t.width,s=t.height,r=this.gl,n=e.stencil=r.createRenderbuffer();let o,a;r.bindRenderbuffer(r.RENDERBUFFER,n),1===this.renderer.context.webGLVersion?(o=r.DEPTH_STENCIL_ATTACHMENT,a=r.DEPTH_STENCIL):t.depth?(o=r.DEPTH_STENCIL_ATTACHMENT,a=r.DEPTH24_STENCIL8):(o=r.STENCIL_ATTACHMENT,a=r.STENCIL_INDEX8),e.msaaBuffer?r.renderbufferStorageMultisample(r.RENDERBUFFER,e.multisample,a,i,s):r.renderbufferStorage(r.RENDERBUFFER,a,i,s),r.framebufferRenderbuffer(r.FRAMEBUFFER,o,r.RENDERBUFFER,n)}reset(){this.current=this.unknownFramebuffer,this.viewport=new vf}destroy(){this.renderer=null}}Bm.extension={type:Up.RendererSystem,name:"framebuffer"},Wp.add(Bm);const km={5126:4,5123:2,5121:1};class Fm{constructor(t){this.renderer=t,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this.canUseUInt32ElementIndex=!1,this.managedGeometries={}}contextChange(){this.disposeAll(!0);const t=this.gl=this.renderer.gl,e=this.renderer.context;if(this.CONTEXT_UID=this.renderer.CONTEXT_UID,2!==e.webGLVersion){let e=this.renderer.context.extensions.vertexArrayObject;Oh.PREFER_ENV===dh.WEBGL_LEGACY&&(e=null),e?(t.createVertexArray=()=>e.createVertexArrayOES(),t.bindVertexArray=t=>e.bindVertexArrayOES(t),t.deleteVertexArray=t=>e.deleteVertexArrayOES(t)):(this.hasVao=!1,t.createVertexArray=()=>null,t.bindVertexArray=()=>null,t.deleteVertexArray=()=>null)}if(2!==e.webGLVersion){const e=t.getExtension("ANGLE_instanced_arrays");e?(t.vertexAttribDivisor=(t,i)=>e.vertexAttribDivisorANGLE(t,i),t.drawElementsInstanced=(t,i,s,r,n)=>e.drawElementsInstancedANGLE(t,i,s,r,n),t.drawArraysInstanced=(t,i,s,r)=>e.drawArraysInstancedANGLE(t,i,s,r)):this.hasInstance=!1}this.canUseUInt32ElementIndex=2===e.webGLVersion||!!e.extensions.uint32ElementIndex}bind(t,e){e=e||this.renderer.shader.shader;const{gl:i}=this;let s=t.glVertexArrayObjects[this.CONTEXT_UID],r=!1;s||(this.managedGeometries[t.id]=t,t.disposeRunner.add(this),t.glVertexArrayObjects[this.CONTEXT_UID]=s={},r=!0);const n=s[e.program.id]||this.initGeometryVao(t,e,r);this._activeGeometry=t,this._activeVao!==n&&(this._activeVao=n,this.hasVao?i.bindVertexArray(n):this.activateVao(t,e.program)),this.updateBuffers()}reset(){this.unbind()}updateBuffers(){const t=this._activeGeometry,e=this.renderer.buffer;for(let i=0;i<t.buffers.length;i++){const s=t.buffers[i];e.update(s)}}checkCompatibility(t,e){const i=t.attributes,s=e.attributeData;for(const r in s)if(!i[r])throw new Error(`shader and geometry incompatible, geometry missing the "${r}" attribute`)}getSignature(t,e){const i=t.attributes,s=e.attributeData,r=["g",t.id];for(const n in i)s[n]&&r.push(n,s[n].location);return r.join("-")}initGeometryVao(t,e,i=!0){const s=this.gl,r=this.CONTEXT_UID,n=this.renderer.buffer,o=e.program;o.glPrograms[r]||this.renderer.shader.generateProgram(e),this.checkCompatibility(t,o);const a=this.getSignature(t,o),l=t.glVertexArrayObjects[this.CONTEXT_UID];let h=l[a];if(h)return l[o.id]=h,h;const u=t.buffers,c=t.attributes,d={},p={};for(const f in u)d[f]=0,p[f]=0;for(const f in c)!c[f].size&&o.attributeData[f]?c[f].size=o.attributeData[f].size:c[f].size||console.warn(`PIXI Geometry attribute '${f}' size cannot be determined (likely the bound shader does not have the attribute)`),d[c[f].buffer]+=c[f].size*km[c[f].type];for(const f in c){const t=c[f],e=t.size;void 0===t.stride&&(d[t.buffer]===e*km[t.type]?t.stride=0:t.stride=d[t.buffer]),void 0===t.start&&(t.start=p[t.buffer],p[t.buffer]+=e*km[t.type])}h=s.createVertexArray(),s.bindVertexArray(h);for(let f=0;f<u.length;f++){const t=u[f];n.bind(t),i&&t._glBuffers[r].refCount++}return this.activateVao(t,o),l[o.id]=h,l[a]=h,s.bindVertexArray(null),n.unbind(Mh.ARRAY_BUFFER),h}disposeGeometry(t,e){if(!this.managedGeometries[t.id])return;delete this.managedGeometries[t.id];const i=t.glVertexArrayObjects[this.CONTEXT_UID],s=this.gl,r=t.buffers,n=this.renderer?.buffer;if(t.disposeRunner.remove(this),i){if(n)for(let t=0;t<r.length;t++){const i=r[t]._glBuffers[this.CONTEXT_UID];i&&(i.refCount--,0===i.refCount&&!e&&n.dispose(r[t],e))}if(!e)for(const t in i)if("g"===t[0]){const e=i[t];this._activeVao===e&&this.unbind(),s.deleteVertexArray(e)}delete t.glVertexArrayObjects[this.CONTEXT_UID]}}disposeAll(t){const e=Object.keys(this.managedGeometries);for(let i=0;i<e.length;i++)this.disposeGeometry(this.managedGeometries[e[i]],t)}activateVao(t,e){const i=this.gl,s=this.CONTEXT_UID,r=this.renderer.buffer,n=t.buffers,o=t.attributes;t.indexBuffer&&r.bind(t.indexBuffer);let a=null;for(const l in o){const t=o[l],h=n[t.buffer],u=h._glBuffers[s];if(e.attributeData[l]){a!==u&&(r.bind(h),a=u);const s=e.attributeData[l].location;if(i.enableVertexAttribArray(s),i.vertexAttribPointer(s,t.size,t.type||i.FLOAT,t.normalized,t.stride,t.start),t.instance){if(!this.hasInstance)throw new Error("geometry error, GPU Instancing is not supported on this device");i.vertexAttribDivisor(s,t.divisor)}}}}draw(t,e,i,s){const{gl:r}=this,n=this._activeGeometry;if(n.indexBuffer){const o=n.indexBuffer.data.BYTES_PER_ELEMENT,a=2===o?r.UNSIGNED_SHORT:r.UNSIGNED_INT;2===o||4===o&&this.canUseUInt32ElementIndex?n.instanced?r.drawElementsInstanced(t,e||n.indexBuffer.data.length,a,(i||0)*o,s||1):r.drawElements(t,e||n.indexBuffer.data.length,a,(i||0)*o):console.warn("unsupported index buffer type: uint32")}else n.instanced?r.drawArraysInstanced(t,i,e||n.getSize(),s||1):r.drawArrays(t,i,e||n.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this.renderer=null}}Fm.extension={type:Up.RendererSystem,name:"geometry"},Wp.add(Fm);const Dm=new Pf;class Um{constructor(t,e){this._texture=t,this.mapCoord=new Pf,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,this.clampMargin=typeof e>"u"?.5:e,this.isSimple=!1}get texture(){return this._texture}set texture(t){this._texture=t,this._textureID=-1}multiplyUvs(t,e){void 0===e&&(e=t);const i=this.mapCoord;for(let s=0;s<t.length;s+=2){const r=t[s],n=t[s+1];e[s]=r*i.a+n*i.c+i.tx,e[s+1]=r*i.b+n*i.d+i.ty}return e}update(t){const e=this._texture;if(!e||!e.valid||!t&&this._textureID===e._updateID)return!1;this._textureID=e._updateID,this._updateID++;const i=e._uvs;this.mapCoord.set(i.x1-i.x0,i.y1-i.y0,i.x3-i.x0,i.y3-i.y0,i.x0,i.y0);const s=e.orig,r=e.trim;r&&(Dm.set(s.width/r.width,0,0,s.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(Dm));const n=e.baseTexture,o=this.uClampFrame,a=this.clampMargin/n.resolution,l=this.clampOffset;return o[0]=(e._frame.x+a+l)/n.width,o[1]=(e._frame.y+a+l)/n.height,o[2]=(e._frame.x+e._frame.width-a+l)/n.width,o[3]=(e._frame.y+e._frame.height-a+l)/n.height,this.uClampOffset[0]=l/n.realWidth,this.uClampOffset[1]=l/n.realHeight,this.isSimple=e._frame.width===n.width&&e._frame.height===n.height&&0===e.rotate,!0}}class Gm extends dm{constructor(t,e,i){let s=null;"string"!=typeof t&&void 0===e&&void 0===i&&(s=t,t=void 0,e=void 0,i=void 0),super(t||"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n",e||"varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n",i),this.maskSprite=s,this.maskMatrix=new Pf}get maskSprite(){return this._maskSprite}set maskSprite(t){this._maskSprite=t,this._maskSprite&&(this._maskSprite.renderable=!1)}apply(t,e,i,s){const r=this._maskSprite,n=r._texture;n.valid&&(n.uvMatrix||(n.uvMatrix=new Um(n,0)),n.uvMatrix.update(),this.uniforms.npmAlpha=n.baseTexture.alphaMode?0:1,this.uniforms.mask=n,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,r).prepend(n.uvMatrix.mapCoord),this.uniforms.alpha=r.worldAlpha,this.uniforms.maskClamp=n.uvMatrix.uClampFrame,t.applyFilter(this,e,i,s))}}class Xm{constructor(t=null){this.type=Sh.NONE,this.autoDetect=!0,this.maskObject=t||null,this.pooled=!1,this.isMaskData=!0,this.resolution=null,this.multisample=dm.defaultMultisample,this.enabled=!0,this.colorMask=15,this._filters=null,this._stencilCounter=0,this._scissorCounter=0,this._scissorRect=null,this._scissorRectLocal=null,this._colorMask=15,this._target=null}get filter(){return this._filters?this._filters[0]:null}set filter(t){t?this._filters?this._filters[0]=t:this._filters=[t]:this._filters=null}reset(){this.pooled&&(this.maskObject=null,this.type=Sh.NONE,this.autoDetect=!0),this._target=null,this._scissorRectLocal=null}copyCountersOrReset(t){t?(this._stencilCounter=t._stencilCounter,this._scissorCounter=t._scissorCounter,this._scissorRect=t._scissorRect):(this._stencilCounter=0,this._scissorCounter=0,this._scissorRect=null)}}class Wm{constructor(t){this.renderer=t,this.enableScissor=!0,this.alphaMaskPool=[],this.maskDataPool=[],this.maskStack=[],this.alphaMaskIndex=0}setMaskStack(t){this.maskStack=t,this.renderer.scissor.setMaskStack(t),this.renderer.stencil.setMaskStack(t)}push(t,e){let i=e;if(!i.isMaskData){const t=this.maskDataPool.pop()||new Xm;t.pooled=!0,t.maskObject=e,i=t}const s=0!==this.maskStack.length?this.maskStack[this.maskStack.length-1]:null;if(i.copyCountersOrReset(s),i._colorMask=s?s._colorMask:15,i.autoDetect&&this.detect(i),i._target=t,i.type!==Sh.SPRITE&&this.maskStack.push(i),i.enabled)switch(i.type){case Sh.SCISSOR:this.renderer.scissor.push(i);break;case Sh.STENCIL:this.renderer.stencil.push(i);break;case Sh.SPRITE:i.copyCountersOrReset(null),this.pushSpriteMask(i);break;case Sh.COLOR:this.pushColorMask(i)}i.type===Sh.SPRITE&&this.maskStack.push(i)}pop(t){const e=this.maskStack.pop();if(e&&e._target===t){if(e.enabled)switch(e.type){case Sh.SCISSOR:this.renderer.scissor.pop(e);break;case Sh.STENCIL:this.renderer.stencil.pop(e.maskObject);break;case Sh.SPRITE:this.popSpriteMask(e);break;case Sh.COLOR:this.popColorMask(e)}if(e.reset(),e.pooled&&this.maskDataPool.push(e),0!==this.maskStack.length){const t=this.maskStack[this.maskStack.length-1];t.type===Sh.SPRITE&&t._filters&&(t._filters[0].maskSprite=t.maskObject)}}}detect(t){const e=t.maskObject;e?e.isSprite?t.type=Sh.SPRITE:this.enableScissor&&this.renderer.scissor.testScissor(t)?t.type=Sh.SCISSOR:t.type=Sh.STENCIL:t.type=Sh.COLOR}pushSpriteMask(t){const{maskObject:e}=t,i=t._target;let s=t._filters;s||(s=this.alphaMaskPool[this.alphaMaskIndex],s||(s=this.alphaMaskPool[this.alphaMaskIndex]=[new Gm])),s[0].resolution=t.resolution,s[0].multisample=t.multisample,s[0].maskSprite=e;const r=i.filterArea;i.filterArea=e.getBounds(!0),this.renderer.filter.push(i,s),i.filterArea=r,t._filters||this.alphaMaskIndex++}popSpriteMask(t){this.renderer.filter.pop(),t._filters?t._filters[0].maskSprite=null:(this.alphaMaskIndex--,this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite=null)}pushColorMask(t){const e=t._colorMask,i=t._colorMask=e&t.colorMask;i!==e&&this.renderer.gl.colorMask(!!(1&i),!!(2&i),!!(4&i),!!(8&i))}popColorMask(t){const e=t._colorMask,i=this.maskStack.length>0?this.maskStack[this.maskStack.length-1]._colorMask:15;i!==e&&this.renderer.gl.colorMask(!!(1&i),!!(2&i),!!(4&i),!!(8&i))}destroy(){this.renderer=null}}Wm.extension={type:Up.RendererSystem,name:"mask"},Wp.add(Wm);class Ym{constructor(t){this.renderer=t,this.maskStack=[],this.glConst=0}getStackLength(){return this.maskStack.length}setMaskStack(t){const{gl:e}=this.renderer,i=this.getStackLength();this.maskStack=t;const s=this.getStackLength();s!==i&&(0===s?e.disable(this.glConst):(e.enable(this.glConst),this._useCurrent()))}_useCurrent(){}destroy(){this.renderer=null,this.maskStack=null}}const Hm=new Pf,$m=[],jm=class t extends Ym{constructor(t){super(t),this.glConst=Oh.ADAPTER.getWebGLRenderingContext().SCISSOR_TEST}getStackLength(){const t=this.maskStack[this.maskStack.length-1];return t?t._scissorCounter:0}calcScissorRect(t){if(t._scissorRectLocal)return;const e=t._scissorRect,{maskObject:i}=t,{renderer:s}=this,r=s.renderTexture,n=i.getBounds(!0,$m.pop()??new vf);this.roundFrameToPixels(n,r.current?r.current.resolution:s.resolution,r.sourceFrame,r.destinationFrame,s.projection.transform),e&&n.fit(e),t._scissorRectLocal=n}static isMatrixRotated(t){if(!t)return!1;const{a:e,b:i,c:s,d:r}=t;return(Math.abs(i)>1e-4||Math.abs(s)>1e-4)&&(Math.abs(e)>1e-4||Math.abs(r)>1e-4)}testScissor(e){const{maskObject:i}=e;if(!i.isFastRect||!i.isFastRect()||t.isMatrixRotated(i.worldTransform)||t.isMatrixRotated(this.renderer.projection.transform))return!1;this.calcScissorRect(e);const s=e._scissorRectLocal;return s.width>0&&s.height>0}roundFrameToPixels(e,i,s,r,n){t.isMatrixRotated(n)||((n=n?Hm.copyFrom(n):Hm.identity()).translate(-s.x,-s.y).scale(r.width/s.width,r.height/s.height).translate(r.x,r.y),this.renderer.filter.transformAABB(n,e),e.fit(r),e.x=Math.round(e.x*i),e.y=Math.round(e.y*i),e.width=Math.round(e.width*i),e.height=Math.round(e.height*i))}push(t){t._scissorRectLocal||this.calcScissorRect(t);const{gl:e}=this.renderer;t._scissorRect||e.enable(e.SCISSOR_TEST),t._scissorCounter++,t._scissorRect=t._scissorRectLocal,this._useCurrent()}pop(t){const{gl:e}=this.renderer;t&&$m.push(t._scissorRectLocal),this.getStackLength()>0?this._useCurrent():e.disable(e.SCISSOR_TEST)}_useCurrent(){const t=this.maskStack[this.maskStack.length-1]._scissorRect;let e;e=this.renderer.renderTexture.current?t.y:this.renderer.height-t.height-t.y,this.renderer.gl.scissor(t.x,e,t.width,t.height)}};jm.extension={type:Up.RendererSystem,name:"scissor"};let zm=jm;Wp.add(zm);class Vm extends Ym{constructor(t){super(t),this.glConst=Oh.ADAPTER.getWebGLRenderingContext().STENCIL_TEST}getStackLength(){const t=this.maskStack[this.maskStack.length-1];return t?t._stencilCounter:0}push(t){const e=t.maskObject,{gl:i}=this.renderer,s=t._stencilCounter;0===s&&(this.renderer.framebuffer.forceStencil(),i.clearStencil(0),i.clear(i.STENCIL_BUFFER_BIT),i.enable(i.STENCIL_TEST)),t._stencilCounter++;const r=t._colorMask;0!==r&&(t._colorMask=0,i.colorMask(!1,!1,!1,!1)),i.stencilFunc(i.EQUAL,s,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.INCR),e.renderable=!0,e.render(this.renderer),this.renderer.batch.flush(),e.renderable=!1,0!==r&&(t._colorMask=r,i.colorMask(!!(1&r),!!(2&r),!!(4&r),!!(8&r))),this._useCurrent()}pop(t){const e=this.renderer.gl;if(0===this.getStackLength())e.disable(e.STENCIL_TEST);else{const i=0!==this.maskStack.length?this.maskStack[this.maskStack.length-1]:null,s=i?i._colorMask:15;0!==s&&(i._colorMask=0,e.colorMask(!1,!1,!1,!1)),e.stencilOp(e.KEEP,e.KEEP,e.DECR),t.renderable=!0,t.render(this.renderer),this.renderer.batch.flush(),t.renderable=!1,0!==s&&(i._colorMask=s,e.colorMask(!!(1&s),!!(2&s),!!(4&s),!!(8&s))),this._useCurrent()}}_useCurrent(){const t=this.renderer.gl;t.stencilFunc(t.EQUAL,this.getStackLength(),4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP)}}Vm.extension={type:Up.RendererSystem,name:"stencil"},Wp.add(Vm);class qm{constructor(t){this.renderer=t,this.plugins={},Object.defineProperties(this.plugins,{extract:{enumerable:!1,get:()=>(Md("7.0.0","renderer.plugins.extract has moved to renderer.extract"),t.extract)},prepare:{enumerable:!1,get:()=>(Md("7.0.0","renderer.plugins.prepare has moved to renderer.prepare"),t.prepare)},interaction:{enumerable:!1,get:()=>(Md("7.0.0","renderer.plugins.interaction has been deprecated, use renderer.events"),t.events)}})}init(){const t=this.rendererPlugins;for(const e in t)this.plugins[e]=new t[e](this.renderer)}destroy(){for(const t in this.plugins)this.plugins[t].destroy(),this.plugins[t]=null}}qm.extension={type:[Up.RendererSystem,Up.CanvasRendererSystem],name:"_plugin"},Wp.add(qm);class Jm{constructor(t){this.renderer=t,this.destinationFrame=null,this.sourceFrame=null,this.defaultFrame=null,this.projectionMatrix=new Pf,this.transform=null}update(t,e,i,s){this.destinationFrame=t||this.destinationFrame||this.defaultFrame,this.sourceFrame=e||this.sourceFrame||t,this.calculateProjection(this.destinationFrame,this.sourceFrame,i,s),this.transform&&this.projectionMatrix.append(this.transform);const r=this.renderer;r.globalUniforms.uniforms.projectionMatrix=this.projectionMatrix,r.globalUniforms.update(),r.shader.shader&&r.shader.syncUniformGroup(r.shader.shader.uniforms.globals)}calculateProjection(t,e,i,s){const r=this.projectionMatrix,n=s?-1:1;r.identity(),r.a=1/e.width*2,r.d=n*(1/e.height*2),r.tx=-1-e.x*r.a,r.ty=-n-e.y*r.d}setTransform(t){}destroy(){this.renderer=null}}Jm.extension={type:Up.RendererSystem,name:"projection"},Wp.add(Jm);const Km=new Rf,Zm=new vf;class Qm{constructor(t){this.renderer=t,this._tempMatrix=new Pf}generateTexture(t,e){const{region:i,...s}=e||{},r=i?.copyTo(Zm)||t.getLocalBounds(Zm,!0),n=s.resolution||this.renderer.resolution;r.width=Math.max(r.width,1/n),r.height=Math.max(r.height,1/n),s.width=r.width,s.height=r.height,s.resolution=n,s.multisample??(s.multisample=this.renderer.multisample);const o=Tm.create(s);this._tempMatrix.tx=-r.x,this._tempMatrix.ty=-r.y;const a=t.transform;return t.transform=Km,this.renderer.render(t,{renderTexture:o,transform:this._tempMatrix,skipUpdateTransform:!!t.parent,blit:!0}),t.transform=a,o}destroy(){}}Qm.extension={type:[Up.RendererSystem,Up.CanvasRendererSystem],name:"textureGenerator"},Wp.add(Qm);const tg=new vf,eg=new vf;class ig{constructor(t){this.renderer=t,this.defaultMaskStack=[],this.current=null,this.sourceFrame=new vf,this.destinationFrame=new vf,this.viewportFrame=new vf}contextChange(){const t=this.renderer?.gl.getContextAttributes();this._rendererPremultipliedAlpha=!!(t&&t.alpha&&t.premultipliedAlpha)}bind(t=null,e,i){const s=this.renderer;let r,n,o;this.current=t,t?(r=t.baseTexture,o=r.resolution,e||(tg.width=t.frame.width,tg.height=t.frame.height,e=tg),i||(eg.x=t.frame.x,eg.y=t.frame.y,eg.width=e.width,eg.height=e.height,i=eg),n=r.framebuffer):(o=s.resolution,e||(tg.width=s._view.screen.width,tg.height=s._view.screen.height,e=tg),i||((i=tg).width=e.width,i.height=e.height));const a=this.viewportFrame;a.x=i.x*o,a.y=i.y*o,a.width=i.width*o,a.height=i.height*o,t||(a.y=s.view.height-(a.y+a.height)),a.ceil(),this.renderer.framebuffer.bind(n,a),this.renderer.projection.update(i,e,o,!n),t?this.renderer.mask.setMaskStack(r.maskStack):this.renderer.mask.setMaskStack(this.defaultMaskStack),this.sourceFrame.copyFrom(e),this.destinationFrame.copyFrom(i)}clear(t,e){const i=this.current?this.current.baseTexture.clear:this.renderer.background.backgroundColor,s=pp.shared.setValue(t||i);(this.current&&this.current.baseTexture.alphaMode>0||!this.current&&this._rendererPremultipliedAlpha)&&s.premultiply(s.alpha);const r=this.destinationFrame,n=this.current?this.current.baseTexture:this.renderer._view.screen,o=r.width!==n.width||r.height!==n.height;if(o){let{x:t,y:e,width:i,height:s}=this.viewportFrame;t=Math.round(t),e=Math.round(e),i=Math.round(i),s=Math.round(s),this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST),this.renderer.gl.scissor(t,e,i,s)}this.renderer.framebuffer.clear(s.red,s.green,s.blue,s.alpha,e),o&&this.renderer.scissor.pop()}resize(){this.bind(null)}reset(){this.bind(null)}destroy(){this.renderer=null}}ig.extension={type:Up.RendererSystem,name:"renderTexture"},Wp.add(ig);class sg{constructor(t,e){this.program=t,this.uniformData=e,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBufferBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBufferBindings=null,this.program=null}}function rg(t,e){const i=Bf(t,t.VERTEX_SHADER,e.vertexSrc),s=Bf(t,t.FRAGMENT_SHADER,e.fragmentSrc),r=t.createProgram();t.attachShader(r,i),t.attachShader(r,s);const n=e.extra?.transformFeedbackVaryings;if(n&&("function"!=typeof t.transformFeedbackVaryings?console.warn("TransformFeedback is not supported but TransformFeedbackVaryings are given."):t.transformFeedbackVaryings(r,n.names,"separate"===n.bufferMode?t.SEPARATE_ATTRIBS:t.INTERLEAVED_ATTRIBS)),t.linkProgram(r),t.getProgramParameter(r,t.LINK_STATUS)||function(t,e,i,s){t.getProgramParameter(e,t.LINK_STATUS)||(t.getShaderParameter(i,t.COMPILE_STATUS)||$f(t,i),t.getShaderParameter(s,t.COMPILE_STATUS)||$f(t,s),console.error("PixiJS Error: Could not initialize shader."),""!==t.getProgramInfoLog(e)&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",t.getProgramInfoLog(e)))}(t,r,i,s),e.attributeData=function(t,e){const i={},s=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<s;r++){const s=e.getActiveAttrib(t,r);if(s.name.startsWith("gl_"))continue;const n=Jf(e,s.type),o={type:n,name:s.name,size:zf(n),location:e.getAttribLocation(t,s.name)};i[s.name]=o}return i}(r,t),e.uniformData=function(t,e){const i={},s=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<s;r++){const s=e.getActiveUniform(t,r),n=s.name.replace(/\[.*?\]$/,""),o=!!s.name.match(/\[.*?\]$/),a=Jf(e,s.type);i[n]={name:n,index:r,type:a,size:s.size,isArray:o,value:Ff(a,s.size)}}return i}(r,t),!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertexSrc)){const i=Object.keys(e.attributeData);i.sort((t,e)=>t>e?1:-1);for(let s=0;s<i.length;s++)e.attributeData[i[s]].location=s,t.bindAttribLocation(r,s,i[s]);t.linkProgram(r)}t.deleteShader(i),t.deleteShader(s);const o={};for(const a in e.uniformData){const i=e.uniformData[a];o[a]={location:t.getUniformLocation(r,a),value:Ff(i.type,i.size)}}return new sg(r,o)}function ng(t,e,i,s,r){i.buffer.update(r)}const og={float:"\n data[offset] = v;\n ",vec2:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n ",vec3:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n ",vec4:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n data[offset+3] = v[3];\n ",mat2:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n\n data[offset+4] = v[2];\n data[offset+5] = v[3];\n ",mat3:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n data[offset + 4] = v[3];\n data[offset + 5] = v[4];\n data[offset + 6] = v[5];\n\n data[offset + 8] = v[6];\n data[offset + 9] = v[7];\n data[offset + 10] = v[8];\n ",mat4:"\n for(var i = 0; i < 16; i++)\n {\n data[offset + i] = v[i];\n }\n "},ag={float:4,vec2:8,vec3:12,vec4:16,int:4,ivec2:8,ivec3:12,ivec4:16,uint:4,uvec2:8,uvec3:12,uvec4:16,bool:4,bvec2:8,bvec3:12,bvec4:16,mat2:32,mat3:48,mat4:64};function lg(t,e){if(!t.autoManage)return{size:0,syncFunc:ng};const i=function(t,e){const i=[];for(const s in t)e[s]&&i.push(e[s]);return i.sort((t,e)=>t.index-e.index),i}(t.uniforms,e),{uboElements:s,size:r}=function(t){const e=t.map(t=>({data:t,offset:0,dataLen:0,dirty:0}));let i=0,s=0,r=0;for(let n=0;n<e.length;n++){const t=e[n];if(i=ag[t.data.type],t.data.size>1&&(i=Math.max(i,16)*t.data.size),t.dataLen=i,s%i!==0&&s<16){const t=s%i%16;s+=t,r+=t}s+i>16?(r=16*Math.ceil(r/16),t.offset=r,r+=i,s=i):(t.offset=r,s+=i,r+=i)}return r=16*Math.ceil(r/16),{uboElements:e,size:r}}(i),n=["\n var v = null;\n var v2 = null;\n var cv = null;\n var t = 0;\n var gl = renderer.gl\n var index = 0;\n var data = buffer.data;\n "];for(let o=0;o<s.length;o++){const e=s[o],i=t.uniforms[e.data.name],r=e.data.name;let a=!1;for(let t=0;t<Df.length;t++){const s=Df[t];if(s.codeUbo&&s.test(e.data,i)){n.push(`offset = ${e.offset/4};`,Df[t].codeUbo(e.data.name,i)),a=!0;break}}if(!a)if(e.data.size>1){const t=zf(e.data.type),i=Math.max(ag[e.data.type]/16,1),s=t/i,o=(4-s%4)%4;n.push(`\n cv = ud.${r}.value;\n v = uv.${r};\n offset = ${e.offset/4};\n\n t = 0;\n\n for(var i=0; i < ${e.data.size*i}; i++)\n {\n for(var j = 0; j < ${s}; j++)\n {\n data[offset++] = v[t++];\n }\n offset += ${o};\n }\n\n `)}else{const t=og[e.data.type];n.push(`\n cv = ud.${r}.value;\n v = uv.${r};\n offset = ${e.offset/4};\n ${t};\n `)}}return n.push("\n renderer.buffer.update(buffer);\n "),{size:r,syncFunc:new Function("ud","uv","renderer","syncData","buffer",n.join("\n"))}}let hg=0;const ug={textureCount:0,uboCount:0};class cg{constructor(t){this.destroyed=!1,this.renderer=t,this.systemCheck(),this.gl=null,this.shader=null,this.program=null,this.cache={},this._uboCache={},this.id=hg++}systemCheck(){if(!function(){if("boolean"==typeof Zf)return Zf;try{Zf=!0===new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")}catch{Zf=!1}return Zf}())throw new Error("Current environment does not allow unsafe-eval, please use @pixi/unsafe-eval module to enable support.")}contextChange(t){this.gl=t,this.reset()}bind(t,e){t.disposeRunner.add(this),t.uniforms.globals=this.renderer.globalUniforms;const i=t.program,s=i.glPrograms[this.renderer.CONTEXT_UID]||this.generateProgram(t);return this.shader=t,this.program!==i&&(this.program=i,this.gl.useProgram(s.program)),e||(ug.textureCount=0,ug.uboCount=0,this.syncUniformGroup(t.uniformGroup,ug)),s}setUniforms(t){const e=this.shader.program,i=e.glPrograms[this.renderer.CONTEXT_UID];e.syncUniforms(i.uniformData,t,this.renderer)}syncUniformGroup(t,e){const i=this.getGlProgram();(!t.static||t.dirtyId!==i.uniformDirtyGroups[t.id])&&(i.uniformDirtyGroups[t.id]=t.dirtyId,this.syncUniforms(t,i,e))}syncUniforms(t,e,i){(t.syncUniforms[this.shader.program.id]||this.createSyncGroups(t))(e.uniformData,t.uniforms,this.renderer,i)}createSyncGroups(t){const e=this.getSignature(t,this.shader.program.uniformData,"u");return this.cache[e]||(this.cache[e]=function(t,e){const i=["\n var v = null;\n var cv = null;\n var cu = null;\n var t = 0;\n var gl = renderer.gl;\n "];for(const s in t.uniforms){const r=e[s];if(!r){!0===t.uniforms[s]?.group&&(t.uniforms[s].ubo?i.push(`\n renderer.shader.syncUniformBufferGroup(uv.${s}, '${s}');\n `):i.push(`\n renderer.shader.syncUniformGroup(uv.${s}, syncData);\n `));continue}const n=t.uniforms[s];let o=!1;for(let t=0;t<Df.length;t++)if(Df[t].test(r,n)){i.push(Df[t].code(s,n)),o=!0;break}if(!o){const t=(1!==r.size||r.isArray?Gf:Uf)[r.type].replace("location",`ud["${s}"].location`);i.push(`\n cu = ud["${s}"];\n cv = cu.value;\n v = uv["${s}"];\n ${t};`)}}return new Function("ud","uv","renderer","syncData",i.join("\n"))}(t,this.shader.program.uniformData)),t.syncUniforms[this.shader.program.id]=this.cache[e],t.syncUniforms[this.shader.program.id]}syncUniformBufferGroup(t,e){const i=this.getGlProgram();if(!t.static||0!==t.dirtyId||!i.uniformGroups[t.id]){t.dirtyId=0;const s=i.uniformGroups[t.id]||this.createSyncBufferGroup(t,i,e);t.buffer.update(),s(i.uniformData,t.uniforms,this.renderer,ug,t.buffer)}this.renderer.buffer.bindBufferBase(t.buffer,i.uniformBufferBindings[e])}createSyncBufferGroup(t,e,i){const{gl:s}=this.renderer;this.renderer.buffer.bind(t.buffer);const r=this.gl.getUniformBlockIndex(e.program,i);e.uniformBufferBindings[i]=this.shader.uniformBindCount,s.uniformBlockBinding(e.program,r,this.shader.uniformBindCount),this.shader.uniformBindCount++;const n=this.getSignature(t,this.shader.program.uniformData,"ubo");let o=this._uboCache[n];if(o||(o=this._uboCache[n]=lg(t,this.shader.program.uniformData)),t.autoManage){const e=new Float32Array(o.size/4);t.buffer.update(e)}return e.uniformGroups[t.id]=o.syncFunc,e.uniformGroups[t.id]}getSignature(t,e,i){const s=t.uniforms,r=[`${i}-`];for(const n in s)r.push(n),e[n]&&r.push(e[n].type);return r.join("-")}getGlProgram(){return this.shader?this.shader.program.glPrograms[this.renderer.CONTEXT_UID]:null}generateProgram(t){const e=this.gl,i=t.program,s=rg(e,i);return i.glPrograms[this.renderer.CONTEXT_UID]=s,s}reset(){this.program=null,this.shader=null}disposeShader(t){this.shader===t&&(this.shader=null)}destroy(){this.renderer=null,this.destroyed=!0}}cg.extension={type:Up.RendererSystem,name:"shader"},Wp.add(cg);class dg{constructor(t){this.renderer=t}run(t){const{renderer:e}=this;e.runners.init.emit(e.options),t.hello&&console.log(`PixiJS 7.4.2 - ${e.rendererLogId} - https://pixijs.com`),e.resize(e.screen.width,e.screen.height)}destroy(){}}dg.defaultOptions={hello:!1},dg.extension={type:[Up.RendererSystem,Up.CanvasRendererSystem],name:"startup"},Wp.add(dg);const pg=class t{constructor(){this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode=mh.NONE,this._blendEq=!1,this.map=[],this.map[0]=this.setBlend,this.map[1]=this.setOffset,this.map[2]=this.setCullFace,this.map[3]=this.setDepthTest,this.map[4]=this.setFrontFace,this.map[5]=this.setDepthMask,this.checks=[],this.defaultState=new jp,this.defaultState.blend=!0}contextChange(t){this.gl=t,this.blendModes=function(t,e=[]){return e[mh.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.ADD]=[t.ONE,t.ONE],e[mh.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.NONE]=[0,0],e[mh.NORMAL_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.ADD_NPM]=[t.SRC_ALPHA,t.ONE,t.ONE,t.ONE],e[mh.SCREEN_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[mh.SRC_IN]=[t.DST_ALPHA,t.ZERO],e[mh.SRC_OUT]=[t.ONE_MINUS_DST_ALPHA,t.ZERO],e[mh.SRC_ATOP]=[t.DST_ALPHA,t.ONE_MINUS_SRC_ALPHA],e[mh.DST_OVER]=[t.ONE_MINUS_DST_ALPHA,t.ONE],e[mh.DST_IN]=[t.ZERO,t.SRC_ALPHA],e[mh.DST_OUT]=[t.ZERO,t.ONE_MINUS_SRC_ALPHA],e[mh.DST_ATOP]=[t.ONE_MINUS_DST_ALPHA,t.SRC_ALPHA],e[mh.XOR]=[t.ONE_MINUS_DST_ALPHA,t.ONE_MINUS_SRC_ALPHA],e[mh.SUBTRACT]=[t.ONE,t.ONE,t.ONE,t.ONE,t.FUNC_REVERSE_SUBTRACT,t.FUNC_ADD],e}(t),this.set(this.defaultState),this.reset()}set(t){if(t=t||this.defaultState,this.stateId!==t.data){let e=this.stateId^t.data,i=0;for(;e;)1&e&&this.map[i].call(this,!!(t.data&1<<i)),e>>=1,i++;this.stateId=t.data}for(let e=0;e<this.checks.length;e++)this.checks[e](this,t)}forceState(t){t=t||this.defaultState;for(let e=0;e<this.map.length;e++)this.map[e].call(this,!!(t.data&1<<e));for(let e=0;e<this.checks.length;e++)this.checks[e](this,t);this.stateId=t.data}setBlend(e){this.updateCheck(t.checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this.updateCheck(t.checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(t){this.gl[t?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(t){this.gl.depthMask(t)}setCullFace(t){this.gl[t?"enable":"disable"](this.gl.CULL_FACE)}setFrontFace(t){this.gl.frontFace(this.gl[t?"CW":"CCW"])}setBlendMode(t){if(t===this.blendMode)return;this.blendMode=t;const e=this.blendModes[t],i=this.gl;2===e.length?i.blendFunc(e[0],e[1]):i.blendFuncSeparate(e[0],e[1],e[2],e[3]),6===e.length?(this._blendEq=!0,i.blendEquationSeparate(e[4],e[5])):this._blendEq&&(this._blendEq=!1,i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD))}setPolygonOffset(t,e){this.gl.polygonOffset(t,e)}reset(){this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode=-1,this.setBlendMode(0)}updateCheck(t,e){const i=this.checks.indexOf(t);e&&-1===i?this.checks.push(t):!e&&-1!==i&&this.checks.splice(i,1)}static checkBlendMode(t,e){t.setBlendMode(e.blendMode)}static checkPolygonOffset(t,e){t.setPolygonOffset(1,e.polygonOffset)}destroy(){this.gl=null}};pg.extension={type:Up.RendererSystem,name:"state"};let fg=pg;Wp.add(fg);class mg extends Qh{constructor(){super(...arguments),this.runners={},this._systemsHash={}}setup(t){this.addRunners(...t.runners);const e=(t.priority??[]).filter(e=>t.systems[e]),i=[...e,...Object.keys(t.systems).filter(t=>!e.includes(t))];for(const s of i)this.addSystem(t.systems[s],s)}addRunners(...t){t.forEach(t=>{this.runners[t]=new qp(t)})}addSystem(t,e){const i=new t(this);if(this[e])throw new Error(`Whoops! The name "${e}" is already in use`);this[e]=i,this._systemsHash[e]=i;for(const s in this.runners)this.runners[s].add(i);return this}emitWithCustomOptions(t,e){const i=Object.keys(this._systemsHash);t.items.forEach(s=>{const r=i.find(t=>this._systemsHash[t]===s);s[t.name](e[r])})}destroy(){Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash={}}}const gg=class t{constructor(e){this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=t.defaultMaxIdle,this.checkCountMax=t.defaultCheckCountMax,this.mode=t.defaultMode}postrender(){this.renderer.objectRenderer.renderingToScreen&&(this.count++,this.mode!==Ah.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())))}run(){const t=this.renderer.texture,e=t.managedTextures;let i=!1;for(let s=0;s<e.length;s++){const r=e[s];r.resource&&this.count-r.touched>this.maxIdle&&(t.destroyTexture(r,!0),e[s]=null,i=!0)}if(i){let t=0;for(let i=0;i<e.length;i++)null!==e[i]&&(e[t++]=e[i]);e.length=t}}unload(t){const e=this.renderer.texture,i=t._texture;i&&!i.framebuffer&&e.destroyTexture(i);for(let s=t.children.length-1;s>=0;s--)this.unload(t.children[s])}destroy(){this.renderer=null}};gg.defaultMode=Ah.AUTO,gg.defaultMaxIdle=3600,gg.defaultCheckCountMax=600,gg.extension={type:Up.RendererSystem,name:"textureGC"};let yg=gg;Wp.add(yg);class vg{constructor(t){this.texture=t,this.width=-1,this.height=-1,this.dirtyId=-1,this.dirtyStyleId=-1,this.mipmap=!1,this.wrapMode=33071,this.type=xh.UNSIGNED_BYTE,this.internalFormat=yh.RGBA,this.samplerType=0}}class xg{constructor(t){this.renderer=t,this.boundTextures=[],this.currentLocation=-1,this.managedTextures=[],this._unknownBoundTextures=!1,this.unknownTexture=new tf,this.hasIntegerTextures=!1}contextChange(){const t=this.gl=this.renderer.gl;this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.webGLVersion=this.renderer.context.webGLVersion,this.internalFormats=function(t){let e;return e="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext?{[xh.UNSIGNED_BYTE]:{[yh.RGBA]:t.RGBA8,[yh.RGB]:t.RGB8,[yh.RG]:t.RG8,[yh.RED]:t.R8,[yh.RGBA_INTEGER]:t.RGBA8UI,[yh.RGB_INTEGER]:t.RGB8UI,[yh.RG_INTEGER]:t.RG8UI,[yh.RED_INTEGER]:t.R8UI,[yh.ALPHA]:t.ALPHA,[yh.LUMINANCE]:t.LUMINANCE,[yh.LUMINANCE_ALPHA]:t.LUMINANCE_ALPHA},[xh.BYTE]:{[yh.RGBA]:t.RGBA8_SNORM,[yh.RGB]:t.RGB8_SNORM,[yh.RG]:t.RG8_SNORM,[yh.RED]:t.R8_SNORM,[yh.RGBA_INTEGER]:t.RGBA8I,[yh.RGB_INTEGER]:t.RGB8I,[yh.RG_INTEGER]:t.RG8I,[yh.RED_INTEGER]:t.R8I},[xh.UNSIGNED_SHORT]:{[yh.RGBA_INTEGER]:t.RGBA16UI,[yh.RGB_INTEGER]:t.RGB16UI,[yh.RG_INTEGER]:t.RG16UI,[yh.RED_INTEGER]:t.R16UI,[yh.DEPTH_COMPONENT]:t.DEPTH_COMPONENT16},[xh.SHORT]:{[yh.RGBA_INTEGER]:t.RGBA16I,[yh.RGB_INTEGER]:t.RGB16I,[yh.RG_INTEGER]:t.RG16I,[yh.RED_INTEGER]:t.R16I},[xh.UNSIGNED_INT]:{[yh.RGBA_INTEGER]:t.RGBA32UI,[yh.RGB_INTEGER]:t.RGB32UI,[yh.RG_INTEGER]:t.RG32UI,[yh.RED_INTEGER]:t.R32UI,[yh.DEPTH_COMPONENT]:t.DEPTH_COMPONENT24},[xh.INT]:{[yh.RGBA_INTEGER]:t.RGBA32I,[yh.RGB_INTEGER]:t.RGB32I,[yh.RG_INTEGER]:t.RG32I,[yh.RED_INTEGER]:t.R32I},[xh.FLOAT]:{[yh.RGBA]:t.RGBA32F,[yh.RGB]:t.RGB32F,[yh.RG]:t.RG32F,[yh.RED]:t.R32F,[yh.DEPTH_COMPONENT]:t.DEPTH_COMPONENT32F},[xh.HALF_FLOAT]:{[yh.RGBA]:t.RGBA16F,[yh.RGB]:t.RGB16F,[yh.RG]:t.RG16F,[yh.RED]:t.R16F},[xh.UNSIGNED_SHORT_5_6_5]:{[yh.RGB]:t.RGB565},[xh.UNSIGNED_SHORT_4_4_4_4]:{[yh.RGBA]:t.RGBA4},[xh.UNSIGNED_SHORT_5_5_5_1]:{[yh.RGBA]:t.RGB5_A1},[xh.UNSIGNED_INT_2_10_10_10_REV]:{[yh.RGBA]:t.RGB10_A2,[yh.RGBA_INTEGER]:t.RGB10_A2UI},[xh.UNSIGNED_INT_10F_11F_11F_REV]:{[yh.RGB]:t.R11F_G11F_B10F},[xh.UNSIGNED_INT_5_9_9_9_REV]:{[yh.RGB]:t.RGB9_E5},[xh.UNSIGNED_INT_24_8]:{[yh.DEPTH_STENCIL]:t.DEPTH24_STENCIL8},[xh.FLOAT_32_UNSIGNED_INT_24_8_REV]:{[yh.DEPTH_STENCIL]:t.DEPTH32F_STENCIL8}}:{[xh.UNSIGNED_BYTE]:{[yh.RGBA]:t.RGBA,[yh.RGB]:t.RGB,[yh.ALPHA]:t.ALPHA,[yh.LUMINANCE]:t.LUMINANCE,[yh.LUMINANCE_ALPHA]:t.LUMINANCE_ALPHA},[xh.UNSIGNED_SHORT_5_6_5]:{[yh.RGB]:t.RGB},[xh.UNSIGNED_SHORT_4_4_4_4]:{[yh.RGBA]:t.RGBA},[xh.UNSIGNED_SHORT_5_5_5_1]:{[yh.RGBA]:t.RGBA}},e}(t),this.samplerTypes=function(t){let e;return e="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext?{[t.RGB]:bh.FLOAT,[t.RGBA]:bh.FLOAT,[t.ALPHA]:bh.FLOAT,[t.LUMINANCE]:bh.FLOAT,[t.LUMINANCE_ALPHA]:bh.FLOAT,[t.R8]:bh.FLOAT,[t.R8_SNORM]:bh.FLOAT,[t.RG8]:bh.FLOAT,[t.RG8_SNORM]:bh.FLOAT,[t.RGB8]:bh.FLOAT,[t.RGB8_SNORM]:bh.FLOAT,[t.RGB565]:bh.FLOAT,[t.RGBA4]:bh.FLOAT,[t.RGB5_A1]:bh.FLOAT,[t.RGBA8]:bh.FLOAT,[t.RGBA8_SNORM]:bh.FLOAT,[t.RGB10_A2]:bh.FLOAT,[t.RGB10_A2UI]:bh.FLOAT,[t.SRGB8]:bh.FLOAT,[t.SRGB8_ALPHA8]:bh.FLOAT,[t.R16F]:bh.FLOAT,[t.RG16F]:bh.FLOAT,[t.RGB16F]:bh.FLOAT,[t.RGBA16F]:bh.FLOAT,[t.R32F]:bh.FLOAT,[t.RG32F]:bh.FLOAT,[t.RGB32F]:bh.FLOAT,[t.RGBA32F]:bh.FLOAT,[t.R11F_G11F_B10F]:bh.FLOAT,[t.RGB9_E5]:bh.FLOAT,[t.R8I]:bh.INT,[t.R8UI]:bh.UINT,[t.R16I]:bh.INT,[t.R16UI]:bh.UINT,[t.R32I]:bh.INT,[t.R32UI]:bh.UINT,[t.RG8I]:bh.INT,[t.RG8UI]:bh.UINT,[t.RG16I]:bh.INT,[t.RG16UI]:bh.UINT,[t.RG32I]:bh.INT,[t.RG32UI]:bh.UINT,[t.RGB8I]:bh.INT,[t.RGB8UI]:bh.UINT,[t.RGB16I]:bh.INT,[t.RGB16UI]:bh.UINT,[t.RGB32I]:bh.INT,[t.RGB32UI]:bh.UINT,[t.RGBA8I]:bh.INT,[t.RGBA8UI]:bh.UINT,[t.RGBA16I]:bh.INT,[t.RGBA16UI]:bh.UINT,[t.RGBA32I]:bh.INT,[t.RGBA32UI]:bh.UINT,[t.DEPTH_COMPONENT16]:bh.FLOAT,[t.DEPTH_COMPONENT24]:bh.FLOAT,[t.DEPTH_COMPONENT32F]:bh.FLOAT,[t.DEPTH_STENCIL]:bh.FLOAT,[t.DEPTH24_STENCIL8]:bh.FLOAT,[t.DEPTH32F_STENCIL8]:bh.FLOAT}:{[t.RGB]:bh.FLOAT,[t.RGBA]:bh.FLOAT,[t.ALPHA]:bh.FLOAT,[t.LUMINANCE]:bh.FLOAT,[t.LUMINANCE_ALPHA]:bh.FLOAT,[t.DEPTH_STENCIL]:bh.FLOAT},e}(t);const e=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);this.boundTextures.length=e;for(let s=0;s<e;s++)this.boundTextures[s]=null;this.emptyTextures={};const i=new vg(t.createTexture());t.bindTexture(t.TEXTURE_2D,i.texture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array(4)),this.emptyTextures[t.TEXTURE_2D]=i,this.emptyTextures[t.TEXTURE_CUBE_MAP]=new vg(t.createTexture()),t.bindTexture(t.TEXTURE_CUBE_MAP,this.emptyTextures[t.TEXTURE_CUBE_MAP].texture);for(let s=0;s<6;s++)t.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,null);t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MIN_FILTER,t.LINEAR);for(let s=0;s<this.boundTextures.length;s++)this.bind(null,s)}bind(t,e=0){const{gl:i}=this;if(t=t?.castToBaseTexture(),t?.valid&&!t.parentTextureArray){t.touched=this.renderer.textureGC.count;const s=t._glTextures[this.CONTEXT_UID]||this.initTexture(t);this.boundTextures[e]!==t&&(this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),i.bindTexture(t.target,s.texture)),s.dirtyId!==t.dirtyId?(this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),this.updateTexture(t)):s.dirtyStyleId!==t.dirtyStyleId&&this.updateTextureStyle(t),this.boundTextures[e]=t}else this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),i.bindTexture(i.TEXTURE_2D,this.emptyTextures[i.TEXTURE_2D].texture),this.boundTextures[e]=null}reset(){this._unknownBoundTextures=!0,this.hasIntegerTextures=!1,this.currentLocation=-1;for(let t=0;t<this.boundTextures.length;t++)this.boundTextures[t]=this.unknownTexture}unbind(t){const{gl:e,boundTextures:i}=this;if(this._unknownBoundTextures){this._unknownBoundTextures=!1;for(let t=0;t<i.length;t++)i[t]===this.unknownTexture&&this.bind(null,t)}for(let s=0;s<i.length;s++)i[s]===t&&(this.currentLocation!==s&&(e.activeTexture(e.TEXTURE0+s),this.currentLocation=s),e.bindTexture(t.target,this.emptyTextures[t.target].texture),i[s]=null)}ensureSamplerType(t){const{boundTextures:e,hasIntegerTextures:i,CONTEXT_UID:s}=this;if(i)for(let r=t-1;r>=0;--r){const t=e[r];t&&t._glTextures[s].samplerType!==bh.FLOAT&&this.renderer.texture.unbind(t)}}initTexture(t){const e=new vg(this.gl.createTexture());return e.dirtyId=-1,t._glTextures[this.CONTEXT_UID]=e,this.managedTextures.push(t),t.on("dispose",this.destroyTexture,this),e}initTextureType(t,e){e.internalFormat=this.internalFormats[t.type]?.[t.format]??t.format,e.samplerType=this.samplerTypes[e.internalFormat]??bh.FLOAT,2===this.webGLVersion&&t.type===xh.HALF_FLOAT?e.type=this.gl.HALF_FLOAT:e.type=t.type}updateTexture(t){const e=t._glTextures[this.CONTEXT_UID];if(!e)return;const i=this.renderer;if(this.initTextureType(t,e),t.resource?.upload(i,t,e))e.samplerType!==bh.FLOAT&&(this.hasIntegerTextures=!0);else{const s=t.realWidth,r=t.realHeight,n=i.gl;(e.width!==s||e.height!==r||e.dirtyId<0)&&(e.width=s,e.height=r,n.texImage2D(t.target,0,e.internalFormat,s,r,0,t.format,e.type,null))}t.dirtyStyleId!==e.dirtyStyleId&&this.updateTextureStyle(t),e.dirtyId=t.dirtyId}destroyTexture(t,e){const{gl:i}=this;if((t=t.castToBaseTexture())._glTextures[this.CONTEXT_UID]&&(this.unbind(t),i.deleteTexture(t._glTextures[this.CONTEXT_UID].texture),t.off("dispose",this.destroyTexture,this),delete t._glTextures[this.CONTEXT_UID],!e)){const e=this.managedTextures.indexOf(t);-1!==e&&wp(this.managedTextures,e,1)}}updateTextureStyle(t){const e=t._glTextures[this.CONTEXT_UID];e&&(t.mipmap!==Ph.POW2&&2===this.webGLVersion||t.isPowerOfTwo?e.mipmap=t.mipmap>=1:e.mipmap=!1,2===this.webGLVersion||t.isPowerOfTwo?e.wrapMode=t.wrapMode:e.wrapMode=_h.CLAMP,t.resource?.style(this.renderer,t,e)||this.setStyle(t,e),e.dirtyStyleId=t.dirtyStyleId)}setStyle(t,e){const i=this.gl;if(e.mipmap&&t.mipmap!==Ph.ON_MANUAL&&i.generateMipmap(t.target),i.texParameteri(t.target,i.TEXTURE_WRAP_S,e.wrapMode),i.texParameteri(t.target,i.TEXTURE_WRAP_T,e.wrapMode),e.mipmap){i.texParameteri(t.target,i.TEXTURE_MIN_FILTER,t.scaleMode===wh.LINEAR?i.LINEAR_MIPMAP_LINEAR:i.NEAREST_MIPMAP_NEAREST);const e=this.renderer.context.extensions.anisotropicFiltering;if(e&&t.anisotropicLevel>0&&t.scaleMode===wh.LINEAR){const s=Math.min(t.anisotropicLevel,i.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY_EXT));i.texParameterf(t.target,e.TEXTURE_MAX_ANISOTROPY_EXT,s)}}else i.texParameteri(t.target,i.TEXTURE_MIN_FILTER,t.scaleMode===wh.LINEAR?i.LINEAR:i.NEAREST);i.texParameteri(t.target,i.TEXTURE_MAG_FILTER,t.scaleMode===wh.LINEAR?i.LINEAR:i.NEAREST)}destroy(){this.renderer=null}}xg.extension={type:Up.RendererSystem,name:"texture"},Wp.add(xg);class bg{constructor(t){this.renderer=t}contextChange(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID}bind(t){const{gl:e,CONTEXT_UID:i}=this,s=t._glTransformFeedbacks[i]||this.createGLTransformFeedback(t);e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,s)}unbind(){const{gl:t}=this;t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null)}beginTransformFeedback(t,e){const{gl:i,renderer:s}=this;e&&s.shader.bind(e),i.beginTransformFeedback(t)}endTransformFeedback(){const{gl:t}=this;t.endTransformFeedback()}createGLTransformFeedback(t){const{gl:e,renderer:i,CONTEXT_UID:s}=this,r=e.createTransformFeedback();t._glTransformFeedbacks[s]=r,e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,r);for(let n=0;n<t.buffers.length;n++){const r=t.buffers[n];r&&(i.buffer.update(r),r._glBuffers[s].refCount++,e.bindBufferBase(e.TRANSFORM_FEEDBACK_BUFFER,n,r._glBuffers[s].buffer||null))}return e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,null),t.disposeRunner.add(this),r}disposeTransformFeedback(t,e){const i=t._glTransformFeedbacks[this.CONTEXT_UID],s=this.gl;t.disposeRunner.remove(this);const r=this.renderer.buffer;if(r)for(let n=0;n<t.buffers.length;n++){const i=t.buffers[n];if(!i)continue;const s=i._glBuffers[this.CONTEXT_UID];s&&(s.refCount--,0===s.refCount&&!e&&r.dispose(i,e))}i&&(e||s.deleteTransformFeedback(i),delete t._glTransformFeedbacks[this.CONTEXT_UID])}destroy(){this.renderer=null}}bg.extension={type:Up.RendererSystem,name:"transformFeedback"},Wp.add(bg);class wg{constructor(t){this.renderer=t}init(t){this.screen=new vf(0,0,t.width,t.height),this.element=t.view||Oh.ADAPTER.createCanvas(),this.resolution=t.resolution||Oh.RESOLUTION,this.autoDensity=!!t.autoDensity}resizeView(t,e){this.element.width=Math.round(t*this.resolution),this.element.height=Math.round(e*this.resolution);const i=this.element.width/this.resolution,s=this.element.height/this.resolution;this.screen.width=i,this.screen.height=s,this.autoDensity&&(this.element.style.width=`${i}px`,this.element.style.height=`${s}px`),this.renderer.emit("resize",i,s),this.renderer.runners.resize.emit(this.screen.width,this.screen.height)}destroy(t){t&&this.element.parentNode?.removeChild(this.element),this.renderer=null,this.element=null,this.screen=null}}wg.defaultOptions={width:800,height:600,resolution:void 0,autoDensity:!1},wg.extension={type:[Up.RendererSystem,Up.CanvasRendererSystem],name:"_view"},Wp.add(wg),Oh.PREFER_ENV=dh.WEBGL2,Oh.STRICT_TEXTURE_CACHE=!1,Oh.RENDER_OPTIONS={...gm.defaultOptions,...pm.defaultOptions,...wg.defaultOptions,...dg.defaultOptions},Object.defineProperties(Oh,{WRAP_MODE:{get:()=>tf.defaultOptions.wrapMode,set(t){Md("7.1.0","settings.WRAP_MODE is deprecated, use BaseTexture.defaultOptions.wrapMode"),tf.defaultOptions.wrapMode=t}},SCALE_MODE:{get:()=>tf.defaultOptions.scaleMode,set(t){Md("7.1.0","settings.SCALE_MODE is deprecated, use BaseTexture.defaultOptions.scaleMode"),tf.defaultOptions.scaleMode=t}},MIPMAP_TEXTURES:{get:()=>tf.defaultOptions.mipmap,set(t){Md("7.1.0","settings.MIPMAP_TEXTURES is deprecated, use BaseTexture.defaultOptions.mipmap"),tf.defaultOptions.mipmap=t}},ANISOTROPIC_LEVEL:{get:()=>tf.defaultOptions.anisotropicLevel,set(t){Md("7.1.0","settings.ANISOTROPIC_LEVEL is deprecated, use BaseTexture.defaultOptions.anisotropicLevel"),tf.defaultOptions.anisotropicLevel=t}},FILTER_RESOLUTION:{get:()=>(Md("7.1.0","settings.FILTER_RESOLUTION is deprecated, use Filter.defaultResolution"),dm.defaultResolution),set(t){dm.defaultResolution=t}},FILTER_MULTISAMPLE:{get:()=>(Md("7.1.0","settings.FILTER_MULTISAMPLE is deprecated, use Filter.defaultMultisample"),dm.defaultMultisample),set(t){dm.defaultMultisample=t}},SPRITE_MAX_TEXTURES:{get:()=>um.defaultMaxTextures,set(t){Md("7.1.0","settings.SPRITE_MAX_TEXTURES is deprecated, use BatchRenderer.defaultMaxTextures"),um.defaultMaxTextures=t}},SPRITE_BATCH_SIZE:{get:()=>um.defaultBatchSize,set(t){Md("7.1.0","settings.SPRITE_BATCH_SIZE is deprecated, use BatchRenderer.defaultBatchSize"),um.defaultBatchSize=t}},CAN_UPLOAD_SAME_BUFFER:{get:()=>um.canUploadSameBuffer,set(t){Md("7.1.0","settings.CAN_UPLOAD_SAME_BUFFER is deprecated, use BatchRenderer.canUploadSameBuffer"),um.canUploadSameBuffer=t}},GC_MODE:{get:()=>yg.defaultMode,set(t){Md("7.1.0","settings.GC_MODE is deprecated, use TextureGCSystem.defaultMode"),yg.defaultMode=t}},GC_MAX_IDLE:{get:()=>yg.defaultMaxIdle,set(t){Md("7.1.0","settings.GC_MAX_IDLE is deprecated, use TextureGCSystem.defaultMaxIdle"),yg.defaultMaxIdle=t}},GC_MAX_CHECK_COUNT:{get:()=>yg.defaultCheckCountMax,set(t){Md("7.1.0","settings.GC_MAX_CHECK_COUNT is deprecated, use TextureGCSystem.defaultCheckCountMax"),yg.defaultCheckCountMax=t}},PRECISION_VERTEX:{get:()=>im.defaultVertexPrecision,set(t){Md("7.1.0","settings.PRECISION_VERTEX is deprecated, use Program.defaultVertexPrecision"),im.defaultVertexPrecision=t}},PRECISION_FRAGMENT:{get:()=>im.defaultFragmentPrecision,set(t){Md("7.1.0","settings.PRECISION_FRAGMENT is deprecated, use Program.defaultFragmentPrecision"),im.defaultFragmentPrecision=t}}});var _g=/* @__PURE__ */(t=>(t[t.INTERACTION=50]="INTERACTION",t[t.HIGH=25]="HIGH",t[t.NORMAL=0]="NORMAL",t[t.LOW=-25]="LOW",t[t.UTILITY=-50]="UTILITY",t))(_g||{});class Pg{constructor(t,e=null,i=0,s=!1){this.next=null,this.previous=null,this._destroyed=!1,this.fn=t,this.context=e,this.priority=i,this.once=s}match(t,e=null){return this.fn===t&&this.context===e}emit(t){this.fn&&(this.context?this.fn.call(this.context,t):this.fn(t));const e=this.next;return this.once&&this.destroy(!0),this._destroyed&&(this.next=null),e}connect(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this}destroy(t=!1){this._destroyed=!0,this.fn=null,this.context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const e=this.next;return this.next=t?null:e,this.previous=null,e}}const Eg=class t{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new Pg(null,null,1/0),this.deltaMS=1/t.targetFPMS,this.elapsedMS=1/t.targetFPMS,this._tick=t=>{this._requestId=null,this.started&&(this.update(t),this.started&&null===this._requestId&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){null===this._requestId&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){null!==this._requestId&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(t,e,i=_g.NORMAL){return this._addListener(new Pg(t,e,i))}addOnce(t,e,i=_g.NORMAL){return this._addListener(new Pg(t,e,i,!0))}_addListener(t){let e=this._head.next,i=this._head;if(e){for(;e;){if(t.priority>e.priority){t.connect(i);break}i=e,e=e.next}t.previous||t.connect(i)}else t.connect(i);return this._startIfPossible(),this}remove(t,e){let i=this._head.next;for(;i;)i=i.match(t,e)?i.destroy():i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let t=0,e=this._head;for(;e=e.next;)t++;return t}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let t=this._head.next;for(;t;)t=t.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let i;if(e>this.lastTime){if(i=this.elapsedMS=e-this.lastTime,i>this._maxElapsedMS&&(i=this._maxElapsedMS),i*=this.speed,this._minElapsedMS){const t=e-this._lastFrame|0;if(t<this._minElapsedMS)return;this._lastFrame=e-t%this._minElapsedMS}this.deltaMS=i,this.deltaTime=this.deltaMS*t.targetFPMS;const s=this._head;let r=s.next;for(;r;)r=r.emit(this.deltaTime);s.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const i=Math.min(this.maxFPS,e),s=Math.min(Math.max(0,i)/1e3,t.targetFPMS);this._maxElapsedMS=1/s}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(t){if(0===t)this._minElapsedMS=0;else{const e=Math.max(this.minFPS,t);this._minElapsedMS=1/(e/1e3)}}static get shared(){if(!t._shared){const e=t._shared=new t;e.autoStart=!0,e._protected=!0}return t._shared}static get system(){if(!t._system){const e=t._system=new t;e.autoStart=!0,e._protected=!0}return t._system}};Eg.targetFPMS=.06;let Tg=Eg;Object.defineProperties(Oh,{TARGET_FPMS:{get:()=>Tg.targetFPMS,set(t){Md("7.1.0","settings.TARGET_FPMS is deprecated, use Ticker.targetFPMS"),Tg.targetFPMS=t}}});class Ag{static init(t){t=Object.assign({autoStart:!0,sharedTicker:!1},t),Object.defineProperty(this,"ticker",{set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,_g.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=t.sharedTicker?Tg.shared:new Tg,t.autoStart&&this.start()}static destroy(){if(this._ticker){const t=this._ticker;this.ticker=null,t.destroy()}}}Ag.extension=Up.Application,Wp.add(Ag);const Ig=[];Wp.handleByList(Up.Renderer,Ig);class Sg{constructor(t){this.renderer=t}contextChange(t){let e;if(1===this.renderer.context.webGLVersion){const i=t.getParameter(t.FRAMEBUFFER_BINDING);t.bindFramebuffer(t.FRAMEBUFFER,null),e=t.getParameter(t.SAMPLES),t.bindFramebuffer(t.FRAMEBUFFER,i)}else{const i=t.getParameter(t.DRAW_FRAMEBUFFER_BINDING);t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),e=t.getParameter(t.SAMPLES),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,i)}e>=Ch.HIGH?this.multisample=Ch.HIGH:e>=Ch.MEDIUM?this.multisample=Ch.MEDIUM:e>=Ch.LOW?this.multisample=Ch.LOW:this.multisample=Ch.NONE}destroy(){}}Sg.extension={type:Up.RendererSystem,name:"_multisample"},Wp.add(Sg);class Cg{constructor(t){this.buffer=t||null,this.updateID=-1,this.byteLength=-1,this.refCount=0}}class Mg{constructor(t){this.renderer=t,this.managedBuffers={},this.boundBufferBases={}}destroy(){this.renderer=null}contextChange(){this.disposeAll(!0),this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID}bind(t){const{gl:e,CONTEXT_UID:i}=this,s=t._glBuffers[i]||this.createGLBuffer(t);e.bindBuffer(t.type,s.buffer)}unbind(t){const{gl:e}=this;e.bindBuffer(t,null)}bindBufferBase(t,e){const{gl:i,CONTEXT_UID:s}=this;if(this.boundBufferBases[e]!==t){const r=t._glBuffers[s]||this.createGLBuffer(t);this.boundBufferBases[e]=t,i.bindBufferBase(i.UNIFORM_BUFFER,e,r.buffer)}}bindBufferRange(t,e,i){const{gl:s,CONTEXT_UID:r}=this;i=i||0;const n=t._glBuffers[r]||this.createGLBuffer(t);s.bindBufferRange(s.UNIFORM_BUFFER,e||0,n.buffer,256*i,256)}update(t){const{gl:e,CONTEXT_UID:i}=this,s=t._glBuffers[i]||this.createGLBuffer(t);if(t._updateID!==s.updateID)if(s.updateID=t._updateID,e.bindBuffer(t.type,s.buffer),s.byteLength>=t.data.byteLength)e.bufferSubData(t.type,0,t.data);else{const i=t.static?e.STATIC_DRAW:e.DYNAMIC_DRAW;s.byteLength=t.data.byteLength,e.bufferData(t.type,t.data,i)}}dispose(t,e){if(!this.managedBuffers[t.id])return;delete this.managedBuffers[t.id];const i=t._glBuffers[this.CONTEXT_UID],s=this.gl;t.disposeRunner.remove(this),i&&(e||s.deleteBuffer(i.buffer),delete t._glBuffers[this.CONTEXT_UID])}disposeAll(t){const e=Object.keys(this.managedBuffers);for(let i=0;i<e.length;i++)this.dispose(this.managedBuffers[e[i]],t)}createGLBuffer(t){const{CONTEXT_UID:e,gl:i}=this;return t._glBuffers[e]=new Cg(i.createBuffer()),this.managedBuffers[t.id]=t,t.disposeRunner.add(this),t._glBuffers[e]}}Mg.extension={type:Up.RendererSystem,name:"buffer"},Wp.add(Mg);class Og{constructor(t){this.renderer=t}render(t,e){const i=this.renderer;let s,r,n,o;if(e&&(s=e.renderTexture,r=e.clear,n=e.transform,o=e.skipUpdateTransform),this.renderingToScreen=!s,i.runners.prerender.emit(),i.emit("prerender"),i.projection.transform=n,!i.context.isLost){if(s||(this.lastObjectRendered=t),!o){const e=t.enableTempParent();t.updateTransform(),t.disableTempParent(e)}i.renderTexture.bind(s),i.batch.currentRenderer.start(),(r??i.background.clearBeforeRender)&&i.renderTexture.clear(),t.render(i),i.batch.currentRenderer.flush(),s&&(e.blit&&i.framebuffer.blit(),s.baseTexture.update()),i.runners.postrender.emit(),i.projection.transform=null,i.emit("postrender")}}destroy(){this.renderer=null,this.lastObjectRendered=null}}Og.extension={type:Up.RendererSystem,name:"objectRenderer"},Wp.add(Og);const Ng=class t extends mg{constructor(e){super(),this.type=ph.WEBGL,e=Object.assign({},Oh.RENDER_OPTIONS,e),this.gl=null,this.CONTEXT_UID=0,this.globalUniforms=new rm({projectionMatrix:new Pf},!0);const i={runners:["init","destroy","contextChange","resolutionChange","reset","update","postrender","prerender","resize"],systems:t.__systems,priority:["_view","textureGenerator","background","_plugin","startup","context","state","texture","buffer","geometry","framebuffer","transformFeedback","mask","scissor","stencil","projection","textureGC","filter","renderTexture","batch","objectRenderer","_multisample"]};this.setup(i),"useContextAlpha"in e&&(Md("7.0.0","options.useContextAlpha is deprecated, use options.premultipliedAlpha and options.backgroundAlpha instead"),e.premultipliedAlpha=e.useContextAlpha&&"notMultiplied"!==e.useContextAlpha,e.backgroundAlpha=!1===e.useContextAlpha?1:e.backgroundAlpha),this._plugin.rendererPlugins=t.__plugins,this.options=e,this.startup.run(this.options)}static test(t){return!t?.forceCanvas&&Fd()}render(t,e){this.objectRenderer.render(t,e)}resize(t,e){this._view.resizeView(t,e)}reset(){return this.runners.reset.emit(),this}clear(){this.renderTexture.bind(),this.renderTexture.clear()}destroy(t=!1){this.runners.destroy.items.reverse(),this.emitWithCustomOptions(this.runners.destroy,{_view:t}),super.destroy()}get plugins(){return this._plugin.plugins}get multisample(){return this._multisample.multisample}get width(){return this._view.element.width}get height(){return this._view.element.height}get resolution(){return this._view.resolution}set resolution(t){this._view.resolution=t,this.runners.resolutionChange.emit(t)}get autoDensity(){return this._view.autoDensity}get view(){return this._view.element}get screen(){return this._view.screen}get lastObjectRendered(){return this.objectRenderer.lastObjectRendered}get renderingToScreen(){return this.objectRenderer.renderingToScreen}get rendererLogId(){return`WebGL ${this.context.webGLVersion}`}get clearBeforeRender(){return Md("7.0.0","renderer.clearBeforeRender has been deprecated, please use renderer.background.clearBeforeRender instead."),this.background.clearBeforeRender}get useContextAlpha(){return Md("7.0.0","renderer.useContextAlpha has been deprecated, please use renderer.context.premultipliedAlpha instead."),this.context.useContextAlpha}get preserveDrawingBuffer(){return Md("7.0.0","renderer.preserveDrawingBuffer has been deprecated, we cannot truly know this unless pixi created the context"),this.context.preserveDrawingBuffer}get backgroundColor(){return Md("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color}set backgroundColor(t){Md("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color=t}get backgroundAlpha(){return Md("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha}set backgroundAlpha(t){Md("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha=t}get powerPreference(){return Md("7.0.0","renderer.powerPreference has been deprecated, we can only know this if pixi creates the context"),this.context.powerPreference}generateTexture(t,e){return this.textureGenerator.generateTexture(t,e)}};Ng.extension={type:Up.Renderer,priority:1},Ng.__plugins={},Ng.__systems={};let Lg=Ng;Wp.handleByMap(Up.RendererPlugin,Lg.__plugins),Wp.handleByMap(Up.RendererSystem,Lg.__systems),Wp.add(Lg);class Rg extends Jp{constructor(t,e){const{width:i,height:s}=e||{};super(i,s),this.items=[],this.itemDirtyIds=[];for(let r=0;r<t;r++){const t=new tf;this.items.push(t),this.itemDirtyIds.push(-2)}this.length=t,this._load=null,this.baseTexture=null}initFromArray(t,e){for(let i=0;i<this.length;i++)t[i]&&(t[i].castToBaseTexture?this.addBaseTextureAt(t[i].castToBaseTexture(),i):t[i]instanceof Jp?this.addResourceAt(t[i],i):this.addResourceAt(Vp(t[i],e),i))}dispose(){for(let t=0,e=this.length;t<e;t++)this.items[t].destroy();this.items=null,this.itemDirtyIds=null,this._load=null}addResourceAt(t,e){if(!this.items[e])throw new Error(`Index ${e} is out of bounds`);return t.valid&&!this.valid&&this.resize(t.width,t.height),this.items[e].setResource(t),this}bind(t){if(null!==this.baseTexture)throw new Error("Only one base texture per TextureArray is allowed");super.bind(t);for(let e=0;e<this.length;e++)this.items[e].parentTextureArray=t,this.items[e].on("update",t.update,t)}unbind(t){super.unbind(t);for(let e=0;e<this.length;e++)this.items[e].parentTextureArray=null,this.items[e].off("update",t.update,t)}load(){if(this._load)return this._load;const t=this.items.map(t=>t.resource).filter(t=>t).map(t=>t.load());return this._load=Promise.all(t).then(()=>{const{realWidth:t,realHeight:e}=this.items[0];return this.resize(t,e),this.update(),Promise.resolve(this)}),this._load}}class Bg extends xm{constructor(t){super(t)}static test(t){const{OffscreenCanvas:e}=globalThis;return!!(e&&t instanceof e)||globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement}}const kg=class t extends Rg{constructor(e,i){const{width:s,height:r,autoLoad:n,linkBaseTexture:o}=i||{};if(e&&e.length!==t.SIDES)throw new Error(`Invalid length. Got ${e.length}, expected 6`);super(6,{width:s,height:r});for(let a=0;a<t.SIDES;a++)this.items[a].target=vh.TEXTURE_CUBE_MAP_POSITIVE_X+a;this.linkBaseTexture=!1!==o,e&&this.initFromArray(e,i),!1!==n&&this.load()}bind(t){super.bind(t),t.target=vh.TEXTURE_CUBE_MAP}addBaseTextureAt(t,e,i){if(void 0===i&&(i=this.linkBaseTexture),!this.items[e])throw new Error(`Index ${e} is out of bounds`);if(!this.linkBaseTexture||t.parentTextureArray||Object.keys(t._glTextures).length>0){if(!t.resource)throw new Error("CubeResource does not support copying of renderTexture.");this.addResourceAt(t.resource,e)}else t.target=vh.TEXTURE_CUBE_MAP_POSITIVE_X+e,t.parentTextureArray=this.baseTexture,this.items[e]=t;return t.valid&&!this.valid&&this.resize(t.realWidth,t.realHeight),this.items[e]=t,this}upload(e,i,s){const r=this.itemDirtyIds;for(let n=0;n<t.SIDES;n++){const t=this.items[n];(r[n]<t.dirtyId||s.dirtyId<i.dirtyId)&&(t.valid&&t.resource?(t.resource.upload(e,t,s),r[n]=t.dirtyId):r[n]<-1&&(e.gl.texImage2D(t.target,0,s.internalFormat,i.realWidth,i.realHeight,0,i.format,s.type,null),r[n]=-1))}return!0}static test(e){return Array.isArray(e)&&e.length===t.SIDES}};kg.SIDES=6;let Fg=kg;class Dg extends xm{constructor(t,e){let i,s,r;e=e||{},"string"==typeof t?(i=Dg.EMPTY,s=t,r=!0):(i=t,s=null,r=!1),super(i),this.url=s,this.crossOrigin=e.crossOrigin??!0,this.alphaMode="number"==typeof e.alphaMode?e.alphaMode:null,this.ownsImageBitmap=e.ownsImageBitmap??r,this._load=null,!1!==e.autoLoad&&this.load()}load(){return this._load||(this._load=new Promise(async(t,e)=>{if(null!==this.url)try{const e=await Oh.ADAPTER.fetch(this.url,{mode:this.crossOrigin?"cors":"no-cors"});if(this.destroyed)return;const i=await e.blob();if(this.destroyed)return;const s=await createImageBitmap(i,{premultiplyAlpha:null===this.alphaMode||this.alphaMode===Eh.UNPACK?"premultiply":"none"});if(this.destroyed)return void s.close();this.source=s,this.update(),t(this)}catch(i){if(this.destroyed)return;e(i),this.onError.emit(i)}else t(this)})),this._load}upload(t,e,i){return this.source instanceof ImageBitmap?("number"==typeof this.alphaMode&&(e.alphaMode=this.alphaMode),super.upload(t,e,i)):(this.load(),!1)}dispose(){this.ownsImageBitmap&&this.source instanceof ImageBitmap&&this.source.close(),super.dispose(),this._load=null}static test(t){return!!globalThis.createImageBitmap&&typeof ImageBitmap<"u"&&("string"==typeof t||t instanceof ImageBitmap)}static get EMPTY(){return Dg._EMPTY=Dg._EMPTY??Oh.ADAPTER.createCanvas(0,0),Dg._EMPTY}}const Ug=class t extends xm{constructor(t,e){e=e||{},super(Oh.ADAPTER.createCanvas()),this._width=0,this._height=0,this.svg=t,this.scale=e.scale||1,this._overrideWidth=e.width,this._overrideHeight=e.height,this._resolve=null,this._crossorigin=e.crossorigin,this._load=null,!1!==e.autoLoad&&this.load()}load(){return this._load||(this._load=new Promise(e=>{if(this._resolve=()=>{this.update(),e(this)},t.SVG_XML.test(this.svg.trim())){if(!btoa)throw new Error("Your browser doesn't support base64 conversions.");this.svg=`data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(this.svg)))}`}this._loadSvg()})),this._load}_loadSvg(){const t=new Image;xm.crossOrigin(t,this.svg,this._crossorigin),t.src=this.svg,t.onerror=e=>{this._resolve&&(t.onerror=null,this.onError.emit(e))},t.onload=()=>{if(!this._resolve)return;const e=t.width,i=t.height;if(!e||!i)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");let s=e*this.scale,r=i*this.scale;(this._overrideWidth||this._overrideHeight)&&(s=this._overrideWidth||this._overrideHeight/i*e,r=this._overrideHeight||this._overrideWidth/e*i),s=Math.round(s),r=Math.round(r);const n=this.source;n.width=s,n.height=r,n._pixiId=`canvas_${Ep()}`,n.getContext("2d").drawImage(t,0,0,e,i,0,0,s,r),this._resolve(),this._resolve=null}}static getSize(e){const i=t.SVG_SIZE.exec(e),s={};return i&&(s[i[1]]=Math.round(parseFloat(i[3])),s[i[5]]=Math.round(parseFloat(i[7]))),s}dispose(){super.dispose(),this._resolve=null,this._crossorigin=null}static test(e,i){return"svg"===i||"string"==typeof e&&e.startsWith("data:image/svg+xml")||"string"==typeof e&&t.SVG_XML.test(e)}};Ug.SVG_XML=/^(<\?xml[^?]+\?>)?\s*(<!--[^(-->)]*-->)?\s*\<svg/m,Ug.SVG_SIZE=/<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i;let Gg=Ug;const Xg=class t extends xm{constructor(e,i){if(i=i||{},!(e instanceof HTMLVideoElement)){const s=document.createElement("video");!1!==i.autoLoad&&s.setAttribute("preload","auto"),!1!==i.playsinline&&(s.setAttribute("webkit-playsinline",""),s.setAttribute("playsinline","")),!0===i.muted&&(s.setAttribute("muted",""),s.muted=!0),!0===i.loop&&s.setAttribute("loop",""),!1!==i.autoPlay&&s.setAttribute("autoplay",""),"string"==typeof e&&(e=[e]);const r=e[0].src||e[0];xm.crossOrigin(s,r,i.crossorigin);for(let i=0;i<e.length;++i){const r=document.createElement("source");let{src:n,mime:o}=e[i];if(n=n||e[i],n.startsWith("data:"))o=n.slice(5,n.indexOf(";"));else if(!n.startsWith("blob:")){const e=n.split("?").shift().toLowerCase(),i=e.slice(e.lastIndexOf(".")+1);o=o||t.MIME_TYPES[i]||`video/${i}`}r.src=n,o&&(r.type=o),s.appendChild(r)}e=s}super(e),this.noSubImage=!0,this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=i.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=!1!==i.autoPlay,this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),!1!==i.autoLoad&&this.load()}update(t=0){if(!this.destroyed){if(this._updateFPS){const t=Tg.shared.elapsedMS*this.source.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-t)}(!this._updateFPS||this._msToNextUpdate<=0)&&(super.update(),this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0)}}_videoFrameRequestCallback(){this.update(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.source.requestVideoFrameCallback(this._videoFrameRequestCallback)}load(){if(this._load)return this._load;const t=this.source;return(t.readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),t.addEventListener("play",this._onPlayStart),t.addEventListener("pause",this._onPlayStop),t.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._onCanPlay():(t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlay),t.addEventListener("error",this._onError,!0)),this._load=new Promise((e,i)=>{this.valid?e(this):(this._resolve=e,this._reject=i,t.load())}),this._load}_onError(t){this.source.removeEventListener("error",this._onError,!0),this.onError.emit(t),this._reject&&(this._reject(t),this._reject=null,this._resolve=null)}_isSourcePlaying(){const t=this.source;return!t.paused&&!t.ended}_isSourceReady(){return this.source.readyState>2}_onPlayStart(){this.valid||this._onCanPlay(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.update(),this._msToNextUpdate=0)}_onCanPlay(){const t=this.source;t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlay);const e=this.valid;this._msToNextUpdate=0,this.update(),this._msToNextUpdate=0,!e&&this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&t.play()}dispose(){this._configureAutoUpdate();const t=this.source;t&&(t.removeEventListener("play",this._onPlayStart),t.removeEventListener("pause",this._onPlayStop),t.removeEventListener("seeked",this._onSeeked),t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlay),t.removeEventListener("error",this._onError,!0),t.pause(),t.src="",t.load()),super.dispose()}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){t!==this._autoUpdate&&(this._autoUpdate=t,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(t){t!==this._updateFPS&&(this._updateFPS=t,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.source.requestVideoFrameCallback?(this._isConnectedToTicker&&(Tg.shared.remove(this.update,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),null===this._videoFrameRequestCallbackHandle&&(this._videoFrameRequestCallbackHandle=this.source.requestVideoFrameCallback(this._videoFrameRequestCallback))):(null!==this._videoFrameRequestCallbackHandle&&(this.source.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(Tg.shared.add(this.update,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(null!==this._videoFrameRequestCallbackHandle&&(this.source.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(Tg.shared.remove(this.update,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e,i){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement||t.TYPES.includes(i)}};Xg.TYPES=["mp4","m4v","webm","ogg","ogv","h264","avi","mov"],Xg.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Wg=Xg;zp.push(Dg,bm,Bg,Wg,class extends xm{constructor(t){super(t)}static test(t){return!!globalThis.VideoFrame&&t instanceof globalThis.VideoFrame}},Gg,Kp,Fg,class extends Rg{constructor(t,e){const{width:i,height:s}=e||{};let r,n;Array.isArray(t)?(r=t,n=t.length):n=t,super(n,{width:i,height:s}),r&&this.initFromArray(r,e)}addBaseTextureAt(t,e){if(!t.resource)throw new Error("ArrayResource does not support RenderTexture");return this.addResourceAt(t.resource,e),this}bind(t){super.bind(t),t.target=vh.TEXTURE_2D_ARRAY}upload(t,e,i){const{length:s,itemDirtyIds:r,items:n}=this,{gl:o}=t;i.dirtyId<0&&o.texImage3D(o.TEXTURE_2D_ARRAY,0,i.internalFormat,this._width,this._height,s,0,e.format,i.type,null);for(let a=0;a<s;a++){const t=n[a];r[a]<t.dirtyId&&(r[a]=t.dirtyId,t.valid&&o.texSubImage3D(o.TEXTURE_2D_ARRAY,0,0,0,a,t.resource.width,t.resource.height,1,e.format,i.type,t.resource.source))}return!0}});class Yg{constructor(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.rect=null,this.updateID=-1}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}clear(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0}getRectangle(t){return this.minX>this.maxX||this.minY>this.maxY?vf.EMPTY:((t=t||new vf(0,0,1,1)).x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)}addPoint(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)}addPointMatrix(t,e){const{a:i,b:s,c:r,d:n,tx:o,ty:a}=t,l=i*e.x+r*e.y+o,h=s*e.x+n*e.y+a;this.minX=Math.min(this.minX,l),this.maxX=Math.max(this.maxX,l),this.minY=Math.min(this.minY,h),this.maxY=Math.max(this.maxY,h)}addQuad(t){let e=this.minX,i=this.minY,s=this.maxX,r=this.maxY,n=t[0],o=t[1];e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,n=t[2],o=t[3],e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,n=t[4],o=t[5],e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,n=t[6],o=t[7],e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,this.minX=e,this.minY=i,this.maxX=s,this.maxY=r}addFrame(t,e,i,s,r){this.addFrameMatrix(t.worldTransform,e,i,s,r)}addFrameMatrix(t,e,i,s,r){const n=t.a,o=t.b,a=t.c,l=t.d,h=t.tx,u=t.ty;let c=this.minX,d=this.minY,p=this.maxX,f=this.maxY,m=n*e+a*i+h,g=o*e+l*i+u;c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*s+a*i+h,g=o*s+l*i+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*e+a*r+h,g=o*e+l*r+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*s+a*r+h,g=o*s+l*r+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,this.minX=c,this.minY=d,this.maxX=p,this.maxY=f}addVertexData(t,e,i){let s=this.minX,r=this.minY,n=this.maxX,o=this.maxY;for(let a=e;a<i;a+=2){const e=t[a],i=t[a+1];s=e<s?e:s,r=i<r?i:r,n=e>n?e:n,o=i>o?i:o}this.minX=s,this.minY=r,this.maxX=n,this.maxY=o}addVertices(t,e,i,s){this.addVerticesMatrix(t.worldTransform,e,i,s)}addVerticesMatrix(t,e,i,s,r=0,n=r){const o=t.a,a=t.b,l=t.c,h=t.d,u=t.tx,c=t.ty;let d=this.minX,p=this.minY,f=this.maxX,m=this.maxY;for(let g=i;g<s;g+=2){const t=e[g],i=e[g+1],s=o*t+l*i+u,y=h*i+a*t+c;d=Math.min(d,s-r),f=Math.max(f,s+r),p=Math.min(p,y-n),m=Math.max(m,y+n)}this.minX=d,this.minY=p,this.maxX=f,this.maxY=m}addBounds(t){const e=this.minX,i=this.minY,s=this.maxX,r=this.maxY;this.minX=t.minX<e?t.minX:e,this.minY=t.minY<i?t.minY:i,this.maxX=t.maxX>s?t.maxX:s,this.maxY=t.maxY>r?t.maxY:r}addBoundsMask(t,e){const i=t.minX>e.minX?t.minX:e.minX,s=t.minY>e.minY?t.minY:e.minY,r=t.maxX<e.maxX?t.maxX:e.maxX,n=t.maxY<e.maxY?t.maxY:e.maxY;if(i<=r&&s<=n){const t=this.minX,e=this.minY,o=this.maxX,a=this.maxY;this.minX=i<t?i:t,this.minY=s<e?s:e,this.maxX=r>o?r:o,this.maxY=n>a?n:a}}addBoundsMatrix(t,e){this.addFrameMatrix(e,t.minX,t.minY,t.maxX,t.maxY)}addBoundsArea(t,e){const i=t.minX>e.x?t.minX:e.x,s=t.minY>e.y?t.minY:e.y,r=t.maxX<e.x+e.width?t.maxX:e.x+e.width,n=t.maxY<e.y+e.height?t.maxY:e.y+e.height;if(i<=r&&s<=n){const t=this.minX,e=this.minY,o=this.maxX,a=this.maxY;this.minX=i<t?i:t,this.minY=s<e?s:e,this.maxX=r>o?r:o,this.maxY=n>a?n:a}}pad(t=0,e=t){this.isEmpty()||(this.minX-=t,this.maxX+=t,this.minY-=e,this.maxY+=e)}addFramePad(t,e,i,s,r,n){t-=r,e-=n,i+=r,s+=n,this.minX=this.minX<t?this.minX:t,this.maxX=this.maxX>i?this.maxX:i,this.minY=this.minY<e?this.minY:e,this.maxY=this.maxY>s?this.maxY:s}}class Hg extends Qh{constructor(){super(),this.tempDisplayObjectParent=null,this.transform=new Rf,this.alpha=1,this.visible=!0,this.renderable=!0,this.cullable=!1,this.cullArea=null,this.parent=null,this.worldAlpha=1,this._lastSortedIndex=0,this._zIndex=0,this.filterArea=null,this.filters=null,this._enabledFilters=null,this._bounds=new Yg,this._localBounds=null,this._boundsID=0,this._boundsRect=null,this._localBoundsRect=null,this._mask=null,this._maskRefCount=0,this._destroyed=!1,this.isSprite=!1,this.isMask=!1}static mixin(t){const e=Object.keys(t);for(let i=0;i<e.length;++i){const s=e[i];Object.defineProperty(Hg.prototype,s,Object.getOwnPropertyDescriptor(t,s))}}get destroyed(){return this._destroyed}_recursivePostUpdateTransform(){this.parent?(this.parent._recursivePostUpdateTransform(),this.transform.updateTransform(this.parent.transform)):this.transform.updateTransform(this._tempDisplayObjectParent.transform)}updateTransform(){this._boundsID++,this.transform.updateTransform(this.parent.transform),this.worldAlpha=this.alpha*this.parent.worldAlpha}getBounds(t,e){return t||(this.parent?(this._recursivePostUpdateTransform(),this.updateTransform()):(this.parent=this._tempDisplayObjectParent,this.updateTransform(),this.parent=null)),this._bounds.updateID!==this._boundsID&&(this.calculateBounds(),this._bounds.updateID=this._boundsID),e||(this._boundsRect||(this._boundsRect=new vf),e=this._boundsRect),this._bounds.getRectangle(e)}getLocalBounds(t){t||(this._localBoundsRect||(this._localBoundsRect=new vf),t=this._localBoundsRect),this._localBounds||(this._localBounds=new Yg);const e=this.transform,i=this.parent;this.parent=null,this._tempDisplayObjectParent.worldAlpha=i?.worldAlpha??1,this.transform=this._tempDisplayObjectParent.transform;const s=this._bounds,r=this._boundsID;this._bounds=this._localBounds;const n=this.getBounds(!1,t);return this.parent=i,this.transform=e,this._bounds=s,this._bounds.updateID+=this._boundsID-r,n}toGlobal(t,e,i=!1){return i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)}toLocal(t,e,i,s){return e&&(t=e.toGlobal(t,i,s)),s||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,i)}setParent(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t}removeFromParent(){this.parent?.removeChild(this)}setTransform(t=0,e=0,i=1,s=1,r=0,n=0,o=0,a=0,l=0){return this.position.x=t,this.position.y=e,this.scale.x=i||1,this.scale.y=s||1,this.rotation=r,this.skew.x=n,this.skew.y=o,this.pivot.x=a,this.pivot.y=l,this}destroy(t){this.removeFromParent(),this._destroyed=!0,this.transform=null,this.parent=null,this._bounds=null,this.mask=null,this.cullArea=null,this.filters=null,this.filterArea=null,this.hitArea=null,this.eventMode="auto",this.interactiveChildren=!1,this.emit("destroyed"),this.removeAllListeners()}get _tempDisplayObjectParent(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new $g),this.tempDisplayObjectParent}enableTempParent(){const t=this.parent;return this.parent=this._tempDisplayObjectParent,t}disableTempParent(t){this.parent=t}get x(){return this.position.x}set x(t){this.transform.position.x=t}get y(){return this.position.y}set y(t){this.transform.position.y=t}get worldTransform(){return this.transform.worldTransform}get localTransform(){return this.transform.localTransform}get position(){return this.transform.position}set position(t){this.transform.position.copyFrom(t)}get scale(){return this.transform.scale}set scale(t){this.transform.scale.copyFrom(t)}get pivot(){return this.transform.pivot}set pivot(t){this.transform.pivot.copyFrom(t)}get skew(){return this.transform.skew}set skew(t){this.transform.skew.copyFrom(t)}get rotation(){return this.transform.rotation}set rotation(t){this.transform.rotation=t}get angle(){return this.transform.rotation*pf}set angle(t){this.transform.rotation=t*ff}get zIndex(){return this._zIndex}set zIndex(t){this._zIndex!==t&&(this._zIndex=t,this.parent&&(this.parent.sortDirty=!0))}get worldVisible(){let t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}get mask(){return this._mask}set mask(t){if(this._mask!==t){if(this._mask){const t=this._mask.isMaskData?this._mask.maskObject:this._mask;t&&(t._maskRefCount--,0===t._maskRefCount&&(t.renderable=!0,t.isMask=!1))}if(this._mask=t,this._mask){const t=this._mask.isMaskData?this._mask.maskObject:this._mask;t&&(0===t._maskRefCount&&(t.renderable=!1,t.isMask=!0),t._maskRefCount++)}}}}class $g extends Hg{constructor(){super(...arguments),this.sortDirty=null}}Hg.prototype.displayObjectUpdateTransform=Hg.prototype.updateTransform;const jg=new Pf;function zg(t,e){return t.zIndex===e.zIndex?t._lastSortedIndex-e._lastSortedIndex:t.zIndex-e.zIndex}const Vg=class t extends Hg{constructor(){super(),this.children=[],this.sortableChildren=t.defaultSortableChildren,this.sortDirty=!1}onChildrenChange(t){}addChild(...t){if(t.length>1)for(let e=0;e<t.length;e++)this.addChild(t[e]);else{const e=t[0];e.parent&&e.parent.removeChild(e),e.parent=this,this.sortDirty=!0,e.transform._parentID=-1,this.children.push(e),this._boundsID++,this.onChildrenChange(this.children.length-1),this.emit("childAdded",e,this,this.children.length-1),e.emit("added",this)}return t[0]}addChildAt(t,e){if(e<0||e>this.children.length)throw new Error(`${t}addChildAt: The index ${e} supplied is out of bounds ${this.children.length}`);return t.parent&&t.parent.removeChild(t),t.parent=this,this.sortDirty=!0,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),this.emit("childAdded",t,this,e),t}swapChildren(t,e){if(t===e)return;const i=this.getChildIndex(t),s=this.getChildIndex(e);this.children[i]=e,this.children[s]=t,this.onChildrenChange(i<s?i:s)}getChildIndex(t){const e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e}setChildIndex(t,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);const i=this.getChildIndex(t);wp(this.children,i,1),this.children.splice(e,0,t),this.onChildrenChange(e)}getChildAt(t){if(t<0||t>=this.children.length)throw new Error(`getChildAt: Index (${t}) does not exist.`);return this.children[t]}removeChild(...t){if(t.length>1)for(let e=0;e<t.length;e++)this.removeChild(t[e]);else{const e=t[0],i=this.children.indexOf(e);if(-1===i)return null;e.parent=null,e.transform._parentID=-1,wp(this.children,i,1),this._boundsID++,this.onChildrenChange(i),e.emit("removed",this),this.emit("childRemoved",e,this,i)}return t[0]}removeChildAt(t){const e=this.getChildAt(t);return e.parent=null,e.transform._parentID=-1,wp(this.children,t,1),this._boundsID++,this.onChildrenChange(t),e.emit("removed",this),this.emit("childRemoved",e,this,t),e}removeChildren(t=0,e=this.children.length){const i=t,s=e-i;let r;if(s>0&&s<=e){r=this.children.splice(i,s);for(let t=0;t<r.length;++t)r[t].parent=null,r[t].transform&&(r[t].transform._parentID=-1);this._boundsID++,this.onChildrenChange(t);for(let t=0;t<r.length;++t)r[t].emit("removed",this),this.emit("childRemoved",r[t],this,t);return r}if(0===s&&0===this.children.length)return[];throw new RangeError("removeChildren: numeric values are outside the acceptable range.")}sortChildren(){let t=!1;for(let e=0,i=this.children.length;e<i;++e){const i=this.children[e];i._lastSortedIndex=e,!t&&0!==i.zIndex&&(t=!0)}t&&this.children.length>1&&this.children.sort(zg),this.sortDirty=!1}updateTransform(){this.sortableChildren&&this.sortDirty&&this.sortChildren(),this._boundsID++,this.transform.updateTransform(this.parent.transform),this.worldAlpha=this.alpha*this.parent.worldAlpha;for(let t=0,e=this.children.length;t<e;++t){const e=this.children[t];e.visible&&e.updateTransform()}}calculateBounds(){this._bounds.clear(),this._calculateBounds();for(let t=0;t<this.children.length;t++){const e=this.children[t];if(e.visible&&e.renderable)if(e.calculateBounds(),e._mask){const t=e._mask.isMaskData?e._mask.maskObject:e._mask;t?(t.calculateBounds(),this._bounds.addBoundsMask(e._bounds,t._bounds)):this._bounds.addBounds(e._bounds)}else e.filterArea?this._bounds.addBoundsArea(e._bounds,e.filterArea):this._bounds.addBounds(e._bounds)}this._bounds.updateID=this._boundsID}getLocalBounds(t,e=!1){const i=super.getLocalBounds(t);if(!e)for(let s=0,r=this.children.length;s<r;++s){const t=this.children[s];t.visible&&t.updateTransform()}return i}_calculateBounds(){}_renderWithCulling(e){const i=e.renderTexture.sourceFrame;if(!(i.width>0&&i.height>0))return;let s,r;this.cullArea?(s=this.cullArea,r=this.worldTransform):this._render!==t.prototype._render&&(s=this.getBounds(!0));const n=e.projection.transform;if(n&&(r?(r=jg.copyFrom(r),r.prepend(n)):r=n),s&&i.intersects(s,r))this._render(e);else if(this.cullArea)return;for(let t=0,o=this.children.length;t<o;++t){const i=this.children[t],s=i.cullable;i.cullable=s||!this.cullArea,i.render(e),i.cullable=s}}render(t){if(this.visible&&!(this.worldAlpha<=0)&&this.renderable)if(this._mask||this.filters?.length)this.renderAdvanced(t);else if(this.cullable)this._renderWithCulling(t);else{this._render(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].render(t)}}renderAdvanced(t){const e=this.filters,i=this._mask;if(e){this._enabledFilters||(this._enabledFilters=[]),this._enabledFilters.length=0;for(let t=0;t<e.length;t++)e[t].enabled&&this._enabledFilters.push(e[t])}const s=e&&this._enabledFilters?.length||i&&(!i.isMaskData||i.enabled&&(i.autoDetect||i.type!==Sh.NONE));if(s&&t.batch.flush(),e&&this._enabledFilters?.length&&t.filter.push(this,this._enabledFilters),i&&t.mask.push(this,this._mask),this.cullable)this._renderWithCulling(t);else{this._render(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].render(t)}s&&t.batch.flush(),i&&t.mask.pop(this),e&&this._enabledFilters?.length&&t.filter.pop()}_render(t){}destroy(t){super.destroy(),this.sortDirty=!1;const e="boolean"==typeof t?t:t?.children,i=this.removeChildren(0,this.children.length);if(e)for(let s=0;s<i.length;++s)i[s].destroy(t)}get width(){return this.scale.x*this.getLocalBounds().width}set width(t){const e=this.getLocalBounds().width;this.scale.x=0!==e?t/e:1,this._width=t}get height(){return this.scale.y*this.getLocalBounds().height}set height(t){const e=this.getLocalBounds().height;this.scale.y=0!==e?t/e:1,this._height=t}};Vg.defaultSortableChildren=!1;let qg=Vg;qg.prototype.containerUpdateTransform=qg.prototype.updateTransform,Object.defineProperties(Oh,{SORTABLE_CHILDREN:{get:()=>qg.defaultSortableChildren,set(t){Md("7.1.0","settings.SORTABLE_CHILDREN is deprecated, use Container.defaultSortableChildren"),qg.defaultSortableChildren=t}}});const Jg=new gf,Kg=new Uint16Array([0,1,2,0,2,3]);class Zg extends qg{constructor(t){super(),this._anchor=new Nf(this._onAnchorUpdate,this,t?t.defaultAnchor.x:0,t?t.defaultAnchor.y:0),this._texture=null,this._width=0,this._height=0,this._tintColor=new pp(16777215),this._tintRGB=null,this.tint=16777215,this.blendMode=mh.NORMAL,this._cachedTint=16777215,this.uvs=null,this.texture=t||Em.EMPTY,this.vertexData=new Float32Array(8),this.vertexTrimmedData=null,this._transformID=-1,this._textureID=-1,this._transformTrimmedID=-1,this._textureTrimmedID=-1,this.indices=Kg,this.pluginName="batch",this.isSprite=!0,this._roundPixels=Oh.ROUND_PIXELS}_onTextureUpdate(){this._textureID=-1,this._textureTrimmedID=-1,this._cachedTint=16777215,this._width&&(this.scale.x=_p(this.scale.x)*this._width/this._texture.orig.width),this._height&&(this.scale.y=_p(this.scale.y)*this._height/this._texture.orig.height)}_onAnchorUpdate(){this._transformID=-1,this._transformTrimmedID=-1}calculateVertices(){const t=this._texture;if(this._transformID===this.transform._worldID&&this._textureID===t._updateID)return;this._textureID!==t._updateID&&(this.uvs=this._texture._uvs.uvsFloat32),this._transformID=this.transform._worldID,this._textureID=t._updateID;const e=this.transform.worldTransform,i=e.a,s=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty,l=this.vertexData,h=t.trim,u=t.orig,c=this._anchor;let d=0,p=0,f=0,m=0;if(h?(p=h.x-c._x*u.width,d=p+h.width,m=h.y-c._y*u.height,f=m+h.height):(p=-c._x*u.width,d=p+u.width,m=-c._y*u.height,f=m+u.height),l[0]=i*p+r*m+o,l[1]=n*m+s*p+a,l[2]=i*d+r*m+o,l[3]=n*m+s*d+a,l[4]=i*d+r*f+o,l[5]=n*f+s*d+a,l[6]=i*p+r*f+o,l[7]=n*f+s*p+a,this._roundPixels){const t=Oh.RESOLUTION;for(let e=0;e<l.length;++e)l[e]=Math.round(l[e]*t)/t}}calculateTrimmedVertices(){if(this.vertexTrimmedData){if(this._transformTrimmedID===this.transform._worldID&&this._textureTrimmedID===this._texture._updateID)return}else this.vertexTrimmedData=new Float32Array(8);this._transformTrimmedID=this.transform._worldID,this._textureTrimmedID=this._texture._updateID;const t=this._texture,e=this.vertexTrimmedData,i=t.orig,s=this._anchor,r=this.transform.worldTransform,n=r.a,o=r.b,a=r.c,l=r.d,h=r.tx,u=r.ty,c=-s._x*i.width,d=c+i.width,p=-s._y*i.height,f=p+i.height;if(e[0]=n*c+a*p+h,e[1]=l*p+o*c+u,e[2]=n*d+a*p+h,e[3]=l*p+o*d+u,e[4]=n*d+a*f+h,e[5]=l*f+o*d+u,e[6]=n*c+a*f+h,e[7]=l*f+o*c+u,this._roundPixels){const t=Oh.RESOLUTION;for(let i=0;i<e.length;++i)e[i]=Math.round(e[i]*t)/t}}_render(t){this.calculateVertices(),t.batch.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this)}_calculateBounds(){const t=this._texture.trim,e=this._texture.orig;!t||t.width===e.width&&t.height===e.height?(this.calculateVertices(),this._bounds.addQuad(this.vertexData)):(this.calculateTrimmedVertices(),this._bounds.addQuad(this.vertexTrimmedData))}getLocalBounds(t){return 0===this.children.length?(this._localBounds||(this._localBounds=new Yg),this._localBounds.minX=this._texture.orig.width*-this._anchor._x,this._localBounds.minY=this._texture.orig.height*-this._anchor._y,this._localBounds.maxX=this._texture.orig.width*(1-this._anchor._x),this._localBounds.maxY=this._texture.orig.height*(1-this._anchor._y),t||(this._localBoundsRect||(this._localBoundsRect=new vf),t=this._localBoundsRect),this._localBounds.getRectangle(t)):super.getLocalBounds.call(this,t)}containsPoint(t){this.worldTransform.applyInverse(t,Jg);const e=this._texture.orig.width,i=this._texture.orig.height,s=-e*this.anchor.x;let r=0;return Jg.x>=s&&Jg.x<s+e&&(r=-i*this.anchor.y,Jg.y>=r&&Jg.y<r+i)}destroy(t){if(super.destroy(t),this._texture.off("update",this._onTextureUpdate,this),this._anchor=null,"boolean"==typeof t?t:t?.texture){const e="boolean"==typeof t?t:t?.baseTexture;this._texture.destroy(!!e)}this._texture=null}static from(t,e){const i=t instanceof Em?t:Em.from(t,e);return new Zg(i)}set roundPixels(t){this._roundPixels!==t&&(this._transformID=-1,this._transformTrimmedID=-1),this._roundPixels=t}get roundPixels(){return this._roundPixels}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(t){const e=_p(this.scale.x)||1;this.scale.x=e*t/this._texture.orig.width,this._width=t}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(t){const e=_p(this.scale.y)||1;this.scale.y=e*t/this._texture.orig.height,this._height=t}get anchor(){return this._anchor}set anchor(t){this._anchor.copyFrom(t)}get tint(){return this._tintColor.value}set tint(t){this._tintColor.setValue(t),this._tintRGB=this._tintColor.toLittleEndianNumber()}get tintValue(){return this._tintColor.toNumber()}get texture(){return this._texture}set texture(t){this._texture!==t&&(this._texture&&this._texture.off("update",this._onTextureUpdate,this),this._texture=t||Em.EMPTY,this._cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.valid?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}const Qg={build(t){const e=t.points;let i,s,r,n,o,a;if(t.type===mf.CIRC){const e=t.shape;i=e.x,s=e.y,o=a=e.radius,r=n=0}else if(t.type===mf.ELIP){const e=t.shape;i=e.x,s=e.y,o=e.width,a=e.height,r=n=0}else{const e=t.shape,l=e.width/2,h=e.height/2;i=e.x+l,s=e.y+h,o=a=Math.max(0,Math.min(e.radius,Math.min(l,h))),r=l-o,n=h-a}if(!(o>=0&&a>=0&&r>=0&&n>=0))return void(e.length=0);const l=Math.ceil(2.3*Math.sqrt(o+a)),h=8*l+(r?4:0)+(n?4:0);if(e.length=h,0===h)return;if(0===l)return e.length=8,e[0]=e[6]=i+r,e[1]=e[3]=s+n,e[2]=e[4]=i-r,void(e[5]=e[7]=s-n);let u=0,c=4*l+(r?2:0)+2,d=c,p=h;{const t=r+o,a=n,l=i+t,h=i-t,f=s+a;if(e[u++]=l,e[u++]=f,e[--c]=f,e[--c]=h,n){const t=s-a;e[d++]=h,e[d++]=t,e[--p]=t,e[--p]=l}}for(let f=1;f<l;f++){const t=Math.PI/2*(f/l),h=r+Math.cos(t)*o,m=n+Math.sin(t)*a,g=i+h,y=i-h,v=s+m,x=s-m;e[u++]=g,e[u++]=v,e[--c]=v,e[--c]=y,e[d++]=y,e[d++]=x,e[--p]=x,e[--p]=g}{const t=n+a,o=i+r,l=i-r,h=s+t,c=s-t;e[u++]=o,e[u++]=h,e[--p]=c,e[--p]=o,r&&(e[u++]=l,e[u++]=h,e[--p]=c,e[--p]=l)}},triangulate(t,e){const i=t.points,s=e.points,r=e.indices;if(0===i.length)return;let n=s.length/2;const o=n;let a,l;if(t.type!==mf.RREC){const e=t.shape;a=e.x,l=e.y}else{const e=t.shape;a=e.x+e.width/2,l=e.y+e.height/2}const h=t.matrix;s.push(t.matrix?h.a*a+h.c*l+h.tx:a,t.matrix?h.b*a+h.d*l+h.ty:l),n++,s.push(i[0],i[1]);for(let u=2;u<i.length;u+=2)s.push(i[u],i[u+1]),r.push(n++,o,n);r.push(o+1,o,n)}};function ty(t,e=!1){const i=t.length;if(i<6)return;let s=0;for(let r=0,n=t[i-2],o=t[i-1];r<i;r+=2){const e=t[r],i=t[r+1];s+=(e-n)*(i+o),n=e,o=i}if(!e&&s>0||e&&s<=0){const e=i/2;for(let s=e+e%2;s<i;s+=2){const e=i-s-2,r=i-s-1,n=s,o=s+1;[t[e],t[n]]=[t[n],t[e]],[t[r],t[o]]=[t[o],t[r]]}}}const ey={build(t){t.points=t.shape.points.slice()},triangulate(t,e){let i=t.points;const s=t.holes,r=e.points,n=e.indices;if(i.length>=6){ty(i,!1);const t=[];for(let r=0;r<s.length;r++){const e=s[r];ty(e.points,!0),t.push(i.length/2),i=i.concat(e.points)}const e=Nt(i,t,2);if(!e)return;const o=r.length/2;for(let i=0;i<e.length;i+=3)n.push(e[i]+o),n.push(e[i+1]+o),n.push(e[i+2]+o);for(let s=0;s<i.length;s++)r.push(i[s])}}},iy={build(t){const e=t.shape,i=e.x,s=e.y,r=e.width,n=e.height,o=t.points;o.length=0,r>=0&&n>=0&&o.push(i,s,i+r,s,i+r,s+n,i,s+n)},triangulate(t,e){const i=t.points,s=e.points;if(0===i.length)return;const r=s.length/2;s.push(i[0],i[1],i[2],i[3],i[6],i[7],i[4],i[5]),e.indices.push(r,r+1,r+2,r+1,r+2,r+3)}},sy={build(t){Qg.build(t)},triangulate(t,e){Qg.triangulate(t,e)}};var ry=/* @__PURE__ */(t=>(t.MITER="miter",t.BEVEL="bevel",t.ROUND="round",t))(ry||{}),ny=/* @__PURE__ */(t=>(t.BUTT="butt",t.ROUND="round",t.SQUARE="square",t))(ny||{});const oy={adaptive:!0,maxLength:10,minSegments:8,maxSegments:2048,epsilon:1e-4,_segmentsCount(t,e=20){if(!this.adaptive||!t||isNaN(t))return e;let i=Math.ceil(t/this.maxLength);return i<this.minSegments?i=this.minSegments:i>this.maxSegments&&(i=this.maxSegments),i}};class ay{static curveTo(t,e,i,s,r,n){const o=n[n.length-2],a=n[n.length-1]-e,l=o-t,h=s-e,u=i-t,c=Math.abs(a*u-l*h);if(c<1e-8||0===r)return(n[n.length-2]!==t||n[n.length-1]!==e)&&n.push(t,e),null;const d=a*a+l*l,p=h*h+u*u,f=a*h+l*u,m=r*Math.sqrt(d)/c,g=r*Math.sqrt(p)/c,y=m*f/d,v=g*f/p,x=m*u+g*l,b=m*h+g*a,w=l*(g+y),_=a*(g+y),P=u*(m+v),E=h*(m+v);return{cx:x+t,cy:b+e,radius:r,startAngle:Math.atan2(_-b,w-x),endAngle:Math.atan2(E-b,P-x),anticlockwise:l*h>u*a}}static arc(t,e,i,s,r,n,o,a,l){const h=o-n,u=oy._segmentsCount(Math.abs(h)*r,40*Math.ceil(Math.abs(h)/df)),c=h/(2*u),d=2*c,p=Math.cos(c),f=Math.sin(c),m=u-1,g=m%1/m;for(let y=0;y<=m;++y){const t=c+n+d*(y+g*y),e=Math.cos(t),o=-Math.sin(t);l.push((p*e+f*o)*r+i,(p*-o+f*e)*r+s)}}}class ly{constructor(){this.reset()}begin(t,e,i){this.reset(),this.style=t,this.start=e,this.attribStart=i}end(t,e){this.attribSize=e-this.attribStart,this.size=t-this.start}reset(){this.style=null,this.size=0,this.start=0,this.attribStart=0,this.attribSize=0}}class hy{static curveLength(t,e,i,s,r,n,o,a){let l=0,h=0,u=0,c=0,d=0,p=0,f=0,m=0,g=0,y=0,v=0,x=t,b=e;for(let w=1;w<=10;++w)h=w/10,u=h*h,c=u*h,d=1-h,p=d*d,f=p*d,m=f*t+3*p*h*i+3*d*u*r+c*o,g=f*e+3*p*h*s+3*d*u*n+c*a,y=x-m,v=b-g,x=m,b=g,l+=Math.sqrt(y*y+v*v);return l}static curveTo(t,e,i,s,r,n,o){const a=o[o.length-2],l=o[o.length-1];o.length-=2;const h=oy._segmentsCount(hy.curveLength(a,l,t,e,i,s,r,n));let u=0,c=0,d=0,p=0,f=0;o.push(a,l);for(let m=1,g=0;m<=h;++m)g=m/h,u=1-g,c=u*u,d=c*u,p=g*g,f=p*g,o.push(d*a+3*c*g*t+3*u*p*i+f*r,d*l+3*c*g*e+3*u*p*s+f*n)}}function uy(t,e,i,s,r,n,o,a){let l,h;o?(l=s,h=-i):(l=-s,h=i);const u=t-i*r+l,c=e-s*r+h,d=t+i*n+l,p=e+s*n+h;return a.push(u,c,d,p),2}function cy(t,e,i,s,r,n,o,a){const l=i-t,h=s-e;let u=Math.atan2(l,h),c=Math.atan2(r-t,n-e);a&&u<c?u+=2*Math.PI:!a&&u>c&&(c+=2*Math.PI);let d=u;const p=c-u,f=Math.abs(p),m=Math.sqrt(l*l+h*h),g=1+(15*f*Math.sqrt(m)/Math.PI|0),y=p/g;if(d+=y,a){o.push(t,e,i,s);for(let i=1,s=d;i<g;i++,s+=y)o.push(t,e,t+Math.sin(s)*m,e+Math.cos(s)*m);o.push(t,e,r,n)}else{o.push(i,s,t,e);for(let i=1,s=d;i<g;i++,s+=y)o.push(t+Math.sin(s)*m,e+Math.cos(s)*m,t,e);o.push(r,n,t,e)}return 2*g}function dy(t,e){t.lineStyle.native?function(t,e){let i=0;const s=t.shape,r=t.points||s.points,n=s.type!==mf.POLY||s.closeStroke;if(0===r.length)return;const o=e.points,a=e.indices,l=r.length/2,h=o.length/2;let u=h;for(o.push(r[0],r[1]),i=1;i<l;i++)o.push(r[2*i],r[2*i+1]),a.push(u,u+1),u++;n&&a.push(u,h)}(t,e):function(t,e){const i=t.shape;let s=t.points||i.points.slice();const r=e.closePointEps;if(0===s.length)return;const n=t.lineStyle,o=new gf(s[0],s[1]),a=new gf(s[s.length-2],s[s.length-1]),l=i.type!==mf.POLY||i.closeStroke,h=Math.abs(o.x-a.x)<r&&Math.abs(o.y-a.y)<r;if(l){s=s.slice(),h&&(s.pop(),s.pop(),a.set(s[s.length-2],s[s.length-1]));const t=.5*(o.x+a.x),e=.5*(a.y+o.y);s.unshift(t,e),s.push(t,e)}const u=e.points,c=s.length/2;let d=s.length;const p=u.length/2,f=n.width/2,m=f*f,g=n.miterLimit*n.miterLimit;let y=s[0],v=s[1],x=s[2],b=s[3],w=0,_=0,P=-(v-b),E=y-x,T=0,A=0,I=Math.sqrt(P*P+E*E);P/=I,E/=I,P*=f,E*=f;const S=n.alignment,C=2*(1-S),M=2*S;l||(n.cap===ny.ROUND?d+=cy(y-P*(C-M)*.5,v-E*(C-M)*.5,y-P*C,v-E*C,y+P*M,v+E*M,u,!0)+2:n.cap===ny.SQUARE&&(d+=uy(y,v,P,E,C,M,!0,u))),u.push(y-P*C,v-E*C,y+P*M,v+E*M);for(let L=1;L<c-1;++L){y=s[2*(L-1)],v=s[2*(L-1)+1],x=s[2*L],b=s[2*L+1],w=s[2*(L+1)],_=s[2*(L+1)+1],P=-(v-b),E=y-x,I=Math.sqrt(P*P+E*E),P/=I,E/=I,P*=f,E*=f,T=-(b-_),A=x-w,I=Math.sqrt(T*T+A*A),T/=I,A/=I,T*=f,A*=f;const t=x-y,e=v-b,i=x-w,r=_-b,o=t*i+e*r,a=e*i-r*t,l=a<0;if(Math.abs(a)<.001*Math.abs(o)){u.push(x-P*C,b-E*C,x+P*M,b+E*M),o>=0&&(n.join===ry.ROUND?d+=cy(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+4:d+=2,u.push(x-T*M,b-A*M,x+T*C,b+A*C));continue}const h=(-P+y)*(-E+b)-(-P+x)*(-E+v),c=(-T+w)*(-A+b)-(-T+x)*(-A+_),p=(t*c-i*h)/a,S=(r*h-e*c)/a,O=(p-x)*(p-x)+(S-b)*(S-b),N=x+(p-x)*C,R=b+(S-b)*C,B=x-(p-x)*M,k=b-(S-b)*M,F=l?C:M,D=O<=Math.min(t*t+e*e,i*i+r*r)+F*F*m;let U=n.join;if(U===ry.MITER&&O/m>g&&(U=ry.BEVEL),D)switch(U){case ry.MITER:u.push(N,R,B,k);break;case ry.BEVEL:l?u.push(N,R,x+P*M,b+E*M,N,R,x+T*M,b+A*M):u.push(x-P*C,b-E*C,B,k,x-T*C,b-A*C,B,k),d+=2;break;case ry.ROUND:l?(u.push(N,R,x+P*M,b+E*M),d+=cy(x,b,x+P*M,b+E*M,x+T*M,b+A*M,u,!0)+4,u.push(N,R,x+T*M,b+A*M)):(u.push(x-P*C,b-E*C,B,k),d+=cy(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+4,u.push(x-T*C,b-A*C,B,k))}else{switch(u.push(x-P*C,b-E*C,x+P*M,b+E*M),U){case ry.MITER:l?u.push(B,k,B,k):u.push(N,R,N,R),d+=2;break;case ry.ROUND:d+=l?cy(x,b,x+P*M,b+E*M,x+T*M,b+A*M,u,!0)+2:cy(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+2}u.push(x-T*C,b-A*C,x+T*M,b+A*M),d+=2}}y=s[2*(c-2)],v=s[2*(c-2)+1],x=s[2*(c-1)],b=s[2*(c-1)+1],P=-(v-b),E=y-x,I=Math.sqrt(P*P+E*E),P/=I,E/=I,P*=f,E*=f,u.push(x-P*C,b-E*C,x+P*M,b+E*M),l||(n.cap===ny.ROUND?d+=cy(x-P*(C-M)*.5,b-E*(C-M)*.5,x-P*C,b-E*C,x+P*M,b+E*M,u,!1)+2:n.cap===ny.SQUARE&&(d+=uy(x,b,P,E,C,M,!1,u)));const O=e.indices,N=oy.epsilon*oy.epsilon;for(let L=p;L<d+p-2;++L)y=u[2*L],v=u[2*L+1],x=u[2*(L+1)],b=u[2*(L+1)+1],w=u[2*(L+2)],_=u[2*(L+2)+1],!(Math.abs(y*(b-_)+x*(_-v)+w*(v-b))<N)&&O.push(L,L+1,L+2)}(t,e)}class py{static curveLength(t,e,i,s,r,n){const o=t-2*i+r,a=e-2*s+n,l=2*i-2*t,h=2*s-2*e,u=4*(o*o+a*a),c=4*(o*l+a*h),d=l*l+h*h,p=2*Math.sqrt(u+c+d),f=Math.sqrt(u),m=2*u*f,g=2*Math.sqrt(d),y=c/f;return(m*p+f*c*(p-g)+(4*d*u-c*c)*Math.log((2*f+y+p)/(y+g)))/(4*m)}static curveTo(t,e,i,s,r){const n=r[r.length-2],o=r[r.length-1],a=oy._segmentsCount(py.curveLength(n,o,t,e,i,s));let l=0,h=0;for(let u=1;u<=a;++u){const c=u/a;l=n+(t-n)*c,h=o+(e-o)*c,r.push(l+(t+(i-t)*c-l)*c,h+(e+(s-e)*c-h)*c)}}}const fy={[mf.POLY]:ey,[mf.CIRC]:Qg,[mf.ELIP]:Qg,[mf.RECT]:iy,[mf.RREC]:sy},my=[],gy=[];class yy{constructor(t,e=null,i=null,s=null){this.points=[],this.holes=[],this.shape=t,this.lineStyle=i,this.fillStyle=e,this.matrix=s,this.type=t.type}clone(){return new yy(this.shape,this.fillStyle,this.lineStyle,this.matrix)}destroy(){this.shape=null,this.holes.length=0,this.holes=null,this.points.length=0,this.points=null,this.lineStyle=null,this.fillStyle=null}}const vy=new gf,xy=class t extends cf{constructor(){super(),this.closePointEps=1e-4,this.boundsPadding=0,this.uvsFloat32=null,this.indicesUint16=null,this.batchable=!1,this.points=[],this.colors=[],this.uvs=[],this.indices=[],this.textureIds=[],this.graphicsData=[],this.drawCalls=[],this.batchDirty=-1,this.batches=[],this.dirty=0,this.cacheDirty=-1,this.clearDirty=0,this.shapeIndex=0,this._bounds=new Yg,this.boundsDirty=-1}get bounds(){return this.updateBatches(),this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.calculateBounds()),this._bounds}invalidate(){this.boundsDirty=-1,this.dirty++,this.batchDirty++,this.shapeIndex=0,this.points.length=0,this.colors.length=0,this.uvs.length=0,this.indices.length=0,this.textureIds.length=0;for(let t=0;t<this.drawCalls.length;t++)this.drawCalls[t].texArray.clear(),gy.push(this.drawCalls[t]);this.drawCalls.length=0;for(let t=0;t<this.batches.length;t++){const e=this.batches[t];e.reset(),my.push(e)}this.batches.length=0}clear(){return this.graphicsData.length>0&&(this.invalidate(),this.clearDirty++,this.graphicsData.length=0),this}drawShape(t,e=null,i=null,s=null){const r=new yy(t,e,i,s);return this.graphicsData.push(r),this.dirty++,this}drawHole(t,e=null){if(!this.graphicsData.length)return null;const i=new yy(t,null,null,e),s=this.graphicsData[this.graphicsData.length-1];return i.lineStyle=s.lineStyle,s.holes.push(i),this.dirty++,this}destroy(){super.destroy();for(let t=0;t<this.graphicsData.length;++t)this.graphicsData[t].destroy();this.points.length=0,this.points=null,this.colors.length=0,this.colors=null,this.uvs.length=0,this.uvs=null,this.indices.length=0,this.indices=null,this.indexBuffer.destroy(),this.indexBuffer=null,this.graphicsData.length=0,this.graphicsData=null,this.drawCalls.length=0,this.drawCalls=null,this.batches.length=0,this.batches=null,this._bounds=null}containsPoint(t){const e=this.graphicsData;for(let i=0;i<e.length;++i){const s=e[i];if(s.fillStyle.visible&&s.shape&&(s.matrix?s.matrix.applyInverse(t,vy):vy.copyFrom(t),s.shape.contains(vy.x,vy.y))){let t=!1;if(s.holes)for(let e=0;e<s.holes.length;e++)if(s.holes[e].shape.contains(vy.x,vy.y)){t=!0;break}if(!t)return!0}}return!1}updateBatches(){if(!this.graphicsData.length)return void(this.batchable=!0);if(!this.validateBatching())return;this.cacheDirty=this.dirty;const t=this.uvs,e=this.graphicsData;let i=null,s=null;this.batches.length>0&&(i=this.batches[this.batches.length-1],s=i.style);for(let a=this.shapeIndex;a<e.length;a++){this.shapeIndex++;const r=e[a],n=r.fillStyle,o=r.lineStyle;fy[r.type].build(r),r.matrix&&this.transformPoints(r.points,r.matrix),(n.visible||o.visible)&&this.processHoles(r.holes);for(let e=0;e<2;e++){const a=0===e?n:o;if(!a.visible)continue;const l=a.texture.baseTexture,h=this.indices.length,u=this.points.length/2;l.wrapMode=_h.REPEAT,0===e?this.processFill(r):this.processLine(r);const c=this.points.length/2-u;0!==c&&(i&&!this._compareStyles(s,a)&&(i.end(h,u),i=null),i||(i=my.pop()||new ly,i.begin(a,h,u),this.batches.push(i),s=a),this.addUvs(this.points,t,a.texture,u,c,a.matrix))}}const r=this.indices.length,n=this.points.length/2;if(i&&i.end(r,n),0===this.batches.length)return void(this.batchable=!0);const o=n>65535;this.indicesUint16&&this.indices.length===this.indicesUint16.length&&o===this.indicesUint16.BYTES_PER_ELEMENT>2?this.indicesUint16.set(this.indices):this.indicesUint16=o?new Uint32Array(this.indices):new Uint16Array(this.indices),this.batchable=this.isBatchable(),this.batchable?this.packBatches():this.buildDrawCalls()}_compareStyles(t,e){return!(!t||!e||t.texture.baseTexture!==e.texture.baseTexture||t.color+t.alpha!==e.color+e.alpha||!!t.native!=!!e.native)}validateBatching(){if(this.dirty===this.cacheDirty||!this.graphicsData.length)return!1;for(let t=0,e=this.graphicsData.length;t<e;t++){const e=this.graphicsData[t],i=e.fillStyle,s=e.lineStyle;if(i&&!i.texture.baseTexture.valid||s&&!s.texture.baseTexture.valid)return!1}return!0}packBatches(){this.batchDirty++,this.uvsFloat32=new Float32Array(this.uvs);const t=this.batches;for(let e=0,i=t.length;e<i;e++){const i=t[e];for(let t=0;t<i.size;t++){const e=i.start+t;this.indicesUint16[e]=this.indicesUint16[e]-i.attribStart}}}isBatchable(){if(this.points.length>131070)return!1;const e=this.batches;for(let t=0;t<e.length;t++)if(e[t].style.native)return!1;return this.points.length<2*t.BATCHABLE_SIZE}buildDrawCalls(){let t=++tf._globalBatch;for(let u=0;u<this.drawCalls.length;u++)this.drawCalls[u].texArray.clear(),gy.push(this.drawCalls[u]);this.drawCalls.length=0;const e=this.colors,i=this.textureIds;let s=gy.pop();s||(s=new ef,s.texArray=new am),s.texArray.count=0,s.start=0,s.size=0,s.type=gh.TRIANGLES;let r=0,n=null,o=0,a=!1,l=gh.TRIANGLES,h=0;this.drawCalls.push(s);for(let u=0;u<this.batches.length;u++){const c=this.batches[u],d=8,p=c.style,f=p.texture.baseTexture;a!==!!p.native&&(a=!!p.native,l=a?gh.LINES:gh.TRIANGLES,n=null,r=d,t++),n!==f&&(n=f,f._batchEnabled!==t&&(r===d&&(t++,r=0,s.size>0&&(s=gy.pop(),s||(s=new ef,s.texArray=new am),this.drawCalls.push(s)),s.start=h,s.size=0,s.texArray.count=0,s.type=l),f.touched=1,f._batchEnabled=t,f._batchLocation=r,f.wrapMode=_h.REPEAT,s.texArray.elements[s.texArray.count++]=f,r++)),s.size+=c.size,h+=c.size,o=f._batchLocation,this.addColors(e,p.color,p.alpha,c.attribSize,c.attribStart),this.addTextureIds(i,o,c.attribSize,c.attribStart)}tf._globalBatch=t,this.packAttributes()}packAttributes(){const t=this.points,e=this.uvs,i=this.colors,s=this.textureIds,r=new ArrayBuffer(3*t.length*4),n=new Float32Array(r),o=new Uint32Array(r);let a=0;for(let l=0;l<t.length/2;l++)n[a++]=t[2*l],n[a++]=t[2*l+1],n[a++]=e[2*l],n[a++]=e[2*l+1],o[a++]=i[l],n[a++]=s[l];this._buffer.update(r),this._indexBuffer.update(this.indicesUint16)}processFill(t){t.holes.length?ey.triangulate(t,this):fy[t.type].triangulate(t,this)}processLine(t){dy(t,this);for(let e=0;e<t.holes.length;e++)dy(t.holes[e],this)}processHoles(t){for(let e=0;e<t.length;e++){const i=t[e];fy[i.type].build(i),i.matrix&&this.transformPoints(i.points,i.matrix)}}calculateBounds(){const t=this._bounds;t.clear(),t.addVertexData(this.points,0,this.points.length),t.pad(this.boundsPadding,this.boundsPadding)}transformPoints(t,e){for(let i=0;i<t.length/2;i++){const s=t[2*i],r=t[2*i+1];t[2*i]=e.a*s+e.c*r+e.tx,t[2*i+1]=e.b*s+e.d*r+e.ty}}addColors(t,e,i,s,r=0){const n=pp.shared.setValue(e).toLittleEndianNumber(),o=pp.shared.setValue(n).toPremultiplied(i);t.length=Math.max(t.length,r+s);for(let a=0;a<s;a++)t[r+a]=o}addTextureIds(t,e,i,s=0){t.length=Math.max(t.length,s+i);for(let r=0;r<i;r++)t[s+r]=e}addUvs(t,e,i,s,r,n=null){let o=0;const a=e.length,l=i.frame;for(;o<r;){let i=t[2*(s+o)],r=t[2*(s+o)+1];if(n){const t=n.a*i+n.c*r+n.tx;r=n.b*i+n.d*r+n.ty,i=t}o++,e.push(i/l.width,r/l.height)}const h=i.baseTexture;(l.width<h.width||l.height<h.height)&&this.adjustUvs(e,i,a,r)}adjustUvs(t,e,i,s){const r=e.baseTexture,n=1e-6,o=i+2*s,a=e.frame,l=a.width/r.width,h=a.height/r.height;let u=a.x/a.width,c=a.y/a.height,d=Math.floor(t[i]+n),p=Math.floor(t[i+1]+n);for(let f=i+2;f<o;f+=2)d=Math.min(d,Math.floor(t[f]+n)),p=Math.min(p,Math.floor(t[f+1]+n));u-=d,c-=p;for(let f=i;f<o;f+=2)t[f]=(t[f]+u)*l,t[f+1]=(t[f+1]+c)*h}};xy.BATCHABLE_SIZE=100;let by=xy;class wy{constructor(){this.color=16777215,this.alpha=1,this.texture=Em.WHITE,this.matrix=null,this.visible=!1,this.reset()}clone(){const t=new wy;return t.color=this.color,t.alpha=this.alpha,t.texture=this.texture,t.matrix=this.matrix,t.visible=this.visible,t}reset(){this.color=16777215,this.alpha=1,this.texture=Em.WHITE,this.matrix=null,this.visible=!1}destroy(){this.texture=null,this.matrix=null}}class _y extends wy{constructor(){super(...arguments),this.width=0,this.alignment=.5,this.native=!1,this.cap=ny.BUTT,this.join=ry.MITER,this.miterLimit=10}clone(){const t=new _y;return t.color=this.color,t.alpha=this.alpha,t.texture=this.texture,t.matrix=this.matrix,t.visible=this.visible,t.width=this.width,t.alignment=this.alignment,t.native=this.native,t.cap=this.cap,t.join=this.join,t.miterLimit=this.miterLimit,t}reset(){super.reset(),this.color=0,this.alignment=.5,this.width=0,this.native=!1,this.cap=ny.BUTT,this.join=ry.MITER,this.miterLimit=10}}const Py={},Ey=class t extends qg{constructor(t=null){super(),this.shader=null,this.pluginName="batch",this.currentPath=null,this.batches=[],this.batchTint=-1,this.batchDirty=-1,this.vertexData=null,this._fillStyle=new wy,this._lineStyle=new _y,this._matrix=null,this._holeMode=!1,this.state=jp.for2d(),this._geometry=t||new by,this._geometry.refCount++,this._transformID=-1,this._tintColor=new pp(16777215),this.blendMode=mh.NORMAL}get geometry(){return this._geometry}clone(){return this.finishPoly(),new t(this._geometry)}set blendMode(t){this.state.blendMode=t}get blendMode(){return this.state.blendMode}get tint(){return this._tintColor.value}set tint(t){this._tintColor.setValue(t)}get fill(){return this._fillStyle}get line(){return this._lineStyle}lineStyle(t=null,e=0,i,s=.5,r=!1){return"number"==typeof t&&(t={width:t,color:e,alpha:i,alignment:s,native:r}),this.lineTextureStyle(t)}lineTextureStyle(t){const e={width:0,texture:Em.WHITE,color:t?.texture?16777215:0,matrix:null,alignment:.5,native:!1,cap:ny.BUTT,join:ry.MITER,miterLimit:10};t=Object.assign(e,t),this.normalizeColor(t),this.currentPath&&this.startPoly();const i=t.width>0&&t.alpha>0;return i?(t.matrix&&(t.matrix=t.matrix.clone(),t.matrix.invert()),Object.assign(this._lineStyle,{visible:i},t)):this._lineStyle.reset(),this}startPoly(){if(this.currentPath){const t=this.currentPath.points,e=this.currentPath.points.length;e>2&&(this.drawShape(this.currentPath),this.currentPath=new wf,this.currentPath.closeStroke=!1,this.currentPath.points.push(t[e-2],t[e-1]))}else this.currentPath=new wf,this.currentPath.closeStroke=!1}finishPoly(){this.currentPath&&(this.currentPath.points.length>2?(this.drawShape(this.currentPath),this.currentPath=null):this.currentPath.points.length=0)}moveTo(t,e){return this.startPoly(),this.currentPath.points[0]=t,this.currentPath.points[1]=e,this}lineTo(t,e){this.currentPath||this.moveTo(0,0);const i=this.currentPath.points,s=i[i.length-2],r=i[i.length-1];return(s!==t||r!==e)&&i.push(t,e),this}_initCurve(t=0,e=0){this.currentPath?0===this.currentPath.points.length&&(this.currentPath.points=[t,e]):this.moveTo(t,e)}quadraticCurveTo(t,e,i,s){this._initCurve();const r=this.currentPath.points;return 0===r.length&&this.moveTo(0,0),py.curveTo(t,e,i,s,r),this}bezierCurveTo(t,e,i,s,r,n){return this._initCurve(),hy.curveTo(t,e,i,s,r,n,this.currentPath.points),this}arcTo(t,e,i,s,r){this._initCurve(t,e);const n=this.currentPath.points,o=ay.curveTo(t,e,i,s,r,n);if(o){const{cx:t,cy:e,radius:i,startAngle:s,endAngle:r,anticlockwise:n}=o;this.arc(t,e,i,s,r,n)}return this}arc(t,e,i,s,r,n=!1){if(s===r)return this;if(!n&&r<=s?r+=df:n&&s<=r&&(s+=df),r-s===0)return this;const o=t+Math.cos(s)*i,a=e+Math.sin(s)*i,l=this._geometry.closePointEps;let h=this.currentPath?this.currentPath.points:null;if(h){const t=Math.abs(h[h.length-2]-o),e=Math.abs(h[h.length-1]-a);t<l&&e<l||h.push(o,a)}else this.moveTo(o,a),h=this.currentPath.points;return ay.arc(o,a,t,e,i,s,r,n,h),this}beginFill(t=0,e){return this.beginTextureFill({texture:Em.WHITE,color:t,alpha:e})}normalizeColor(t){const e=pp.shared.setValue(t.color??0);t.color=e.toNumber(),t.alpha??(t.alpha=e.alpha)}beginTextureFill(t){const e={texture:Em.WHITE,color:16777215,matrix:null};t=Object.assign(e,t),this.normalizeColor(t),this.currentPath&&this.startPoly();const i=t.alpha>0;return i?(t.matrix&&(t.matrix=t.matrix.clone(),t.matrix.invert()),Object.assign(this._fillStyle,{visible:i},t)):this._fillStyle.reset(),this}endFill(){return this.finishPoly(),this._fillStyle.reset(),this}drawRect(t,e,i,s){return this.drawShape(new vf(t,e,i,s))}drawRoundedRect(t,e,i,s,r){return this.drawShape(new _f(t,e,i,s,r))}drawCircle(t,e,i){return this.drawShape(new xf(t,e,i))}drawEllipse(t,e,i,s){return this.drawShape(new bf(t,e,i,s))}drawPolygon(...t){let e,i=!0;const s=t[0];s.points?(i=s.closeStroke,e=s.points):e=Array.isArray(t[0])?t[0]:t;const r=new wf(e);return r.closeStroke=i,this.drawShape(r),this}drawShape(t){return this._holeMode?this._geometry.drawHole(t,this._matrix):this._geometry.drawShape(t,this._fillStyle.clone(),this._lineStyle.clone(),this._matrix),this}clear(){return this._geometry.clear(),this._lineStyle.reset(),this._fillStyle.reset(),this._boundsID++,this._matrix=null,this._holeMode=!1,this.currentPath=null,this}isFastRect(){const t=this._geometry.graphicsData;return!(1!==t.length||t[0].shape.type!==mf.RECT||t[0].matrix||t[0].holes.length||t[0].lineStyle.visible&&t[0].lineStyle.width)}_render(t){this.finishPoly();const e=this._geometry;e.updateBatches(),e.batchable?(this.batchDirty!==e.batchDirty&&this._populateBatches(),this._renderBatched(t)):(t.batch.flush(),this._renderDirect(t))}_populateBatches(){const t=this._geometry,e=this.blendMode,i=t.batches.length;this.batchTint=-1,this._transformID=-1,this.batchDirty=t.batchDirty,this.batches.length=i,this.vertexData=new Float32Array(t.points);for(let s=0;s<i;s++){const i=t.batches[s],r=i.style.color,n=new Float32Array(this.vertexData.buffer,4*i.attribStart*2,2*i.attribSize),o=new Float32Array(t.uvsFloat32.buffer,4*i.attribStart*2,2*i.attribSize),a={vertexData:n,blendMode:e,indices:new Uint16Array(t.indicesUint16.buffer,2*i.start,i.size),uvs:o,_batchRGB:pp.shared.setValue(r).toRgbArray(),_tintRGB:r,_texture:i.style.texture,alpha:i.style.alpha,worldAlpha:1};this.batches[s]=a}}_renderBatched(t){if(this.batches.length){t.batch.setObjectRenderer(t.plugins[this.pluginName]),this.calculateVertices(),this.calculateTints();for(let e=0,i=this.batches.length;e<i;e++){const i=this.batches[e];i.worldAlpha=this.worldAlpha*i.alpha,t.plugins[this.pluginName].render(i)}}}_renderDirect(t){const e=this._resolveDirectShader(t),i=this._geometry,s=this.worldAlpha,r=e.uniforms,n=i.drawCalls;r.translationMatrix=this.transform.worldTransform,pp.shared.setValue(this._tintColor).premultiply(s).toArray(r.tint),t.shader.bind(e),t.geometry.bind(i,e),t.state.set(this.state);for(let o=0,a=n.length;o<a;o++)this._renderDrawCallDirect(t,i.drawCalls[o])}_renderDrawCallDirect(t,e){const{texArray:i,type:s,size:r,start:n}=e,o=i.count;for(let a=0;a<o;a++)t.texture.bind(i.elements[a],a);t.geometry.draw(s,r,n)}_resolveDirectShader(t){let e=this.shader;const i=this.pluginName;if(!e){if(!Py[i]){const{maxTextures:e}=t.plugins[i],s=new Int32Array(e);for(let t=0;t<e;t++)s[t]=t;const r={tint:new Float32Array([1,1,1,1]),translationMatrix:new Pf,default:rm.from({uSamplers:s},!0)},n=t.plugins[i]._shader.program;Py[i]=new nm(n,r)}e=Py[i]}return e}_calculateBounds(){this.finishPoly();const t=this._geometry;if(!t.graphicsData.length)return;const{minX:e,minY:i,maxX:s,maxY:r}=t.bounds;this._bounds.addFrame(this.transform,e,i,s,r)}containsPoint(e){return this.worldTransform.applyInverse(e,t._TEMP_POINT),this._geometry.containsPoint(t._TEMP_POINT)}calculateTints(){if(this.batchTint!==this.tint){this.batchTint=this._tintColor.toNumber();for(let t=0;t<this.batches.length;t++){const e=this.batches[t];e._tintRGB=pp.shared.setValue(this._tintColor).multiply(e._batchRGB).toLittleEndianNumber()}}}calculateVertices(){const t=this.transform._worldID;if(this._transformID===t)return;this._transformID=t;const e=this.transform.worldTransform,i=e.a,s=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty,l=this._geometry.points,h=this.vertexData;let u=0;for(let c=0;c<l.length;c+=2){const t=l[c],e=l[c+1];h[u++]=i*t+r*e+o,h[u++]=n*e+s*t+a}}closePath(){const t=this.currentPath;return t&&(t.closeStroke=!0,this.finishPoly()),this}setMatrix(t){return this._matrix=t,this}beginHole(){return this.finishPoly(),this._holeMode=!0,this}endHole(){return this.finishPoly(),this._holeMode=!1,this}destroy(t){this._geometry.refCount--,0===this._geometry.refCount&&this._geometry.dispose(),this._matrix=null,this.currentPath=null,this._lineStyle.destroy(),this._lineStyle=null,this._fillStyle.destroy(),this._fillStyle=null,this._geometry=null,this.shader=null,this.vertexData=null,this.batches.length=0,this.batches=null,super.destroy(t)}};Ey.curves=oy,Ey._TEMP_POINT=new gf;let Ty=Ey;var Ay=/* @__PURE__ */(t=>(t[t.LINEAR_VERTICAL=0]="LINEAR_VERTICAL",t[t.LINEAR_HORIZONTAL=1]="LINEAR_HORIZONTAL",t))(Ay||{});const Iy={willReadFrequently:!0},Sy=class t{static get experimentalLetterSpacingSupported(){let e=t._experimentalLetterSpacingSupported;if(void 0!==e){const i=Oh.ADAPTER.getCanvasRenderingContext2D().prototype;e=t._experimentalLetterSpacingSupported="letterSpacing"in i||"textLetterSpacing"in i}return e}constructor(t,e,i,s,r,n,o,a,l){this.text=t,this.style=e,this.width=i,this.height=s,this.lines=r,this.lineWidths=n,this.lineHeight=o,this.maxLineWidth=a,this.fontProperties=l}static measureText(e,i,s,r=t._canvas){s=s??i.wordWrap;const n=i.toFontString(),o=t.measureFont(n);0===o.fontSize&&(o.fontSize=i.fontSize,o.ascent=i.fontSize);const a=r.getContext("2d",Iy);a.font=n;const l=(s?t.wordWrap(e,i,r):e).split(/(?:\r\n|\r|\n)/),h=new Array(l.length);let u=0;for(let f=0;f<l.length;f++){const e=t._measureText(l[f],i.letterSpacing,a);h[f]=e,u=Math.max(u,e)}let c=u+i.strokeThickness;i.dropShadow&&(c+=i.dropShadowDistance);const d=i.lineHeight||o.fontSize+i.strokeThickness;let p=Math.max(d,o.fontSize+2*i.strokeThickness)+i.leading+(l.length-1)*(d+i.leading);return i.dropShadow&&(p+=i.dropShadowDistance),new t(e,i,c,p,l,h,d+i.leading,u,o)}static _measureText(e,i,s){let r=!1;t.experimentalLetterSpacingSupported&&(t.experimentalLetterSpacing?(s.letterSpacing=`${i}px`,s.textLetterSpacing=`${i}px`,r=!0):(s.letterSpacing="0px",s.textLetterSpacing="0px"));let n=s.measureText(e).width;return n>0&&(r?n-=i:n+=(t.graphemeSegmenter(e).length-1)*i),n}static wordWrap(e,i,s=t._canvas){const r=s.getContext("2d",Iy);let n=0,o="",a="";const l=/* @__PURE__ */Object.create(null),{letterSpacing:h,whiteSpace:u}=i,c=t.collapseSpaces(u),d=t.collapseNewlines(u);let p=!c;const f=i.wordWrapWidth+h,m=t.tokenize(e);for(let g=0;g<m.length;g++){let e=m[g];if(t.isNewline(e)){if(!d){a+=t.addLine(o),p=!c,o="",n=0;continue}e=" "}if(c){const i=t.isBreakingSpace(e),s=t.isBreakingSpace(o[o.length-1]);if(i&&s)continue}const s=t.getFromCache(e,h,l,r);if(s>f)if(""!==o&&(a+=t.addLine(o),o="",n=0),t.canBreakWords(e,i.breakWords)){const s=t.wordWrapSplit(e);for(let u=0;u<s.length;u++){let c=s[u],d=c,m=1;for(;s[u+m];){const r=s[u+m];if(t.canBreakChars(d,r,e,u,i.breakWords))break;c+=r,d=r,m++}u+=m-1;const g=t.getFromCache(c,h,l,r);g+n>f&&(a+=t.addLine(o),p=!1,o="",n=0),o+=c,n+=g}}else{o.length>0&&(a+=t.addLine(o),o="",n=0);const i=g===m.length-1;a+=t.addLine(e,!i),p=!1,o="",n=0}else s+n>f&&(p=!1,a+=t.addLine(o),o="",n=0),(o.length>0||!t.isBreakingSpace(e)||p)&&(o+=e,n+=s)}return a+=t.addLine(o,!1),a}static addLine(e,i=!0){return e=t.trimRight(e),e=i?`${e}\n`:e}static getFromCache(e,i,s,r){let n=s[e];return"number"!=typeof n&&(n=t._measureText(e,i,r)+i,s[e]=n),n}static collapseSpaces(t){return"normal"===t||"pre-line"===t}static collapseNewlines(t){return"normal"===t}static trimRight(e){if("string"!=typeof e)return"";for(let i=e.length-1;i>=0;i--){const s=e[i];if(!t.isBreakingSpace(s))break;e=e.slice(0,-1)}return e}static isNewline(e){return"string"==typeof e&&t._newlines.includes(e.charCodeAt(0))}static isBreakingSpace(e,i){return"string"==typeof e&&t._breakingSpaces.includes(e.charCodeAt(0))}static tokenize(e){const i=[];let s="";if("string"!=typeof e)return i;for(let r=0;r<e.length;r++){const n=e[r],o=e[r+1];t.isBreakingSpace(n,o)||t.isNewline(n)?(""!==s&&(i.push(s),s=""),i.push(n)):s+=n}return""!==s&&i.push(s),i}static canBreakWords(t,e){return e}static canBreakChars(t,e,i,s,r){return!0}static wordWrapSplit(e){return t.graphemeSegmenter(e)}static measureFont(e){if(t._fonts[e])return t._fonts[e];const i={ascent:0,descent:0,fontSize:0},s=t._canvas,r=t._context;r.font=e;const n=t.METRICS_STRING+t.BASELINE_SYMBOL,o=Math.ceil(r.measureText(n).width);let a=Math.ceil(r.measureText(t.BASELINE_SYMBOL).width);const l=Math.ceil(t.HEIGHT_MULTIPLIER*a);if(a=a*t.BASELINE_MULTIPLIER|0,0===o||0===l)return t._fonts[e]=i,i;s.width=o,s.height=l,r.fillStyle="#f00",r.fillRect(0,0,o,l),r.font=e,r.textBaseline="alphabetic",r.fillStyle="#000",r.fillText(n,0,a);const h=r.getImageData(0,0,o,l).data,u=h.length,c=4*o;let d=0,p=0,f=!1;for(d=0;d<a;++d){for(let t=0;t<c;t+=4)if(255!==h[p+t]){f=!0;break}if(f)break;p+=c}for(i.ascent=a-d,p=u-c,f=!1,d=l;d>a;--d){for(let t=0;t<c;t+=4)if(255!==h[p+t]){f=!0;break}if(f)break;p-=c}return i.descent=d-a,i.fontSize=i.ascent+i.descent,t._fonts[e]=i,i}static clearMetrics(e=""){e?delete t._fonts[e]:t._fonts={}}static get _canvas(){if(!t.__canvas){let e;try{const i=new OffscreenCanvas(0,0);if(i.getContext("2d",Iy)?.measureText)return t.__canvas=i,i;e=Oh.ADAPTER.createCanvas()}catch{e=Oh.ADAPTER.createCanvas()}e.width=e.height=10,t.__canvas=e}return t.__canvas}static get _context(){return t.__context||(t.__context=t._canvas.getContext("2d",Iy)),t.__context}};Sy.METRICS_STRING="|ÉqÅ",Sy.BASELINE_SYMBOL="M",Sy.BASELINE_MULTIPLIER=1.4,Sy.HEIGHT_MULTIPLIER=2,Sy.graphemeSegmenter=(()=>{if("function"==typeof Intl?.Segmenter){const t=new Intl.Segmenter;return e=>[...t.segment(e)].map(t=>t.segment)}return t=>[...t]})(),Sy.experimentalLetterSpacing=!1,Sy._fonts={},Sy._newlines=[10,13],Sy._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288];let Cy=Sy;const My=["serif","sans-serif","monospace","cursive","fantasy","system-ui"],Oy=class t{constructor(t){this.styleID=0,this.reset(),Ry(this,t,t)}clone(){const e={};return Ry(e,this,t.defaultStyle),new t(e)}reset(){Ry(this,t.defaultStyle,t.defaultStyle)}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this.styleID++)}get breakWords(){return this._breakWords}set breakWords(t){this._breakWords!==t&&(this._breakWords=t,this.styleID++)}get dropShadow(){return this._dropShadow}set dropShadow(t){this._dropShadow!==t&&(this._dropShadow=t,this.styleID++)}get dropShadowAlpha(){return this._dropShadowAlpha}set dropShadowAlpha(t){this._dropShadowAlpha!==t&&(this._dropShadowAlpha=t,this.styleID++)}get dropShadowAngle(){return this._dropShadowAngle}set dropShadowAngle(t){this._dropShadowAngle!==t&&(this._dropShadowAngle=t,this.styleID++)}get dropShadowBlur(){return this._dropShadowBlur}set dropShadowBlur(t){this._dropShadowBlur!==t&&(this._dropShadowBlur=t,this.styleID++)}get dropShadowColor(){return this._dropShadowColor}set dropShadowColor(t){const e=Ly(t);this._dropShadowColor!==e&&(this._dropShadowColor=e,this.styleID++)}get dropShadowDistance(){return this._dropShadowDistance}set dropShadowDistance(t){this._dropShadowDistance!==t&&(this._dropShadowDistance=t,this.styleID++)}get fill(){return this._fill}set fill(t){const e=Ly(t);this._fill!==e&&(this._fill=e,this.styleID++)}get fillGradientType(){return this._fillGradientType}set fillGradientType(t){this._fillGradientType!==t&&(this._fillGradientType=t,this.styleID++)}get fillGradientStops(){return this._fillGradientStops}set fillGradientStops(t){(function(t,e){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;++i)if(t[i]!==e[i])return!1;return!0})(this._fillGradientStops,t)||(this._fillGradientStops=t,this.styleID++)}get fontFamily(){return this._fontFamily}set fontFamily(t){this.fontFamily!==t&&(this._fontFamily=t,this.styleID++)}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(this._fontSize=t,this.styleID++)}get fontStyle(){return this._fontStyle}set fontStyle(t){this._fontStyle!==t&&(this._fontStyle=t,this.styleID++)}get fontVariant(){return this._fontVariant}set fontVariant(t){this._fontVariant!==t&&(this._fontVariant=t,this.styleID++)}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.styleID++)}get letterSpacing(){return this._letterSpacing}set letterSpacing(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.styleID++)}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this.styleID++)}get leading(){return this._leading}set leading(t){this._leading!==t&&(this._leading=t,this.styleID++)}get lineJoin(){return this._lineJoin}set lineJoin(t){this._lineJoin!==t&&(this._lineJoin=t,this.styleID++)}get miterLimit(){return this._miterLimit}set miterLimit(t){this._miterLimit!==t&&(this._miterLimit=t,this.styleID++)}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this.styleID++)}get stroke(){return this._stroke}set stroke(t){const e=Ly(t);this._stroke!==e&&(this._stroke=e,this.styleID++)}get strokeThickness(){return this._strokeThickness}set strokeThickness(t){this._strokeThickness!==t&&(this._strokeThickness=t,this.styleID++)}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline!==t&&(this._textBaseline=t,this.styleID++)}get trim(){return this._trim}set trim(t){this._trim!==t&&(this._trim=t,this.styleID++)}get whiteSpace(){return this._whiteSpace}set whiteSpace(t){this._whiteSpace!==t&&(this._whiteSpace=t,this.styleID++)}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this.styleID++)}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.styleID++)}toFontString(){const t="number"==typeof this.fontSize?`${this.fontSize}px`:this.fontSize;let e=this.fontFamily;Array.isArray(this.fontFamily)||(e=this.fontFamily.split(","));for(let i=e.length-1;i>=0;i--){let t=e[i].trim();!/([\"\'])[^\'\"]+\1/.test(t)&&!My.includes(t)&&(t=`"${t}"`),e[i]=t}return`${this.fontStyle} ${this.fontVariant} ${this.fontWeight} ${t} ${e.join(",")}`}};Oy.defaultStyle={align:"left",breakWords:!1,dropShadow:!1,dropShadowAlpha:1,dropShadowAngle:Math.PI/6,dropShadowBlur:0,dropShadowColor:"black",dropShadowDistance:5,fill:"black",fillGradientType:Ay.LINEAR_VERTICAL,fillGradientStops:[],fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,lineJoin:"miter",miterLimit:10,padding:0,stroke:"black",strokeThickness:0,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let Ny=Oy;function Ly(t){const e=pp.shared,i=t=>{const i=e.setValue(t);return 1===i.alpha?i.toHex():i.toRgbaString()};return Array.isArray(t)?t.map(i):i(t)}function Ry(t,e,i){for(const s in i)Array.isArray(e[s])?t[s]=e[s].slice():t[s]=e[s]}const By={texture:!0,children:!1,baseTexture:!0},ky=class t extends Zg{constructor(e,i,s){let r=!1;s||(s=Oh.ADAPTER.createCanvas(),r=!0),s.width=3,s.height=3;const n=Em.from(s);n.orig=new vf,n.trim=new vf,super(n),this._ownCanvas=r,this.canvas=s,this.context=s.getContext("2d",{willReadFrequently:!0}),this._resolution=t.defaultResolution??Oh.RESOLUTION,this._autoResolution=t.defaultAutoResolution,this._text=null,this._style=null,this._styleListener=null,this._font="",this.text=e,this.style=i,this.localStyleID=-1}static get experimentalLetterSpacing(){return Cy.experimentalLetterSpacing}static set experimentalLetterSpacing(t){Md("7.1.0","Text.experimentalLetterSpacing is deprecated, use TextMetrics.experimentalLetterSpacing"),Cy.experimentalLetterSpacing=t}updateText(t){const e=this._style;if(this.localStyleID!==e.styleID&&(this.dirty=!0,this.localStyleID=e.styleID),!this.dirty&&t)return;this._font=this._style.toFontString();const i=this.context,s=Cy.measureText(this._text||" ",this._style,this._style.wordWrap,this.canvas),r=s.width,n=s.height,o=s.lines,a=s.lineHeight,l=s.lineWidths,h=s.maxLineWidth,u=s.fontProperties;let c,d;this.canvas.width=Math.ceil(Math.ceil(Math.max(1,r)+2*e.padding)*this._resolution),this.canvas.height=Math.ceil(Math.ceil(Math.max(1,n)+2*e.padding)*this._resolution),i.scale(this._resolution,this._resolution),i.clearRect(0,0,this.canvas.width,this.canvas.height),i.font=this._font,i.lineWidth=e.strokeThickness,i.textBaseline=e.textBaseline,i.lineJoin=e.lineJoin,i.miterLimit=e.miterLimit;const p=e.dropShadow?2:1;for(let f=0;f<p;++f){const t=e.dropShadow&&0===f,r=t?Math.ceil(Math.max(1,n)+2*e.padding):0,p=r*this._resolution;if(t){i.fillStyle="black",i.strokeStyle="black";const t=e.dropShadowColor,s=e.dropShadowBlur*this._resolution,r=e.dropShadowDistance*this._resolution;i.shadowColor=pp.shared.setValue(t).setAlpha(e.dropShadowAlpha).toRgbaString(),i.shadowBlur=s,i.shadowOffsetX=Math.cos(e.dropShadowAngle)*r,i.shadowOffsetY=Math.sin(e.dropShadowAngle)*r+p}else i.fillStyle=this._generateFillStyle(e,o,s),i.strokeStyle=e.stroke,i.shadowColor="black",i.shadowBlur=0,i.shadowOffsetX=0,i.shadowOffsetY=0;let m=(a-u.fontSize)/2;a-u.fontSize<0&&(m=0);for(let i=0;i<o.length;i++)c=e.strokeThickness/2,d=e.strokeThickness/2+i*a+u.ascent+m,"right"===e.align?c+=h-l[i]:"center"===e.align&&(c+=(h-l[i])/2),e.stroke&&e.strokeThickness&&this.drawLetterSpacing(o[i],c+e.padding,d+e.padding-r,!0),e.fill&&this.drawLetterSpacing(o[i],c+e.padding,d+e.padding-r)}this.updateTexture()}drawLetterSpacing(t,e,i,s=!1){const r=this._style.letterSpacing;let n=!1;if(Cy.experimentalLetterSpacingSupported&&(Cy.experimentalLetterSpacing?(this.context.letterSpacing=`${r}px`,this.context.textLetterSpacing=`${r}px`,n=!0):(this.context.letterSpacing="0px",this.context.textLetterSpacing="0px")),0===r||n)return void(s?this.context.strokeText(t,e,i):this.context.fillText(t,e,i));let o=e;const a=Cy.graphemeSegmenter(t);let l=this.context.measureText(t).width,h=0;for(let u=0;u<a.length;++u){const t=a[u];s?this.context.strokeText(t,o,i):this.context.fillText(t,o,i);let e="";for(let i=u+1;i<a.length;++i)e+=a[i];h=this.context.measureText(e).width,o+=l-h+r,l=h}}updateTexture(){const t=this.canvas;if(this._style.trim){const e=Bp(t);e.data&&(t.width=e.width,t.height=e.height,this.context.putImageData(e.data,0,0))}const e=this._texture,i=this._style,s=i.trim?0:i.padding,r=e.baseTexture;e.trim.width=e._frame.width=t.width/this._resolution,e.trim.height=e._frame.height=t.height/this._resolution,e.trim.x=-s,e.trim.y=-s,e.orig.width=e._frame.width-2*s,e.orig.height=e._frame.height-2*s,this._onTextureUpdate(),r.setRealSize(t.width,t.height,this._resolution),e.updateUvs(),this.dirty=!1}_render(t){this._autoResolution&&this._resolution!==t.resolution&&(this._resolution=t.resolution,this.dirty=!0),this.updateText(!0),super._render(t)}updateTransform(){this.updateText(!0),super.updateTransform()}getBounds(t,e){return this.updateText(!0),-1===this._textureID&&(t=!1),super.getBounds(t,e)}getLocalBounds(t){return this.updateText(!0),super.getLocalBounds.call(this,t)}_calculateBounds(){this.calculateVertices(),this._bounds.addQuad(this.vertexData)}_generateFillStyle(t,e,i){const s=t.fill;if(!Array.isArray(s))return s;if(1===s.length)return s[0];let r;const n=t.dropShadow?t.dropShadowDistance:0,o=t.padding||0,a=this.canvas.width/this._resolution-n-2*o,l=this.canvas.height/this._resolution-n-2*o,h=s.slice(),u=t.fillGradientStops.slice();if(!u.length){const t=h.length+1;for(let e=1;e<t;++e)u.push(e/t)}if(h.unshift(s[0]),u.unshift(0),h.push(s[s.length-1]),u.push(1),t.fillGradientType===Ay.LINEAR_VERTICAL){r=this.context.createLinearGradient(a/2,o,a/2,l+o);const s=i.fontProperties.fontSize+t.strokeThickness;for(let t=0;t<e.length;t++){const n=i.lineHeight*(t-1)+s,o=i.lineHeight*t;let a=o;t>0&&n>o&&(a=(o+n)/2);const c=o+s,d=i.lineHeight*(t+1);let p=c;t+1<e.length&&d<c&&(p=(c+d)/2);const f=(p-a)/l;for(let t=0;t<h.length;t++){let e=0;e="number"==typeof u[t]?u[t]:t/h.length;let i=Math.min(1,Math.max(0,a/l+e*f));i=Number(i.toFixed(5)),r.addColorStop(i,h[t])}}}else{r=this.context.createLinearGradient(o,l/2,a+o,l/2);const t=h.length+1;let e=1;for(let i=0;i<h.length;i++){let s;s="number"==typeof u[i]?u[i]:e/t,r.addColorStop(s,h[i]),e++}}return r}destroy(t){"boolean"==typeof t&&(t={children:t}),t=Object.assign({},By,t),super.destroy(t),this._ownCanvas&&(this.canvas.height=this.canvas.width=0),this.context=null,this.canvas=null,this._style=null}get width(){return this.updateText(!0),Math.abs(this.scale.x)*this._texture.orig.width}set width(t){this.updateText(!0);const e=_p(this.scale.x)||1;this.scale.x=e*t/this._texture.orig.width,this._width=t}get height(){return this.updateText(!0),Math.abs(this.scale.y)*this._texture.orig.height}set height(t){this.updateText(!0);const e=_p(this.scale.y)||1;this.scale.y=e*t/this._texture.orig.height,this._height=t}get style(){return this._style}set style(t){t=t||{},this._style=t instanceof Ny?t:new Ny(t),this.localStyleID=-1,this.dirty=!0}get text(){return this._text}set text(t){t=String(t??""),this._text!==t&&(this._text=t,this.dirty=!0)}get resolution(){return this._resolution}set resolution(t){this._autoResolution=!1,this._resolution!==t&&(this._resolution=t,this.dirty=!0)}};ky.defaultAutoResolution=!0;let Fy=ky;class Dy extends dm{constructor(){super("attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n",{m:new Float32Array([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]),uAlpha:1}),this.alpha=1}_loadMatrix(t,e=!1){let i=t;e&&(this._multiply(i,this.uniforms.m,t),i=this._colorMatrix(i)),this.uniforms.m=i}_multiply(t,e,i){return t[0]=e[0]*i[0]+e[1]*i[5]+e[2]*i[10]+e[3]*i[15],t[1]=e[0]*i[1]+e[1]*i[6]+e[2]*i[11]+e[3]*i[16],t[2]=e[0]*i[2]+e[1]*i[7]+e[2]*i[12]+e[3]*i[17],t[3]=e[0]*i[3]+e[1]*i[8]+e[2]*i[13]+e[3]*i[18],t[4]=e[0]*i[4]+e[1]*i[9]+e[2]*i[14]+e[3]*i[19]+e[4],t[5]=e[5]*i[0]+e[6]*i[5]+e[7]*i[10]+e[8]*i[15],t[6]=e[5]*i[1]+e[6]*i[6]+e[7]*i[11]+e[8]*i[16],t[7]=e[5]*i[2]+e[6]*i[7]+e[7]*i[12]+e[8]*i[17],t[8]=e[5]*i[3]+e[6]*i[8]+e[7]*i[13]+e[8]*i[18],t[9]=e[5]*i[4]+e[6]*i[9]+e[7]*i[14]+e[8]*i[19]+e[9],t[10]=e[10]*i[0]+e[11]*i[5]+e[12]*i[10]+e[13]*i[15],t[11]=e[10]*i[1]+e[11]*i[6]+e[12]*i[11]+e[13]*i[16],t[12]=e[10]*i[2]+e[11]*i[7]+e[12]*i[12]+e[13]*i[17],t[13]=e[10]*i[3]+e[11]*i[8]+e[12]*i[13]+e[13]*i[18],t[14]=e[10]*i[4]+e[11]*i[9]+e[12]*i[14]+e[13]*i[19]+e[14],t[15]=e[15]*i[0]+e[16]*i[5]+e[17]*i[10]+e[18]*i[15],t[16]=e[15]*i[1]+e[16]*i[6]+e[17]*i[11]+e[18]*i[16],t[17]=e[15]*i[2]+e[16]*i[7]+e[17]*i[12]+e[18]*i[17],t[18]=e[15]*i[3]+e[16]*i[8]+e[17]*i[13]+e[18]*i[18],t[19]=e[15]*i[4]+e[16]*i[9]+e[17]*i[14]+e[18]*i[19]+e[19],t}_colorMatrix(t){const e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e}brightness(t,e){const i=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}tint(t,e){const[i,s,r]=pp.shared.setValue(t).toArray(),n=[i,0,0,0,0,0,s,0,0,0,0,0,r,0,0,0,0,0,1,0];this._loadMatrix(n,e)}greyscale(t,e){const i=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}blackAndWhite(t){this._loadMatrix([.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0],t)}hue(t,e){t=(t||0)/180*Math.PI;const i=Math.cos(t),s=Math.sin(t),r=1/3,n=(0,Math.sqrt)(r),o=[i+(1-i)*r,r*(1-i)-n*s,r*(1-i)+n*s,0,0,r*(1-i)+n*s,i+r*(1-i),r*(1-i)-n*s,0,0,r*(1-i)-n*s,r*(1-i)+n*s,i+r*(1-i),0,0,0,0,0,1,0];this._loadMatrix(o,e)}contrast(t,e){const i=(t||0)+1,s=-.5*(i-1),r=[i,0,0,0,s,0,i,0,0,s,0,0,i,0,s,0,0,0,1,0];this._loadMatrix(r,e)}saturate(t=0,e){const i=2*t/3+1,s=-.5*(i-1),r=[i,s,s,0,0,s,i,s,0,0,s,s,i,0,0,0,0,0,1,0];this._loadMatrix(r,e)}desaturate(){this.saturate(-1)}negative(t){this._loadMatrix([-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0],t)}sepia(t){this._loadMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0],t)}technicolor(t){this._loadMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0],t)}polaroid(t){this._loadMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],t)}toBGR(t){this._loadMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0],t)}kodachrome(t){this._loadMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0],t)}browni(t){this._loadMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0],t)}vintage(t){this._loadMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0],t)}colorTone(t,e,i,s,r){t=t||.2,e=e||.15,i=i||16770432,s=s||3375104;const n=pp.shared,[o,a,l]=n.setValue(i).toArray(),[h,u,c]=n.setValue(s).toArray(),d=[.3,.59,.11,0,0,o,a,l,t,0,h,u,c,e,0,o-h,a-u,l-c,0,0];this._loadMatrix(d,r)}night(t,e){const i=[-2*(t=t||.1),-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}predator(t,e){const i=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(i,e)}lsd(t){this._loadMatrix([2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0],t)}reset(){this._loadMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],!1)}get matrix(){return this.uniforms.m}set matrix(t){this.uniforms.m=t}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}}Dy.prototype.grayscale=Dy.prototype.greyscale;var Uy,Gy={exports:{}},Xy=Gy.exports;var Wy=(Uy||(Uy=1,function(t){(function(){var e,i;i=e={linear:function(t,e,i,s){return i*t/s+e},easeInQuad:function(t,e,i,s){return i*(t/=s)*t+e},easeOutQuad:function(t,e,i,s){return-i*(t/=s)*(t-2)+e},easeInOutQuad:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,s){return i*(t/=s)*t*t+e},easeOutCubic:function(t,e,i,s){return i*((t=t/s-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,s){return i*(t/=s)*t*t*t+e},easeOutQuart:function(t,e,i,s){return-i*((t=t/s-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,s){return i*(t/=s)*t*t*t*t+e},easeOutQuint:function(t,e,i,s){return i*((t=t/s-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,s){return-i*Math.cos(t/s*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,s){return i*Math.sin(t/s*(Math.PI/2))+e},easeInOutSine:function(t,e,i,s){return-i/2*(Math.cos(Math.PI*t/s)-1)+e},easeInExpo:function(t,e,i,s){return 0===t?e:i*Math.pow(2,10*(t/s-1))+e},easeOutExpo:function(t,e,i,s){return t===s?e+i:i*(1-Math.pow(2,-10*t/s))+e},easeInOutExpo:function(t,e,i,s){return(t/=s/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,s){return-i*(Math.sqrt(1-(t/=s)*t)-1)+e},easeOutCirc:function(t,e,i,s){return i*Math.sqrt(1-(t=t/s-1)*t)+e},easeInOutCirc:function(t,e,i,s){return(t/=s/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),-r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)+e},easeOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),r*Math.pow(2,-10*t)*Math.sin((t*s-o)*(2*Math.PI)/n)+i+e},easeInOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s/2),(n=0)||(n=s*(.3*1.5)),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),t<1?r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*-.5+e:r*Math.pow(2,-10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*.5+i+e},easeInBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*(t/=s)*t*((r+1)*t-r)+e},easeOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*((t=t/s-1)*t*((r+1)*t+r)+1)+e},easeInOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),(t/=s/2)<1?i/2*(t*t*((1+(r*=1.525))*t-r))+e:i/2*((t-=2)*t*((1+(r*=1.525))*t+r)+2)+e},easeInBounce:function(t,i,s,r){return s-e.easeOutBounce(r-t,0,s,r)+i},easeOutBounce:function(t,e,i,s){return(t/=s)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e},easeInOutBounce:function(t,i,s,r){return t<r/2?.5*e.easeInBounce(2*t,0,s,r)+i:.5*e.easeOutBounce(2*t-r,0,s,r)+.5*s+i}},t.exports=i}).call(Xy)}(Gy)),Gy.exports);const Yy=/* @__PURE__ */It(Wy);qg.prototype._renderCanvas=function(t){},qg.prototype.renderCanvas=function(t){if(this.visible&&!(this.worldAlpha<=0)&&this.renderable){this._mask&&t.mask.pushMask(this._mask),this._renderCanvas(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].renderCanvas(t);this._mask&&t.mask.popMask(t)}},Hg.prototype.renderCanvas=function(t){},Fy.prototype._renderCanvas=function(t){this._autoResolution&&this._resolution!==t.resolution&&(this._resolution=t.resolution,this.dirty=!0),this.updateText(!0),Zg.prototype._renderCanvas.call(this,t)},Hg.prototype.name=null,qg.prototype.getChildByName=function(t,e){for(let i=0,s=this.children.length;i<s;i++)if(this.children[i].name===t)return this.children[i];if(e)for(let i=0,s=this.children.length;i<s;i++){const e=this.children[i];if(!e.getChildByName)continue;const s=e.getChildByName(t,!0);if(s)return s}return null};const Hy={vec3(t,e,i,s){(i[0]!==s[0]||i[1]!==s[1]||i[2]!==s[2])&&(i[0]=s[0],i[1]=s[1],i[2]=s[2],t.uniform3f(e,s[0],s[1],s[2]))},int(t,e,i,s){t.uniform1i(e,s)},ivec2(t,e,i,s){t.uniform2i(e,s[0],s[1])},ivec3(t,e,i,s){t.uniform3i(e,s[0],s[1],s[2])},ivec4(t,e,i,s){t.uniform4i(e,s[0],s[1],s[2],s[3])},uint(t,e,i,s){t.uniform1ui(e,s)},uvec2(t,e,i,s){t.uniform2ui(e,s[0],s[1])},uvec3(t,e,i,s){t.uniform3ui(e,s[0],s[1],s[2])},uvec4(t,e,i,s){t.uniform4ui(e,s[0],s[1],s[2],s[3])},bvec2(t,e,i,s){t.uniform2i(e,s[0],s[1])},bvec3(t,e,i,s){t.uniform3i(e,s[0],s[1],s[2])},bvec4(t,e,i,s){t.uniform4i(e,s[0],s[1],s[2],s[3])},mat2(t,e,i,s){t.uniformMatrix2fv(e,!1,s)},mat4(t,e,i,s){t.uniformMatrix4fv(e,!1,s)}},$y={float(t,e,i,s){t.uniform1fv(e,s)},vec2(t,e,i,s){t.uniform2fv(e,s)},vec3(t,e,i,s){t.uniform3fv(e,s)},vec4(t,e,i,s){t.uniform4fv(e,s)},int(t,e,i,s){t.uniform1iv(e,s)},ivec2(t,e,i,s){t.uniform2iv(e,s)},ivec3(t,e,i,s){t.uniform3iv(e,s)},ivec4(t,e,i,s){t.uniform4iv(e,s)},uint(t,e,i,s){t.uniform1uiv(e,s)},uvec2(t,e,i,s){t.uniform2uiv(e,s)},uvec3(t,e,i,s){t.uniform3uiv(e,s)},uvec4(t,e,i,s){t.uniform4uiv(e,s)},bool(t,e,i,s){t.uniform1iv(e,s)},bvec2(t,e,i,s){t.uniform2iv(e,s)},bvec3(t,e,i,s){t.uniform3iv(e,s)},bvec4(t,e,i,s){t.uniform4iv(e,s)},sampler2D(t,e,i,s){t.uniform1iv(e,s)},samplerCube(t,e,i,s){t.uniform1iv(e,s)},sampler2DArray(t,e,i,s){t.uniform1iv(e,s)}};Object.assign(cg.prototype,{systemCheck(){},syncUniforms(t,e){const{shader:i,renderer:s}=this;!function(t,e,i,s,r){let n=0,o=null,a=null;const l=r.gl;for(const h in t.uniforms){const u=e[h],c=s[h],d=i[h],p=t.uniforms[h];u?"float"!==u.type||1!==u.size||u.isArray?"bool"!==u.type||1!==u.size||u.isArray?"sampler2D"!==u.type&&"samplerCube"!==u.type&&"sampler2DArray"!==u.type||1!==u.size||u.isArray?"mat3"!==u.type||1!==u.size||u.isArray?"vec2"!==u.type||1!==u.size||u.isArray?"vec4"!==u.type||1!==u.size||u.isArray?(1!==u.size||u.isArray?$y:Hy)[u.type].call(null,l,d.location,d.value,c):void 0!==p.width?(a=d.value,o=c,(a[0]!==o.x||a[1]!==o.y||a[2]!==o.width||a[3]!==o.height)&&(a[0]=o.x,a[1]=o.y,a[2]=o.width,a[3]=o.height,l.uniform4f(d.location,o.x,o.y,o.width,o.height))):(a=d.value,o=c,(a[0]!==o[0]||a[1]!==o[1]||a[2]!==o[2]||a[3]!==o[3])&&(a[0]=o[0],a[1]=o[1],a[2]=o[2],a[3]=o[3],l.uniform4f(d.location,o[0],o[1],o[2],o[3]))):void 0!==p.x?(a=d.value,o=c,(a[0]!==o.x||a[1]!==o.y)&&(a[0]=o.x,a[1]=o.y,l.uniform2f(d.location,o.x,o.y))):(a=d.value,o=c,(a[0]!==o[0]||a[1]!==o[1])&&(a[0]=o[0],a[1]=o[1],l.uniform2f(d.location,o[0],o[1]))):void 0!==p.a?l.uniformMatrix3fv(d.location,!1,c.toArray(!0)):l.uniformMatrix3fv(d.location,!1,c):(r.texture.bind(c,n),d.value!==n&&(d.value=n,l.uniform1i(d.location,n)),n++):c!==d.value&&(d.value=c,l.uniform1i(d.location,Number(c))):c!==d.value&&(d.value=c,l.uniform1f(d.location,c)):!0===p.group&&r.shader.syncUniformGroup(c)}}(t,i.program.uniformData,e.uniformData,t.uniforms,s)}});const jy=new class{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this.tickerAdded=!1,this._pauseUpdate=!0}init(t){this.removeTickerListener(),this.events=t,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this.tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(t){this._pauseUpdate=t}addTickerListener(){this.tickerAdded||!this.domElement||(Tg.system.add(this.tickerUpdate,this,_g.INTERACTION),this.tickerAdded=!0)}removeTickerListener(){this.tickerAdded&&(Tg.system.remove(this.tickerUpdate,this),this.tickerAdded=!1)}pointerMoved(){this._didMove=!0}update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove)return void(this._didMove=!1);const t=this.events.rootPointerEvent;this.events.supportsTouchEvents&&"touch"===t.pointerType||globalThis.document.dispatchEvent(new PointerEvent("pointermove",{clientX:t.clientX,clientY:t.clientY}))}tickerUpdate(t){this._deltaTime+=t,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this.update())}};class zy{constructor(t){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=zy.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new gf,this.page=new gf,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=t}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(t,e,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(t,e,i,s,r){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}class Vy extends zy{constructor(){super(...arguments),this.client=new gf,this.movement=new gf,this.offset=new gf,this.global=new gf,this.screen=new gf}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(t,e,i){return t.worldTransform.applyInverse(i||this.global,e)}getModifierState(t){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(t)}initMouseEvent(t,e,i,s,r,n,o,a,l,h,u,c,d,p,f){throw new Error("Method not implemented.")}}class qy extends Vy{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return"pointermove"===this.type||"mousemove"===this.type||"touchmove"===this.type?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Jy extends Vy{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Jy.DOM_DELTA_PIXEL=0,Jy.DOM_DELTA_LINE=1,Jy.DOM_DELTA_PAGE=2;const Ky=new gf,Zy=new gf;class Qy{constructor(t){this.dispatch=new Qh,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=/* @__PURE__ */new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=t,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(t,e){this.mappingTable[t]||(this.mappingTable[t]=[]),this.mappingTable[t].push({fn:e,priority:0}),this.mappingTable[t].sort((t,e)=>t.priority-e.priority)}dispatchEvent(t,e){t.propagationStopped=!1,t.propagationImmediatelyStopped=!1,this.propagate(t,e),this.dispatch.emit(e||t.type,t)}mapEvent(t){if(!this.rootTarget)return;const e=this.mappingTable[t.type];if(e)for(let i=0,s=e.length;i<s;i++)e[i].fn(t);else console.warn(`[EventBoundary]: Event mapping not defined for ${t.type}`)}hitTest(t,e){jy.pauseUpdate=!0;const i=this[this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive"](this.rootTarget,this.rootTarget.eventMode,Ky.set(t,e),this.hitTestFn,this.hitPruneFn);return i&&i[0]}propagate(t,e){if(!t.target)return;const i=t.composedPath();t.eventPhase=t.CAPTURING_PHASE;for(let s=0,r=i.length-1;s<r;s++)if(t.currentTarget=i[s],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return;if(t.eventPhase=t.AT_TARGET,t.currentTarget=t.target,this.notifyTarget(t,e),!t.propagationStopped&&!t.propagationImmediatelyStopped){t.eventPhase=t.BUBBLING_PHASE;for(let s=i.length-2;s>=0;s--)if(t.currentTarget=i[s],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return}}all(t,e,i=this._allInteractiveElements){if(0===i.length)return;t.eventPhase=t.BUBBLING_PHASE;const s=Array.isArray(e)?e:[e];for(let r=i.length-1;r>=0;r--)s.forEach(e=>{t.currentTarget=i[r],this.notifyTarget(t,e)})}propagationPath(t){const e=[t];for(let i=0;i<2048&&t!==this.rootTarget;i++){if(!t.parent)throw new Error("Cannot find propagation path to disconnected target");e.push(t.parent),t=t.parent}return e.reverse(),e}hitTestMoveRecursive(t,e,i,s,r,n=!1){let o=!1;if(this._interactivePrune(t))return null;if(("dynamic"===t.eventMode||"dynamic"===e)&&(jy.pauseUpdate=!1),t.interactiveChildren&&t.children){const a=t.children;for(let l=a.length-1;l>=0;l--){const h=a[l],u=this.hitTestMoveRecursive(h,this._isInteractive(e)?e:h.eventMode,i,s,r,n||r(t,i));if(u){if(u.length>0&&!u[u.length-1].parent)continue;const e=t.isInteractive();(u.length>0||e)&&(e&&this._allInteractiveElements.push(t),u.push(t)),0===this._hitElements.length&&(this._hitElements=u),o=!0}}}const a=this._isInteractive(e),l=t.isInteractive();return a&&l&&this._allInteractiveElements.push(t),n||this._hitElements.length>0?null:o?this._hitElements:a&&!r(t,i)&&s(t,i)?l?[t]:[]:null}hitTestRecursive(t,e,i,s,r){if(this._interactivePrune(t)||r(t,i))return null;if(("dynamic"===t.eventMode||"dynamic"===e)&&(jy.pauseUpdate=!1),t.interactiveChildren&&t.children){const n=t.children;for(let o=n.length-1;o>=0;o--){const a=n[o],l=this.hitTestRecursive(a,this._isInteractive(e)?e:a.eventMode,i,s,r);if(l){if(l.length>0&&!l[l.length-1].parent)continue;const e=t.isInteractive();return(l.length>0||e)&&l.push(t),l}}}const n=this._isInteractive(e),o=t.isInteractive();return n&&s(t,i)?o?[t]:[]:null}_isInteractive(t){return"static"===t||"dynamic"===t}_interactivePrune(t){return!(t&&!t.isMask&&t.visible&&t.renderable&&"none"!==t.eventMode&&("passive"!==t.eventMode||t.interactiveChildren)&&!t.isMask)}hitPruneFn(t,e){if(t.hitArea&&(t.worldTransform.applyInverse(e,Zy),!t.hitArea.contains(Zy.x,Zy.y)))return!0;if(t._mask){const i=t._mask.isMaskData?t._mask.maskObject:t._mask;if(i&&!i.containsPoint?.(e))return!0}return!1}hitTestFn(t,e){return"passive"!==t.eventMode&&(!!t.hitArea||!!t.containsPoint&&t.containsPoint(e))}notifyTarget(t,e){const i=`on${e=e??t.type}`;t.currentTarget[i]?.(t);const s=t.eventPhase===t.CAPTURING_PHASE||t.eventPhase===t.AT_TARGET?`${e}capture`:e;this.notifyListeners(t,s),t.eventPhase===t.AT_TARGET&&this.notifyListeners(t,e)}mapPointerDown(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.createPointerEvent(t);if(this.dispatchEvent(e,"pointerdown"),"touch"===e.pointerType)this.dispatchEvent(e,"touchstart");else if("mouse"===e.pointerType||"pen"===e.pointerType){const t=2===e.button;this.dispatchEvent(e,t?"rightdown":"mousedown")}this.trackingData(t.pointerId).pressTargetsByButton[t.button]=e.composedPath(),this.freeEvent(e)}mapPointerMove(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const e=this.createPointerEvent(t);this._isPointerMoveEvent=!1;const i="mouse"===e.pointerType||"pen"===e.pointerType,s=this.trackingData(t.pointerId),r=this.findMountedTarget(s.overTargets);if(s.overTargets?.length>0&&r!==e.target){const s="mousemove"===t.type?"mouseout":"pointerout",n=this.createPointerEvent(t,s,r);if(this.dispatchEvent(n,"pointerout"),i&&this.dispatchEvent(n,"mouseout"),!e.composedPath().includes(r)){const s=this.createPointerEvent(t,"pointerleave",r);for(s.eventPhase=s.AT_TARGET;s.target&&!e.composedPath().includes(s.target);)s.currentTarget=s.target,this.notifyTarget(s),i&&this.notifyTarget(s,"mouseleave"),s.target=s.target.parent;this.freeEvent(s)}this.freeEvent(n)}if(r!==e.target){const s="mousemove"===t.type?"mouseover":"pointerover",n=this.clonePointerEvent(e,s);this.dispatchEvent(n,"pointerover"),i&&this.dispatchEvent(n,"mouseover");let o=r?.parent;for(;o&&o!==this.rootTarget.parent&&o!==e.target;)o=o.parent;if(!o||o===this.rootTarget.parent){const t=this.clonePointerEvent(e,"pointerenter");for(t.eventPhase=t.AT_TARGET;t.target&&t.target!==r&&t.target!==this.rootTarget.parent;)t.currentTarget=t.target,this.notifyTarget(t),i&&this.notifyTarget(t,"mouseenter"),t.target=t.target.parent;this.freeEvent(t)}this.freeEvent(n)}const n=[],o=this.enableGlobalMoveEvents??!0;this.moveOnAll?n.push("pointermove"):this.dispatchEvent(e,"pointermove"),o&&n.push("globalpointermove"),"touch"===e.pointerType&&(this.moveOnAll?n.splice(1,0,"touchmove"):this.dispatchEvent(e,"touchmove"),o&&n.push("globaltouchmove")),i&&(this.moveOnAll?n.splice(1,0,"mousemove"):this.dispatchEvent(e,"mousemove"),o&&n.push("globalmousemove"),this.cursor=e.target?.cursor),n.length>0&&this.all(e,n),this._allInteractiveElements.length=0,this._hitElements.length=0,s.overTargets=e.composedPath(),this.freeEvent(e)}mapPointerOver(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId),i=this.createPointerEvent(t),s="mouse"===i.pointerType||"pen"===i.pointerType;this.dispatchEvent(i,"pointerover"),s&&this.dispatchEvent(i,"mouseover"),"mouse"===i.pointerType&&(this.cursor=i.target?.cursor);const r=this.clonePointerEvent(i,"pointerenter");for(r.eventPhase=r.AT_TARGET;r.target&&r.target!==this.rootTarget.parent;)r.currentTarget=r.target,this.notifyTarget(r),s&&this.notifyTarget(r,"mouseenter"),r.target=r.target.parent;e.overTargets=i.composedPath(),this.freeEvent(i),this.freeEvent(r)}mapPointerOut(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId);if(e.overTargets){const i="mouse"===t.pointerType||"pen"===t.pointerType,s=this.findMountedTarget(e.overTargets),r=this.createPointerEvent(t,"pointerout",s);this.dispatchEvent(r),i&&this.dispatchEvent(r,"mouseout");const n=this.createPointerEvent(t,"pointerleave",s);for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),i&&this.notifyTarget(n,"mouseleave"),n.target=n.target.parent;e.overTargets=null,this.freeEvent(r),this.freeEvent(n)}this.cursor=null}mapPointerUp(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=performance.now(),i=this.createPointerEvent(t);if(this.dispatchEvent(i,"pointerup"),"touch"===i.pointerType)this.dispatchEvent(i,"touchend");else if("mouse"===i.pointerType||"pen"===i.pointerType){const t=2===i.button;this.dispatchEvent(i,t?"rightup":"mouseup")}const s=this.trackingData(t.pointerId),r=this.findMountedTarget(s.pressTargetsByButton[t.button]);let n=r;if(r&&!i.composedPath().includes(r)){let e=r;for(;e&&!i.composedPath().includes(e);){if(i.currentTarget=e,this.notifyTarget(i,"pointerupoutside"),"touch"===i.pointerType)this.notifyTarget(i,"touchendoutside");else if("mouse"===i.pointerType||"pen"===i.pointerType){const t=2===i.button;this.notifyTarget(i,t?"rightupoutside":"mouseupoutside")}e=e.parent}delete s.pressTargetsByButton[t.button],n=e}if(n){const r=this.clonePointerEvent(i,"click");r.target=n,r.path=null,s.clicksByButton[t.button]||(s.clicksByButton[t.button]={clickCount:0,target:r.target,timeStamp:e});const o=s.clicksByButton[t.button];if(o.target===r.target&&e-o.timeStamp<200?++o.clickCount:o.clickCount=1,o.target=r.target,o.timeStamp=e,r.detail=o.clickCount,"mouse"===r.pointerType){const t=2===r.button;this.dispatchEvent(r,t?"rightclick":"click")}else"touch"===r.pointerType&&this.dispatchEvent(r,"tap");this.dispatchEvent(r,"pointertap"),this.freeEvent(r)}this.freeEvent(i)}mapPointerUpOutside(t){if(!(t instanceof qy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId),i=this.findMountedTarget(e.pressTargetsByButton[t.button]),s=this.createPointerEvent(t);if(i){let r=i;for(;r;)s.currentTarget=r,this.notifyTarget(s,"pointerupoutside"),"touch"===s.pointerType?this.notifyTarget(s,"touchendoutside"):("mouse"===s.pointerType||"pen"===s.pointerType)&&this.notifyTarget(s,2===s.button?"rightupoutside":"mouseupoutside"),r=r.parent;delete e.pressTargetsByButton[t.button]}this.freeEvent(s)}mapWheel(t){if(!(t instanceof Jy))return void console.warn("EventBoundary cannot map a non-wheel event as a wheel event");const e=this.createWheelEvent(t);this.dispatchEvent(e),this.freeEvent(e)}findMountedTarget(t){if(!t)return null;let e=t[0];for(let i=1;i<t.length&&t[i].parent===e;i++)e=t[i];return e}createPointerEvent(t,e,i){const s=this.allocateEvent(qy);return this.copyPointerData(t,s),this.copyMouseData(t,s),this.copyData(t,s),s.nativeEvent=t.nativeEvent,s.originalEvent=t,s.target=i??this.hitTest(s.global.x,s.global.y)??this._hitElements[0],"string"==typeof e&&(s.type=e),s}createWheelEvent(t){const e=this.allocateEvent(Jy);return this.copyWheelData(t,e),this.copyMouseData(t,e),this.copyData(t,e),e.nativeEvent=t.nativeEvent,e.originalEvent=t,e.target=this.hitTest(e.global.x,e.global.y),e}clonePointerEvent(t,e){const i=this.allocateEvent(qy);return i.nativeEvent=t.nativeEvent,i.originalEvent=t.originalEvent,this.copyPointerData(t,i),this.copyMouseData(t,i),this.copyData(t,i),i.target=t.target,i.path=t.composedPath().slice(),i.type=e??i.type,i}copyWheelData(t,e){e.deltaMode=t.deltaMode,e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ}copyPointerData(t,e){t instanceof qy&&e instanceof qy&&(e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist)}copyMouseData(t,e){t instanceof Vy&&e instanceof Vy&&(e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.copyFrom(t.client),e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.copyFrom(t.movement),e.screen.copyFrom(t.screen),e.shiftKey=t.shiftKey,e.global.copyFrom(t.global))}copyData(t,e){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.detail=t.detail,e.view=t.view,e.which=t.which,e.layer.copyFrom(t.layer),e.page.copyFrom(t.page)}trackingData(t){return this.mappingState.trackingData[t]||(this.mappingState.trackingData[t]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[t]}allocateEvent(t){this.eventPool.has(t)||this.eventPool.set(t,[]);const e=this.eventPool.get(t).pop()||new t(this);return e.eventPhase=e.NONE,e.currentTarget=null,e.path=null,e.target=null,e}freeEvent(t){if(t.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const e=t.constructor;this.eventPool.has(e)||this.eventPool.set(e,[]),this.eventPool.get(e).push(t)}notifyListeners(t,e){const i=t.currentTarget._events[e];if(i&&t.currentTarget.isInteractive())if("fn"in i)i.once&&t.currentTarget.removeListener(e,i.fn,void 0,!0),i.fn.call(i.context,t);else for(let s=0,r=i.length;s<r&&!t.propagationImmediatelyStopped;s++)i[s].once&&t.currentTarget.removeListener(e,i[s].fn,void 0,!0),i[s].fn.call(i[s].context,t)}}const tv={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},ev=class t{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new Qy(null),jy.init(this),this.autoPreventDefault=!0,this.eventsAdded=!1,this.rootPointerEvent=new qy(null),this.rootWheelEvent=new Jy(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...t.defaultEventFeatures},{set:(t,e,i)=>("globalMove"===e&&(this.rootBoundary.enableGlobalMoveEvents=i),t[e]=i,!0)}),this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.onPointerOverOut=this.onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{view:i,resolution:s}=this.renderer;this.setTargetElement(i),this.resolution=s,t._defaultEventMode=e.eventMode??"auto",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(t){this.resolution=t}destroy(){this.setTargetElement(null),this.renderer=null}setCursor(t){t=t||"default";let e=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(e=!1),this.currentCursor===t)return;this.currentCursor=t;const i=this.cursorStyles[t];if(i)switch(typeof i){case"string":e&&(this.domElement.style.cursor=i);break;case"function":i(t);break;case"object":e&&Object.assign(this.domElement.style,i)}else e&&"string"==typeof t&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,t)&&(this.domElement.style.cursor=t)}get pointer(){return this.rootPointerEvent}onPointerDown(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&(t.cancelable||!("cancelable"in t))&&t.preventDefault();for(let i=0,s=e.length;i<s;i++){const t=e[i],s=this.bootstrapEvent(this.rootPointerEvent,t);this.rootBoundary.mapEvent(s)}this.setCursor(this.rootBoundary.cursor)}onPointerMove(t){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,jy.pointerMoved();const e=this.normalizeToPointerData(t);for(let i=0,s=e.length;i<s;i++){const t=this.bootstrapEvent(this.rootPointerEvent,e[i]);this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onPointerUp(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let e=t.target;t.composedPath&&t.composedPath().length>0&&(e=t.composedPath()[0]);const i=e!==this.domElement?"outside":"",s=this.normalizeToPointerData(t);for(let r=0,n=s.length;r<n;r++){const t=this.bootstrapEvent(this.rootPointerEvent,s[r]);t.type+=i,this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onPointerOverOut(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this.normalizeToPointerData(t);for(let i=0,s=e.length;i<s;i++){const t=this.bootstrapEvent(this.rootPointerEvent,e[i]);this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onWheel(t){if(!this.features.wheel)return;const e=this.normalizeWheelEvent(t);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(e)}setTargetElement(t){this.removeEvents(),this.domElement=t,jy.domElement=t,this.addEvents()}addEvents(){if(this.eventsAdded||!this.domElement)return;jy.addTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="none",t.msTouchAction="none"):this.supportsPointerEvents&&(t.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this.onPointerMove,!0),this.domElement.addEventListener("pointerdown",this.onPointerDown,!0),this.domElement.addEventListener("pointerleave",this.onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this.onPointerOverOut,!0),globalThis.addEventListener("pointerup",this.onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this.onPointerMove,!0),this.domElement.addEventListener("mousedown",this.onPointerDown,!0),this.domElement.addEventListener("mouseout",this.onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this.onPointerOverOut,!0),globalThis.addEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this.onPointerDown,!0),this.domElement.addEventListener("touchend",this.onPointerUp,!0),this.domElement.addEventListener("touchmove",this.onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this.eventsAdded=!0}removeEvents(){if(!this.eventsAdded||!this.domElement)return;jy.removeTickerListener();const t=this.domElement.style;globalThis.navigator.msPointerEnabled?(t.msContentZooming="",t.msTouchAction=""):this.supportsPointerEvents&&(t.touchAction=""),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this.onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this.onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this.onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this.onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this.onPointerMove,!0),this.domElement.removeEventListener("mousedown",this.onPointerDown,!0),this.domElement.removeEventListener("mouseout",this.onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this.onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this.onPointerDown,!0),this.domElement.removeEventListener("touchend",this.onPointerUp,!0),this.domElement.removeEventListener("touchmove",this.onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this.eventsAdded=!1}mapPositionToPoint(t,e,i){const s=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},r=1/this.resolution;t.x=(e-s.left)*(this.domElement.width/s.width)*r,t.y=(i-s.top)*(this.domElement.height/s.height)*r}normalizeToPointerData(t){const e=[];if(this.supportsTouchEvents&&t instanceof TouchEvent)for(let i=0,s=t.changedTouches.length;i<s;i++){const s=t.changedTouches[i];typeof s.button>"u"&&(s.button=0),typeof s.buttons>"u"&&(s.buttons=1),typeof s.isPrimary>"u"&&(s.isPrimary=1===t.touches.length&&"touchstart"===t.type),typeof s.width>"u"&&(s.width=s.radiusX||1),typeof s.height>"u"&&(s.height=s.radiusY||1),typeof s.tiltX>"u"&&(s.tiltX=0),typeof s.tiltY>"u"&&(s.tiltY=0),typeof s.pointerType>"u"&&(s.pointerType="touch"),typeof s.pointerId>"u"&&(s.pointerId=s.identifier||0),typeof s.pressure>"u"&&(s.pressure=s.force||.5),typeof s.twist>"u"&&(s.twist=0),typeof s.tangentialPressure>"u"&&(s.tangentialPressure=0),typeof s.layerX>"u"&&(s.layerX=s.offsetX=s.clientX),typeof s.layerY>"u"&&(s.layerY=s.offsetY=s.clientY),s.isNormalized=!0,s.type=t.type,e.push(s)}else if(globalThis.MouseEvent&&(!(t instanceof MouseEvent)||this.supportsPointerEvents&&t instanceof globalThis.PointerEvent))e.push(t);else{const i=t;typeof i.isPrimary>"u"&&(i.isPrimary=!0),typeof i.width>"u"&&(i.width=1),typeof i.height>"u"&&(i.height=1),typeof i.tiltX>"u"&&(i.tiltX=0),typeof i.tiltY>"u"&&(i.tiltY=0),typeof i.pointerType>"u"&&(i.pointerType="mouse"),typeof i.pointerId>"u"&&(i.pointerId=1),typeof i.pressure>"u"&&(i.pressure=.5),typeof i.twist>"u"&&(i.twist=0),typeof i.tangentialPressure>"u"&&(i.tangentialPressure=0),i.isNormalized=!0,e.push(i)}return e}normalizeWheelEvent(t){const e=this.rootWheelEvent;return this.transferMouseData(e,t),e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ,e.deltaMode=t.deltaMode,this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.nativeEvent=t,e.type=t.type,e}bootstrapEvent(t,e){return t.originalEvent=null,t.nativeEvent=e,t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist,this.transferMouseData(t,e),this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.isTrusted=e.isTrusted,"pointerleave"===t.type&&(t.type="pointerout"),t.type.startsWith("mouse")&&(t.type=t.type.replace("mouse","pointer")),t.type.startsWith("touch")&&(t.type=tv[t.type]||t.type),t}transferMouseData(t,e){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.x=e.clientX,t.client.y=e.clientY,t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.x=e.movementX,t.movement.y=e.movementY,t.page.x=e.pageX,t.page.y=e.pageY,t.relatedTarget=null,t.shiftKey=e.shiftKey}};ev.extension={name:"events",type:[Up.RendererSystem,Up.CanvasRendererSystem]},ev.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let iv=ev;function sv(t){return"dynamic"===t||"static"===t}Wp.add(iv);const rv={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,_internalInteractive:void 0,get interactive(){return this._internalInteractive??sv(iv.defaultEventMode)},set interactive(t){Md("7.2.0","Setting interactive is deprecated, use eventMode = 'none'/'passive'/'auto'/'static'/'dynamic' instead."),this._internalInteractive=t,this.eventMode=t?"static":"auto"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??iv.defaultEventMode},set eventMode(t){this._internalInteractive=sv(t),this._internalEventMode=t},isInteractive(){return"static"===this.eventMode||"dynamic"===this.eventMode},interactiveChildren:!0,hitArea:null,addEventListener(t,e,i){const s="boolean"==typeof i&&i||"object"==typeof i&&i.capture,r="object"==typeof i?i.signal:void 0,n="object"==typeof i&&!0===i.once,o="function"==typeof e?void 0:e;t=s?`${t}capture`:t;const a="function"==typeof e?e:e.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(t,a,o)}),n?l.once(t,a,o):l.on(t,a,o)},removeEventListener(t,e,i){const s="function"==typeof e?void 0:e;t="boolean"==typeof i&&i||"object"==typeof i&&i.capture?`${t}capture`:t,e="function"==typeof e?e:e.handleEvent,this.off(t,e,s)},dispatchEvent(t){if(!(t instanceof zy))throw new Error("DisplayObject cannot propagate events outside of the Federated Events API");return t.defaultPrevented=!1,t.path=null,t.target=this,t.manager.dispatchEvent(t),!t.defaultPrevented}};Hg.mixin(rv);const nv=new vf;class ov{constructor(t){this.renderer=t}async image(t,e,i,s){const r=new Image;return r.src=await this.base64(t,e,i,s),r}async base64(t,e,i,s){const r=this.canvas(t,s);if(void 0!==r.toBlob)return new Promise((t,s)=>{r.toBlob(e=>{if(!e)return void s(new Error("ICanvas.toBlob failed!"));const i=new FileReader;i.onload=()=>t(i.result),i.onerror=s,i.readAsDataURL(e)},e,i)});if(void 0!==r.toDataURL)return r.toDataURL(e,i);if(void 0!==r.convertToBlob){const t=await r.convertToBlob({type:e,quality:i});return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsDataURL(t)})}throw new Error("CanvasExtract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(t,e){const i=this.renderer;if(!i)throw new Error("The CanvasExtract has already been destroyed");let s,r,n;t&&(t instanceof Tm?n=t:(n=i.generateTexture(t,{region:e,resolution:i.resolution}),e&&(nv.width=e.width,nv.height=e.height,e=nv))),n?(s=n.baseTexture._canvasRenderTarget.context,r=n.baseTexture._canvasRenderTarget.resolution,e=e??n.frame):(s=i.canvasContext.rootContext,r=i._view.resolution,e||((e=nv).width=i.width/r,e.height=i.height/r));const o=Math.round(e.x*r),a=Math.round(e.y*r),l=Math.max(Math.round(e.width*r),1),h=Math.max(Math.round(e.height*r),1),u=new Op(l,h,1),c=s.getImageData(o,a,l,h);return u.context.putImageData(c,0,0),u.canvas}pixels(t,e){const i=this.renderer;if(!i)throw new Error("The CanvasExtract has already been destroyed");let s,r,n;t&&(t instanceof Tm?n=t:(n=i.generateTexture(t,{region:e,resolution:i.resolution}),e&&(nv.width=e.width,nv.height=e.height,e=nv))),n?(s=n.baseTexture._canvasRenderTarget.context,r=n.baseTexture._canvasRenderTarget.resolution,e=e??n.frame):(s=i.canvasContext.rootContext,r=i.resolution,e||((e=nv).width=i.width/r,e.height=i.height/r));const o=Math.round(e.x*r),a=Math.round(e.y*r),l=Math.max(Math.round(e.width*r),1),h=Math.max(Math.round(e.height*r),1);return s.getImageData(o,a,l,h).data}destroy(){this.renderer=null}}let av;function lv(t){const e=Oh.ADAPTER.createCanvas(6,1),i=e.getContext("2d");return i.fillStyle=t,i.fillRect(0,0,6,1),e}function hv(){if(typeof document>"u")return!1;if(void 0!==av)return av;const t=lv("#ff00ff"),e=lv("#ffff00"),i=Oh.ADAPTER.createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(t,0,0),i.drawImage(e,2,0);const s=i.getImageData(2,0,1,1);if(s){const t=s.data;av=255===t[0]&&0===t[1]&&0===t[2]}else av=!1;return av}ov.extension={name:"extract",type:Up.CanvasRendererSystem},Wp.add(ov),tf.prototype.getDrawableSource=function(){const t=this.resource;return t?t.bitmap||t.source:null},vm.prototype._canvasRenderTarget=null,Em.prototype.patternCache=null,Em.prototype.tintCache=null;const uv=new Pf;class cv{constructor(t){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=function(t=[]){return hv()?(t[mh.NORMAL]="source-over",t[mh.ADD]="lighter",t[mh.MULTIPLY]="multiply",t[mh.SCREEN]="screen",t[mh.OVERLAY]="overlay",t[mh.DARKEN]="darken",t[mh.LIGHTEN]="lighten",t[mh.COLOR_DODGE]="color-dodge",t[mh.COLOR_BURN]="color-burn",t[mh.HARD_LIGHT]="hard-light",t[mh.SOFT_LIGHT]="soft-light",t[mh.DIFFERENCE]="difference",t[mh.EXCLUSION]="exclusion",t[mh.HUE]="hue",t[mh.SATURATION]="saturation",t[mh.COLOR]="color",t[mh.LUMINOSITY]="luminosity"):(t[mh.NORMAL]="source-over",t[mh.ADD]="lighter",t[mh.MULTIPLY]="source-over",t[mh.SCREEN]="source-over",t[mh.OVERLAY]="source-over",t[mh.DARKEN]="source-over",t[mh.LIGHTEN]="source-over",t[mh.COLOR_DODGE]="source-over",t[mh.COLOR_BURN]="source-over",t[mh.HARD_LIGHT]="source-over",t[mh.SOFT_LIGHT]="source-over",t[mh.DIFFERENCE]="source-over",t[mh.EXCLUSION]="source-over",t[mh.HUE]="source-over",t[mh.SATURATION]="source-over",t[mh.COLOR]="source-over",t[mh.LUMINOSITY]="source-over"),t[mh.NORMAL_NPM]=t[mh.NORMAL],t[mh.ADD_NPM]=t[mh.ADD],t[mh.SCREEN_NPM]=t[mh.SCREEN],t[mh.SRC_IN]="source-in",t[mh.SRC_OUT]="source-out",t[mh.SRC_ATOP]="source-atop",t[mh.DST_OVER]="destination-over",t[mh.DST_IN]="destination-in",t[mh.DST_OUT]="destination-out",t[mh.DST_ATOP]="destination-atop",t[mh.XOR]="xor",t[mh.SUBTRACT]="source-over",t}(),this._activeBlendMode=null,this._projTransform=null,this._outerBlend=!1,this.renderer=t}init(){const t=this.renderer.background.alpha<1;if(this.rootContext=this.renderer.view.getContext("2d",{alpha:t}),this.activeContext=this.rootContext,!this.rootContext.imageSmoothingEnabled){const t=this.rootContext;t.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":t.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":t.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":t.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(t,e,i){let s=t;const r=this._projTransform,n=this.activeResolution;i=i||n,r&&(s=uv,s.copyFrom(t),s.prepend(r)),e?this.activeContext.setTransform(s.a*i,s.b*i,s.c*i,s.d*i,s.tx*n|0,s.ty*n|0):this.activeContext.setTransform(s.a*i,s.b*i,s.c*i,s.d*i,s.tx*n,s.ty*n)}clear(t,e){const{activeContext:i,renderer:s}=this,r=t?pp.shared.setValue(t):this.renderer.background.backgroundColor;i.clearRect(0,0,s.width,s.height),t&&(i.globalAlpha=e??this.renderer.background.alpha,i.fillStyle=r.toHex(),i.fillRect(0,0,s.width,s.height),i.globalAlpha=1)}setBlendMode(t,e){const i=t===mh.SRC_IN||t===mh.SRC_OUT||t===mh.DST_IN||t===mh.DST_ATOP;!e&&i&&(t=mh.NORMAL),this._activeBlendMode!==t&&(this._activeBlendMode=t,this._outerBlend=i,this.activeContext.globalCompositeOperation=this.blendModes[t])}resize(){this.smoothProperty&&(this.rootContext[this.smoothProperty]=tf.defaultOptions.scaleMode===wh.LINEAR)}invalidateBlendMode(){this._activeBlendMode=this.blendModes.indexOf(this.activeContext.globalCompositeOperation)}destroy(){this.renderer=null,this.rootContext=null,this.activeContext=null,this.smoothProperty=null}}cv.extension={type:Up.CanvasRendererSystem,name:"canvasContext"},Wp.add(cv);class dv{constructor(t){this._foundShapes=[],this.renderer=t}pushMask(t){const e=this.renderer,i=t.maskObject||t;e.canvasContext.activeContext.save();const s=this._foundShapes;if(this.recursiveFindShapes(i,s),s.length>0){const t=e.canvasContext.activeContext;t.beginPath();for(let e=0;e<s.length;e++){const t=s[e],i=t.transform.worldTransform;this.renderer.canvasContext.setContextTransform(i),this.renderGraphicsShape(t)}s.length=0,t.clip()}}recursiveFindShapes(t,e){t.geometry&&t.geometry.graphicsData&&e.push(t);const{children:i}=t;if(i)for(let s=0;s<i.length;s++)this.recursiveFindShapes(i[s],e)}renderGraphicsShape(t){t.finishPoly();const e=this.renderer.canvasContext.activeContext,i=t.geometry.graphicsData,s=i.length;if(0!==s)for(let r=0;r<s;r++){const t=i[r],s=t.shape;if(s.type===mf.POLY){let i=s.points;const r=t.holes;let n,o,a,l;e.moveTo(i[0],i[1]);for(let t=1;t<i.length/2;t++)e.lineTo(i[2*t],i[2*t+1]);if(r.length>0){n=0,a=i[0],l=i[1];for(let t=2;t+2<i.length;t+=2)n+=(i[t]-a)*(i[t+3]-l)-(i[t+2]-a)*(i[t+1]-l);for(let t=0;t<r.length;t++)if(i=r[t].shape.points,i){o=0,a=i[0],l=i[1];for(let t=2;t+2<i.length;t+=2)o+=(i[t]-a)*(i[t+3]-l)-(i[t+2]-a)*(i[t+1]-l);if(o*n<0){e.moveTo(i[0],i[1]);for(let t=2;t<i.length;t+=2)e.lineTo(i[t],i[t+1])}else{e.moveTo(i[i.length-2],i[i.length-1]);for(let t=i.length-4;t>=0;t-=2)e.lineTo(i[t],i[t+1])}r[t].shape.closeStroke&&e.closePath()}}i[0]===i[i.length-2]&&i[1]===i[i.length-1]&&e.closePath()}else if(s.type===mf.RECT)e.rect(s.x,s.y,s.width,s.height),e.closePath();else if(s.type===mf.CIRC)e.arc(s.x,s.y,s.radius,0,2*Math.PI),e.closePath();else if(s.type===mf.ELIP){const t=2*s.width,i=2*s.height,r=s.x-t/2,n=s.y-i/2,o=.5522848,a=t/2*o,l=i/2*o,h=r+t,u=n+i,c=r+t/2,d=n+i/2;e.moveTo(r,d),e.bezierCurveTo(r,d-l,c-a,n,c,n),e.bezierCurveTo(c+a,n,h,d-l,h,d),e.bezierCurveTo(h,d+l,c+a,u,c,u),e.bezierCurveTo(c-a,u,r,d+l,r,d),e.closePath()}else if(s.type===mf.RREC){const t=s.x,i=s.y,r=s.width,n=s.height;let o=s.radius;const a=Math.min(r,n)/2;o=o>a?a:o,e.moveTo(t,i+o),e.lineTo(t,i+n-o),e.quadraticCurveTo(t,i+n,t+o,i+n),e.lineTo(t+r-o,i+n),e.quadraticCurveTo(t+r,i+n,t+r,i+n-o),e.lineTo(t+r,i+o),e.quadraticCurveTo(t+r,i,t+r-o,i),e.lineTo(t+o,i),e.quadraticCurveTo(t,i,t,i+o),e.closePath()}}}popMask(t){t.canvasContext.activeContext.restore(),t.canvasContext.invalidateBlendMode()}destroy(){}}dv.extension={type:Up.CanvasRendererSystem,name:"mask"},Wp.add(dv);class pv{constructor(t){this.renderer=t}render(t,e){const i=this.renderer;if(!i.view)return;const s=i.canvasContext;let r,n,o,a;e&&(r=e.renderTexture,n=e.clear,o=e.transform,a=e.skipUpdateTransform),this.renderingToScreen=!r,i.emit("prerender");const l=i.resolution;r?(r=r.castToBaseTexture(),r._canvasRenderTarget||(r._canvasRenderTarget=new Op(r.width,r.height,r.resolution),r.resource=new Bg(r._canvasRenderTarget.canvas),r.valid=!0),s.activeContext=r._canvasRenderTarget.context,i.canvasContext.activeResolution=r._canvasRenderTarget.resolution):(s.activeContext=s.rootContext,s.activeResolution=l);const h=s.activeContext;if(s._projTransform=o||null,r||(this.lastObjectRendered=t),!a){const e=t.enableTempParent();t.updateTransform(),t.disableTempParent(e)}if(h.save(),h.setTransform(1,0,0,1,0,0),h.globalAlpha=1,s._activeBlendMode=mh.NORMAL,s._outerBlend=!1,h.globalCompositeOperation=s.blendModes[mh.NORMAL],n??i.background.clearBeforeRender)if(this.renderingToScreen){h.clearRect(0,0,i.width,i.height);const t=i.background;t.alpha>0&&(h.globalAlpha=t.backgroundColor.alpha,h.fillStyle=t.backgroundColor.toHex(),h.fillRect(0,0,i.width,i.height),h.globalAlpha=1)}else r._canvasRenderTarget.clear(),r.clear.alpha>0&&(h.globalAlpha=r.clear.alpha,h.fillStyle=r.clear.toHex(),h.fillRect(0,0,r.realWidth,r.realHeight),h.globalAlpha=1);const u=s.activeContext;s.activeContext=h,t.renderCanvas(i),s.activeContext=u,h.restore(),s.activeResolution=l,s._projTransform=null,i.emit("postrender")}destroy(){this.lastObjectRendered=null,this.render=null}}pv.extension={type:Up.CanvasRendererSystem,name:"objectRenderer"},Wp.add(pv);const{deprecation:fv}=Dp,mv=class t extends mg{constructor(e){super(),this.type=ph.CANVAS,this.rendererLogId="Canvas",e=Object.assign({},Oh.RENDER_OPTIONS,e);const i={runners:["init","destroy","contextChange","resolutionChange","reset","update","postrender","prerender","resize"],systems:t.__systems,priority:["textureGenerator","background","_view","_plugin","startup","mask","canvasContext","objectRenderer"]};this.setup(i),"useContextAlpha"in e&&(fv("7.0.0","options.useContextAlpha is deprecated, use options.backgroundAlpha instead"),e.backgroundAlpha=!1===e.useContextAlpha?1:e.backgroundAlpha),this._plugin.rendererPlugins=t.__plugins,this.options=e,this.startup.run(this.options)}static test(){return!0}generateTexture(t,e){return this.textureGenerator.generateTexture(t,e)}reset(){}render(t,e){this.objectRenderer.render(t,e)}clear(){this.canvasContext.clear()}destroy(t){this.runners.destroy.items.reverse(),this.emitWithCustomOptions(this.runners.destroy,{_view:t}),super.destroy()}get plugins(){return this._plugin.plugins}resize(t,e){this._view.resizeView(t,e)}get width(){return this._view.element.width}get height(){return this._view.element.height}get resolution(){return this._view.resolution}set resolution(t){this._view.resolution=t,this.runners.resolutionChange.emit(t)}get autoDensity(){return this._view.autoDensity}get view(){return this._view.element}get screen(){return this._view.screen}get lastObjectRendered(){return this.objectRenderer.lastObjectRendered}get renderingToScreen(){return this.objectRenderer.renderingToScreen}get clearBeforeRender(){return this.background.clearBeforeRender}get blendModes(){return fv("7.0.0","renderer.blendModes has been deprecated, please use renderer.canvasContext.blendModes instead"),this.canvasContext.blendModes}get maskManager(){return fv("7.0.0","renderer.maskManager has been deprecated, please use renderer.mask instead"),this.mask}get refresh(){return fv("7.0.0","renderer.refresh has been deprecated"),!0}get rootContext(){return fv("7.0.0","renderer.rootContext has been deprecated, please use renderer.canvasContext.rootContext instead"),this.canvasContext.rootContext}get context(){return fv("7.0.0","renderer.context has been deprecated, please use renderer.canvasContext.activeContext instead"),this.canvasContext.activeContext}get smoothProperty(){return fv("7.0.0","renderer.smoothProperty has been deprecated, please use renderer.canvasContext.smoothProperty instead"),this.canvasContext.smoothProperty}setBlendMode(t,e){fv("7.0.0","renderer.setBlendMode has been deprecated, use renderer.canvasContext.setBlendMode instead"),this.canvasContext.setBlendMode(t,e)}invalidateBlendMode(){fv("7.0.0","renderer.invalidateBlendMode has been deprecated, use renderer.canvasContext.invalidateBlendMode instead"),this.canvasContext.invalidateBlendMode()}setContextTransform(t,e,i){fv("7.0.0","renderer.setContextTransform has been deprecated, use renderer.canvasContext.setContextTransform instead"),this.canvasContext.setContextTransform(t,e,i)}get backgroundColor(){return fv("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color}set backgroundColor(t){fv("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color=t}get backgroundAlpha(){return fv("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha}set backgroundAlpha(t){fv("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha=t}get preserveDrawingBuffer(){return fv("7.0.0","renderer.preserveDrawingBuffer has been deprecated"),!1}get useContextAlpha(){return fv("7.0.0","renderer.useContextAlpha has been deprecated"),!1}};mv.extension={type:Up.Renderer,priority:0},mv.__plugins={},mv.__systems={};let gv=mv;Wp.handleByMap(Up.CanvasRendererPlugin,gv.__plugins),Wp.handleByMap(Up.CanvasRendererSystem,gv.__systems),Wp.add(gv);const yv={canvas:null,getTintedCanvas:(t,e)=>{const i=t.texture,s=pp.shared.setValue(e).toHex();i.tintCache=i.tintCache||{};const r=i.tintCache[s];let n;if(r){if(r.tintId===i._updateID)return i.tintCache[s];n=i.tintCache[s]}else n=Oh.ADAPTER.createCanvas();if(yv.tintMethod(i,e,n),n.tintId=i._updateID,yv.convertTintToImage&&void 0!==n.toDataURL){const t=new Image;t.src=n.toDataURL(),i.tintCache[s]=t}else i.tintCache[s]=n;return n},getTintedPattern:(t,e)=>{const i=pp.shared.setValue(e).toHex();t.patternCache=t.patternCache||{};let s=t.patternCache[i];return s?.tintId===t._updateID||(yv.canvas||(yv.canvas=Oh.ADAPTER.createCanvas()),yv.tintMethod(t,e,yv.canvas),s=yv.canvas.getContext("2d").createPattern(yv.canvas,"repeat"),s.tintId=t._updateID,t.patternCache[i]=s),s},tintWithMultiply:(t,e,i)=>{const s=i.getContext("2d"),r=t._frame.clone(),n=t.baseTexture.resolution;r.x*=n,r.y*=n,r.width*=n,r.height*=n,i.width=Math.ceil(r.width),i.height=Math.ceil(r.height),s.save(),s.fillStyle=pp.shared.setValue(e).toHex(),s.fillRect(0,0,r.width,r.height),s.globalCompositeOperation="multiply";const o=t.baseTexture.getDrawableSource();s.drawImage(o,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.globalCompositeOperation="destination-atop",s.drawImage(o,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore()},tintWithOverlay:(t,e,i)=>{const s=i.getContext("2d"),r=t._frame.clone(),n=t.baseTexture.resolution;r.x*=n,r.y*=n,r.width*=n,r.height*=n,i.width=Math.ceil(r.width),i.height=Math.ceil(r.height),s.save(),s.globalCompositeOperation="copy",s.fillStyle=`#${`00000${(0|e).toString(16)}`.slice(-6)}`,s.fillRect(0,0,r.width,r.height),s.globalCompositeOperation="destination-atop",s.drawImage(t.baseTexture.getDrawableSource(),r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore()},tintWithPerPixel:(t,e,i)=>{const s=i.getContext("2d"),r=t._frame.clone(),n=t.baseTexture.resolution;r.x*=n,r.y*=n,r.width*=n,r.height*=n,i.width=Math.ceil(r.width),i.height=Math.ceil(r.height),s.save(),s.globalCompositeOperation="copy",s.drawImage(t.baseTexture.getDrawableSource(),r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore();const[o,a,l]=pp.shared.setValue(e).toArray(),h=s.getImageData(0,0,r.width,r.height),u=h.data;for(let c=0;c<u.length;c+=4)u[c+0]*=o,u[c+1]*=a,u[c+2]*=l;s.putImageData(h,0,0)},roundColor:t=>(Md("7.3.0","PIXI.canvasUtils.roundColor is deprecated"),pp.shared.setValue(t).round(yv.cacheStepsPerColorChannel).toNumber()),cacheStepsPerColorChannel:8,convertTintToImage:!1,canUseMultiply:hv(),tintMethod:null};let vv;yv.tintMethod=yv.canUseMultiply?yv.tintWithMultiply:yv.tintWithPerPixel;const xv=new Pf;Ty.prototype.generateCanvasTexture=function(t,e=1){const i=this.getLocalBounds(new vf);i.width=Math.max(i.width,1/e),i.height=Math.max(i.height,1/e);const s=Tm.create({width:i.width,height:i.height,scaleMode:t,resolution:e});vv||(vv=new gv),this.transform.updateLocalTransform(),this.transform.localTransform.copyTo(xv),xv.invert(),xv.tx-=i.x,xv.ty-=i.y,vv.render(this,{renderTexture:s,clear:!0,transform:xv});const r=Em.from(s.baseTexture._canvasRenderTarget.canvas,{scaleMode:t});return r.baseTexture.setResolution(e),r},Ty.prototype.cachedGraphicsData=[],Ty.prototype._renderCanvas=function(t){!0!==this.isMask&&(this.finishPoly(),t.plugins.graphics.render(this))};class bv{static offsetPolygon(t,e){const i=[],s=t.length;e=bv.isPolygonClockwise(t)?e:-1*e;for(let r=0;r<s;r+=2){let n=r-2;n<0&&(n+=s);const o=(r+2)%s;let a=t[r]-t[n],l=t[r+1]-t[n+1],h=Math.sqrt(a*a+l*l);a/=h,l/=h,a*=e,l*=e;const u=-l,c=a,d=[t[n]+u,t[n+1]+c],p=[t[r]+u,t[r+1]+c];let f=t[o]-t[r],m=t[o+1]-t[r+1];h=Math.sqrt(f*f+m*m),f/=h,m/=h,f*=e,m*=e;const g=-m,y=f,v=[t[r]+g,t[r+1]+y],x=[t[o]+g,t[o+1]+y],b=bv.findIntersection(d[0],d[1],p[0],p[1],v[0],v[1],x[0],x[1]);b&&i.push(...b)}return i}static findIntersection(t,e,i,s,r,n,o,a){const l=(a-n)*(i-t)-(o-r)*(s-e),h=(o-r)*(e-n)-(a-n)*(t-r);if(0===l)return 0===h&&0===(i-t)*(e-n)-(s-e)*(t-r)?[(t+i)/2,(e+s)/2]:null;const u=h/l;return[t+u*(i-t),e+u*(s-e)]}static isPolygonClockwise(t){let e=0;for(let i=0,s=t.length-2;i<t.length;s=i,i+=2)e+=(t[i]-t[s])*(t[i+1]+t[s+1]);return e>0}}class wv{constructor(t){this._svgMatrix=null,this._tempMatrix=new Pf,this.renderer=t}_calcCanvasStyle(t,e){let i;return t.texture&&t.texture.baseTexture!==Em.WHITE.baseTexture?t.texture.valid?(i=yv.getTintedPattern(t.texture,e),this.setPatternTransform(i,t.matrix||Pf.IDENTITY)):i="#808080":i=`#${`00000${(0|e).toString(16)}`.slice(-6)}`,i}render(t){const e=this.renderer,i=e.canvasContext.activeContext,s=t.worldAlpha,r=t.transform.worldTransform;e.canvasContext.setContextTransform(r),e.canvasContext.setBlendMode(t.blendMode);const n=t.geometry.graphicsData;let o,a;const l=pp.shared.setValue(t.tint).toArray();for(let h=0;h<n.length;h++){const t=n[h],u=t.shape,c=t.fillStyle,d=t.lineStyle,p=0|t.fillStyle.color,f=0|t.lineStyle.color;if(t.matrix&&e.canvasContext.setContextTransform(r.copyTo(this._tempMatrix).append(t.matrix)),c.visible&&(o=this._calcCanvasStyle(c,pp.shared.setValue(p).multiply(l).toNumber())),d.visible&&(a=this._calcCanvasStyle(d,pp.shared.setValue(f).multiply(l).toNumber())),i.lineWidth=d.width,i.lineCap=d.cap,i.lineJoin=d.join,i.miterLimit=d.miterLimit,t.type===mf.POLY){i.beginPath();const e=u;let r=e.points;const n=t.holes;let l,h,p,f,m;i.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)i.lineTo(r[t],r[t+1]);if(e.closeStroke&&i.closePath(),n.length>0){m=[],l=0,p=r[0],f=r[1];for(let t=2;t+2<r.length;t+=2)l+=(r[t]-p)*(r[t+3]-f)-(r[t+2]-p)*(r[t+1]-f);for(let t=0;t<n.length;t++)if(r=n[t].shape.points,r){h=0,p=r[0],f=r[1];for(let t=2;t+2<r.length;t+=2)h+=(r[t]-p)*(r[t+3]-f)-(r[t+2]-p)*(r[t+1]-f);if(h*l<0){i.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)i.lineTo(r[t],r[t+1])}else{i.moveTo(r[r.length-2],r[r.length-1]);for(let t=r.length-4;t>=0;t-=2)i.lineTo(r[t],r[t+1])}n[t].shape.closeStroke&&i.closePath(),m[t]=h*l<0}}c.visible&&(i.globalAlpha=c.alpha*s,i.fillStyle=o,i.fill()),d.visible&&this.paintPolygonStroke(e,d,a,n,m,s,i)}else if(t.type===mf.RECT){const t=u;if(c.visible&&(i.globalAlpha=c.alpha*s,i.fillStyle=o,i.fillRect(t.x,t.y,t.width,t.height)),d.visible){const e=d.width*(.5-(1-d.alignment)),r=t.width+2*e,n=t.height+2*e;i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.strokeRect(t.x-e,t.y-e,r,n)}}else if(t.type===mf.CIRC){const t=u;if(i.beginPath(),i.arc(t.x,t.y,t.radius,0,2*Math.PI),i.closePath(),c.visible&&(i.globalAlpha=c.alpha*s,i.fillStyle=o,i.fill()),d.visible){if(.5!==d.alignment){const e=d.width*(.5-(1-d.alignment));i.beginPath(),i.arc(t.x,t.y,t.radius+e,0,2*Math.PI),i.closePath()}i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.stroke()}}else if(t.type===mf.ELIP){const t=u,e=1===d.alignment;if(e||this.paintEllipse(t,c,d,o,s,i),d.visible){if(.5!==d.alignment){const e=.5522848,s=d.width*(.5-(1-d.alignment)),r=2*(t.width+s),n=2*(t.height+s),o=t.x-r/2,a=t.y-n/2,l=r/2*e,h=n/2*e,u=o+r,c=a+n,p=o+r/2,f=a+n/2;i.beginPath(),i.moveTo(o,f),i.bezierCurveTo(o,f-h,p-l,a,p,a),i.bezierCurveTo(p+l,a,u,f-h,u,f),i.bezierCurveTo(u,f+h,p+l,c,p,c),i.bezierCurveTo(p-l,c,o,f+h,o,f),i.closePath()}i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.stroke()}e&&this.paintEllipse(t,c,d,o,s,i)}else if(t.type===mf.RREC){const t=u,e=1===d.alignment;if(e||this.paintRoundedRectangle(t,c,d,o,s,i),d.visible){if(.5!==d.alignment){const e=t.width,s=t.height,r=d.width*(.5-(1-d.alignment)),n=t.x-r,o=t.y-r,a=t.width+2*r,l=t.height+2*r,h=r*(d.alignment>=1?Math.min(a/e,l/s):Math.min(e/a,s/l));let u=t.radius+h;const c=Math.min(a,l)/2;u=u>c?c:u,i.beginPath(),i.moveTo(n,o+u),i.lineTo(n,o+l-u),i.quadraticCurveTo(n,o+l,n+u,o+l),i.lineTo(n+a-u,o+l),i.quadraticCurveTo(n+a,o+l,n+a,o+l-u),i.lineTo(n+a,o+u),i.quadraticCurveTo(n+a,o,n+a-u,o),i.lineTo(n+u,o),i.quadraticCurveTo(n,o,n,o+u),i.closePath()}i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.stroke()}e&&this.paintRoundedRectangle(t,c,d,o,s,i)}}}paintPolygonStroke(t,e,i,s,r,n,o){if(.5!==e.alignment){const i=e.width*(.5-(1-e.alignment));let n,a=bv.offsetPolygon(t.points,i);o.beginPath(),o.moveTo(a[0],a[1]);for(let t=2;t<a.length;t+=2)o.lineTo(a[t],a[t+1]);t.closeStroke&&o.closePath();for(let t=0;t<s.length;t++){if(n=s[t].shape.points,a=bv.offsetPolygon(n,i),r[t]){o.moveTo(a[0],a[1]);for(let t=2;t<a.length;t+=2)o.lineTo(a[t],a[t+1])}else{o.moveTo(a[a.length-2],a[a.length-1]);for(let t=a.length-4;t>=0;t-=2)o.lineTo(a[t],a[t+1])}s[t].shape.closeStroke&&o.closePath()}}o.globalAlpha=e.alpha*n,o.strokeStyle=i,o.stroke()}paintEllipse(t,e,i,s,r,n){const o=2*t.width,a=2*t.height,l=t.x-o/2,h=t.y-a/2,u=.5522848,c=o/2*u,d=a/2*u,p=l+o,f=h+a,m=l+o/2,g=h+a/2;0===i.alignment&&n.save(),n.beginPath(),n.moveTo(l,g),n.bezierCurveTo(l,g-d,m-c,h,m,h),n.bezierCurveTo(m+c,h,p,g-d,p,g),n.bezierCurveTo(p,g+d,m+c,f,m,f),n.bezierCurveTo(m-c,f,l,g+d,l,g),n.closePath(),0===i.alignment&&n.clip(),e.visible&&(n.globalAlpha=e.alpha*r,n.fillStyle=s,n.fill()),0===i.alignment&&n.restore()}paintRoundedRectangle(t,e,i,s,r,n){const o=t.x,a=t.y,l=t.width,h=t.height;let u=t.radius;const c=Math.min(l,h)/2;u=u>c?c:u,0===i.alignment&&n.save(),n.beginPath(),n.moveTo(o,a+u),n.lineTo(o,a+h-u),n.quadraticCurveTo(o,a+h,o+u,a+h),n.lineTo(o+l-u,a+h),n.quadraticCurveTo(o+l,a+h,o+l,a+h-u),n.lineTo(o+l,a+u),n.quadraticCurveTo(o+l,a,o+l-u,a),n.lineTo(o+u,a),n.quadraticCurveTo(o,a,o,a+u),n.closePath(),0===i.alignment&&n.clip(),e.visible&&(n.globalAlpha=e.alpha*r,n.fillStyle=s,n.fill()),0===i.alignment&&n.restore()}setPatternTransform(t,e){if(!1!==this._svgMatrix){if(!this._svgMatrix){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");if(e?.createSVGMatrix&&(this._svgMatrix=e.createSVGMatrix()),!this._svgMatrix||!t.setTransform)return void(this._svgMatrix=!1)}this._svgMatrix.a=e.a,this._svgMatrix.b=e.b,this._svgMatrix.c=e.c,this._svgMatrix.d=e.d,this._svgMatrix.e=e.tx,this._svgMatrix.f=e.ty,t.setTransform(this._svgMatrix.inverse())}}destroy(){this.renderer=null,this._svgMatrix=null,this._tempMatrix=null}}wv.extension={name:"graphics",type:Up.CanvasRendererPlugin},Wp.add(wv);class _v{constructor(t){this.maxItemsPerFrame=t,this.itemsLeft=0}beginFrame(){this.itemsLeft=this.maxItemsPerFrame}allowedToUpload(){return this.itemsLeft-- >0}}function Pv(t,e){let i=!1;if(t?._textures?.length)for(let s=0;s<t._textures.length;s++)if(t._textures[s]instanceof Em){const r=t._textures[s].baseTexture;e.includes(r)||(e.push(r),i=!0)}return i}function Ev(t,e){if(t.baseTexture instanceof tf){const i=t.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function Tv(t,e){if(t._texture&&t._texture instanceof Em){const i=t._texture.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function Av(t,e){return e instanceof Fy&&(e.updateText(!0),!0)}function Iv(t,e){if(e instanceof Ny){const t=e.toFontString();return Cy.measureFont(t),!0}return!1}function Sv(t,e){if(t instanceof Fy){e.includes(t.style)||e.push(t.style),e.includes(t)||e.push(t);const i=t._texture.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function Cv(t,e){return t instanceof Ny&&(e.includes(t)||e.push(t),!0)}const Mv=class t{constructor(e){this.limiter=new _v(t.uploadsPerFrame),this.renderer=e,this.uploadHookHelper=null,this.queue=[],this.addHooks=[],this.uploadHooks=[],this.completes=[],this.ticking=!1,this.delayedTick=()=>{this.queue&&this.prepareItems()},this.registerFindHook(Sv),this.registerFindHook(Cv),this.registerFindHook(Pv),this.registerFindHook(Ev),this.registerFindHook(Tv),this.registerUploadHook(Av),this.registerUploadHook(Iv)}upload(t){return new Promise(e=>{t&&this.add(t),this.queue.length?(this.completes.push(e),this.ticking||(this.ticking=!0,Tg.system.addOnce(this.tick,this,_g.UTILITY))):e()})}tick(){setTimeout(this.delayedTick,0)}prepareItems(){for(this.limiter.beginFrame();this.queue.length&&this.limiter.allowedToUpload();){const t=this.queue[0];let e=!1;if(t&&!t._destroyed)for(let i=0,s=this.uploadHooks.length;i<s;i++)if(this.uploadHooks[i](this.uploadHookHelper,t)){this.queue.shift(),e=!0;break}e||this.queue.shift()}if(this.queue.length)Tg.system.addOnce(this.tick,this,_g.UTILITY);else{this.ticking=!1;const t=this.completes.slice(0);this.completes.length=0;for(let e=0,i=t.length;e<i;e++)t[e]()}}registerFindHook(t){return t&&this.addHooks.push(t),this}registerUploadHook(t){return t&&this.uploadHooks.push(t),this}add(t){for(let e=0,i=this.addHooks.length;e<i&&!this.addHooks[e](t,this.queue);e++);if(t instanceof qg)for(let e=t.children.length-1;e>=0;e--)this.add(t.children[e]);return this}destroy(){this.ticking&&Tg.system.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null}};Mv.uploadsPerFrame=4;let Ov=Mv;function Nv(t,e){return e instanceof tf&&(e._glTextures[t.CONTEXT_UID]||t.texture.bind(e),!0)}function Lv(t,e){if(!(e instanceof Ty))return!1;const{geometry:i}=e;e.finishPoly(),i.updateBatches();const{batches:s}=i;for(let r=0;r<s.length;r++){const{texture:e}=s[r].style;e&&Nv(t,e.baseTexture)}return i.batchable||t.geometry.bind(i,e._resolveDirectShader(t)),!0}function Rv(t,e){return t instanceof Ty&&(e.push(t),!0)}Object.defineProperties(Oh,{UPLOADS_PER_FRAME:{get:()=>Ov.uploadsPerFrame,set(t){Md("7.1.0","settings.UPLOADS_PER_FRAME is deprecated, use prepare.BasePrepare.uploadsPerFrame"),Ov.uploadsPerFrame=t}}});class Bv extends Ov{constructor(t){super(t),this.uploadHookHelper=this.renderer,this.registerFindHook(Rv),this.registerUploadHook(Nv),this.registerUploadHook(Lv)}}Bv.extension={name:"prepare",type:Up.RendererSystem},Wp.add(Bv);function kv(t,e){const i=t;if(e instanceof tf){const t=e.source,s=0===t.width?i.canvas.width:Math.min(i.canvas.width,t.width),r=0===t.height?i.canvas.height:Math.min(i.canvas.height,t.height);return i.ctx.drawImage(t,0,0,s,r,0,0,i.canvas.width,i.canvas.height),!0}return!1}class Fv extends Ov{constructor(t){super(t),this.uploadHookHelper=this,this.canvas=Oh.ADAPTER.createCanvas(16,16),this.ctx=this.canvas.getContext("2d"),this.registerUploadHook(kv)}destroy(){super.destroy(),this.ctx=null,this.canvas=null}}Fv.extension={name:"prepare",type:Up.CanvasRendererSystem},Wp.add(Fv),Zg.prototype._tintedCanvas=null,Zg.prototype._renderCanvas=function(t){t.plugins.sprite.render(this)};const Dv=new Pf;class Uv{constructor(t){this.renderer=t}render(t){const e=t._texture,i=this.renderer,s=i.canvasContext.activeContext,r=i.canvasContext.activeResolution;if(!e.valid)return;const n=e._frame.width,o=e._frame.height;let a=e._frame.width,l=e._frame.height;e.trim&&(a=e.trim.width,l=e.trim.height);let h=t.transform.worldTransform,u=0,c=0;const d=e.baseTexture.getDrawableSource();if(e.orig.width<=0||e.orig.height<=0||!e.valid||!d)return;i.canvasContext.setBlendMode(t.blendMode,!0),s.globalAlpha=t.worldAlpha;const p=e.baseTexture.scaleMode===wh.LINEAR,f=i.canvasContext.smoothProperty;f&&s[f]!==p&&(s[f]=p),e.trim?(u=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,c=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(u=(.5-t.anchor.x)*e.orig.width,c=(.5-t.anchor.y)*e.orig.height),e.rotate&&(h.copyTo(Dv),h=Dv,Of.matrixAppendRotationInv(h,e.rotate,u,c),u=0,c=0),u-=a/2,c-=l/2,i.canvasContext.setContextTransform(h,t.roundPixels,1),t.roundPixels&&(u|=0,c|=0);const m=e.baseTexture.resolution,g=i.canvasContext._outerBlend;g&&(s.save(),s.beginPath(),s.rect(u*r,c*r,a*r,l*r),s.clip()),16777215!==t.tint?((t._cachedTint!==t.tintValue||t._tintedCanvas.tintId!==t._texture._updateID)&&(t._cachedTint=t.tintValue,t._tintedCanvas=yv.getTintedCanvas(t,t.tintValue)),s.drawImage(t._tintedCanvas,0,0,Math.floor(n*m),Math.floor(o*m),Math.floor(u*r),Math.floor(c*r),Math.floor(a*r),Math.floor(l*r))):s.drawImage(d,e._frame.x*m,e._frame.y*m,Math.floor(n*m),Math.floor(o*m),Math.floor(u*r),Math.floor(c*r),Math.floor(a*r),Math.floor(l*r)),g&&s.restore(),i.canvasContext.setBlendMode(mh.NORMAL)}destroy(){this.renderer=null}}Uv.extension={name:"sprite",type:Up.CanvasRendererPlugin},Wp.add(Uv);var Gv=Object.defineProperty,Xv=(t,e,i)=>(((t,e,i)=>{e in t?Gv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i})(t,"symbol"!=typeof e?e+"":e,i),i);let Wv=class{constructor(t){Xv(this,"parent"),Xv(this,"paused"),this.parent=t,this.paused=!1}destroy(){}down(t){return!1}move(t){return!1}up(t){return!1}wheel(t){return!1}update(t){}resize(){}reset(){}pause(){this.paused=!0}resume(){this.paused=!1}};var Yv,Hv=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$v={exports:{}};Yv=$v,function(){var t,e;e=t={linear:function(t,e,i,s){return i*t/s+e},easeInQuad:function(t,e,i,s){return i*(t/=s)*t+e},easeOutQuad:function(t,e,i,s){return-i*(t/=s)*(t-2)+e},easeInOutQuad:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,s){return i*(t/=s)*t*t+e},easeOutCubic:function(t,e,i,s){return i*((t=t/s-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,s){return i*(t/=s)*t*t*t+e},easeOutQuart:function(t,e,i,s){return-i*((t=t/s-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,s){return i*(t/=s)*t*t*t*t+e},easeOutQuint:function(t,e,i,s){return i*((t=t/s-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,s){return-i*Math.cos(t/s*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,s){return i*Math.sin(t/s*(Math.PI/2))+e},easeInOutSine:function(t,e,i,s){return-i/2*(Math.cos(Math.PI*t/s)-1)+e},easeInExpo:function(t,e,i,s){return 0===t?e:i*Math.pow(2,10*(t/s-1))+e},easeOutExpo:function(t,e,i,s){return t===s?e+i:i*(1-Math.pow(2,-10*t/s))+e},easeInOutExpo:function(t,e,i,s){return(t/=s/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,s){return-i*(Math.sqrt(1-(t/=s)*t)-1)+e},easeOutCirc:function(t,e,i,s){return i*Math.sqrt(1-(t=t/s-1)*t)+e},easeInOutCirc:function(t,e,i,s){return(t/=s/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),-r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)+e},easeOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),r*Math.pow(2,-10*t)*Math.sin((t*s-o)*(2*Math.PI)/n)+i+e},easeInOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s/2),(n=0)||(n=s*(.3*1.5)),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),t<1?r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*-.5+e:r*Math.pow(2,-10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*.5+i+e},easeInBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*(t/=s)*t*((r+1)*t-r)+e},easeOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*((t=t/s-1)*t*((r+1)*t+r)+1)+e},easeInOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),(t/=s/2)<1?i/2*(t*t*((1+(r*=1.525))*t-r))+e:i/2*((t-=2)*t*((1+(r*=1.525))*t+r)+2)+e},easeInBounce:function(e,i,s,r){return s-t.easeOutBounce(r-e,0,s,r)+i},easeOutBounce:function(t,e,i,s){return(t/=s)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e},easeInOutBounce:function(e,i,s,r){return e<r/2?.5*t.easeInBounce(2*e,0,s,r)+i:.5*t.easeOutBounce(2*e-r,0,s,r)+.5*s+i}},Yv.exports=e}.call(Hv);const jv=$v.exports;function zv(t,e){return t?"function"==typeof t?t:"string"==typeof t?jv[t]:void 0:jv[e]}const Vv={removeOnInterrupt:!1,ease:"linear",time:1e3};let qv=class extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"startX"),Xv(this,"startY"),Xv(this,"deltaX"),Xv(this,"deltaY"),Xv(this,"keepCenter"),Xv(this,"startWidth",null),Xv(this,"startHeight",null),Xv(this,"deltaWidth",null),Xv(this,"deltaHeight",null),Xv(this,"width",null),Xv(this,"height",null),Xv(this,"time",0),this.options=Object.assign({},Vv,e),this.options.ease=zv(this.options.ease),this.setupPosition(),this.setupZoom(),this.time=0}setupPosition(){typeof this.options.position<"u"?(this.startX=this.parent.center.x,this.startY=this.parent.center.y,this.deltaX=this.options.position.x-this.parent.center.x,this.deltaY=this.options.position.y-this.parent.center.y,this.keepCenter=!1):this.keepCenter=!0}setupZoom(){this.width=null,this.height=null,typeof this.options.scale<"u"?this.width=this.parent.screenWidth/this.options.scale:typeof this.options.scaleX<"u"||typeof this.options.scaleY<"u"?(typeof this.options.scaleX<"u"&&(this.width=this.parent.screenWidth/this.options.scaleX),typeof this.options.scaleY<"u"&&(this.height=this.parent.screenHeight/this.options.scaleY)):(typeof this.options.width<"u"&&(this.width=this.options.width),typeof this.options.height<"u"&&(this.height=this.options.height)),null!==this.width&&(this.startWidth=this.parent.screenWidthInWorldPixels,this.deltaWidth=this.width-this.startWidth),null!==this.height&&(this.startHeight=this.parent.screenHeightInWorldPixels,this.deltaHeight=this.height-this.startHeight)}down(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("animate"),!1}complete(){this.parent.plugins.remove("animate"),null!==this.width&&this.parent.fitWidth(this.width,this.keepCenter,null===this.height),null!==this.height&&this.parent.fitHeight(this.height,this.keepCenter,null===this.width),!this.keepCenter&&this.options.position&&this.parent.moveCenter(this.options.position),this.parent.emit("animate-end",this.parent),this.options.callbackOnComplete&&this.options.callbackOnComplete(this.parent)}update(t){if(this.paused)return;this.time+=t;const e=new gf(this.parent.scale.x,this.parent.scale.y);if(this.time>=this.options.time){const t=this.parent.width,i=this.parent.height;this.complete(),(t!==this.parent.width||i!==this.parent.height)&&this.parent.emit("zoomed",{viewport:this.parent,original:e,type:"animate"})}else{const t=this.options.ease(this.time,0,1,this.options.time);if(null!==this.width){const e=this.startWidth,i=this.deltaWidth;this.parent.fitWidth(e+i*t,this.keepCenter,null===this.height)}if(null!==this.height){const e=this.startHeight,i=this.deltaHeight;this.parent.fitHeight(e+i*t,this.keepCenter,null===this.width)}if(null===this.width?this.parent.scale.x=this.parent.scale.y:null===this.height&&(this.parent.scale.y=this.parent.scale.x),!this.keepCenter){const e=this.startX,i=this.startY,s=this.deltaX,r=this.deltaY,n=new gf(this.parent.x,this.parent.y);this.parent.moveCenter(e+s*t,i+r*t),this.parent.emit("moved",{viewport:this.parent,original:n,type:"animate"})}(this.width||this.height)&&this.parent.emit("zoomed",{viewport:this.parent,original:e,type:"animate"})}}};const Jv={sides:"all",friction:.5,time:150,ease:"easeInOutSine",underflow:"center",bounceBox:null};class Kv extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"left"),Xv(this,"top"),Xv(this,"right"),Xv(this,"bottom"),Xv(this,"underflowX"),Xv(this,"underflowY"),Xv(this,"ease"),Xv(this,"toX"),Xv(this,"toY"),this.options=Object.assign({},Jv,e),this.ease=zv(this.options.ease,"easeInOutSine"),this.options.sides?"all"===this.options.sides?this.top=this.bottom=this.left=this.right=!0:"horizontal"===this.options.sides?(this.right=this.left=!0,this.top=this.bottom=!1):"vertical"===this.options.sides?(this.left=this.right=!1,this.top=this.bottom=!0):(this.top=-1!==this.options.sides.indexOf("top"),this.bottom=-1!==this.options.sides.indexOf("bottom"),this.left=-1!==this.options.sides.indexOf("left"),this.right=-1!==this.options.sides.indexOf("right")):this.left=this.top=this.right=this.bottom=!1;const i=this.options.underflow.toLowerCase();"center"===i?(this.underflowX=0,this.underflowY=0):(this.underflowX=-1!==i.indexOf("left")?-1:-1!==i.indexOf("right")?1:0,this.underflowY=-1!==i.indexOf("top")?-1:-1!==i.indexOf("bottom")?1:0),this.reset()}isActive(){return null!==this.toX||null!==this.toY}down(){return this.toX=this.toY=null,!1}up(){return this.bounce(),!1}update(t){if(!this.paused){if(this.bounce(),this.toX){const e=this.toX;e.time+=t,this.parent.emit("moved",{viewport:this.parent,type:"bounce-x"}),e.time>=this.options.time?(this.parent.x=e.end,this.toX=null,this.parent.emit("bounce-x-end",this.parent)):this.parent.x=this.ease(e.time,e.start,e.delta,this.options.time)}if(this.toY){const e=this.toY;e.time+=t,this.parent.emit("moved",{viewport:this.parent,type:"bounce-y"}),e.time>=this.options.time?(this.parent.y=e.end,this.toY=null,this.parent.emit("bounce-y-end",this.parent)):this.parent.y=this.ease(e.time,e.start,e.delta,this.options.time)}}}calcUnderflowX(){let t;switch(this.underflowX){case-1:t=0;break;case 1:t=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:t=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}return t}calcUnderflowY(){let t;switch(this.underflowY){case-1:t=0;break;case 1:t=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:t=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}return t}oob(){const t=this.options.bounceBox;if(t){const e=typeof t.x>"u"?0:t.x,i=typeof t.y>"u"?0:t.y,s=typeof t.width>"u"?this.parent.worldWidth:t.width,r=typeof t.height>"u"?this.parent.worldHeight:t.height;return{left:this.parent.left<e,right:this.parent.right>s,top:this.parent.top<i,bottom:this.parent.bottom>r,topLeft:new gf(e*this.parent.scale.x,i*this.parent.scale.y),bottomRight:new gf(s*this.parent.scale.x-this.parent.screenWidth,r*this.parent.scale.y-this.parent.screenHeight)}}return{left:this.parent.left<0,right:this.parent.right>this.parent.worldWidth,top:this.parent.top<0,bottom:this.parent.bottom>this.parent.worldHeight,topLeft:new gf(0,0),bottomRight:new gf(this.parent.worldWidth*this.parent.scale.x-this.parent.screenWidth,this.parent.worldHeight*this.parent.scale.y-this.parent.screenHeight)}}bounce(){var t,e;if(this.paused)return;let i,s=this.parent.plugins.get("decelerate",!0);s&&(s.x||s.y)&&(s.x&&s.percentChangeX===(null==(t=s.options)?void 0:t.friction)||s.y&&s.percentChangeY===(null==(e=s.options)?void 0:e.friction))&&(i=this.oob(),(i.left&&this.left||i.right&&this.right)&&(s.percentChangeX=this.options.friction),(i.top&&this.top||i.bottom&&this.bottom)&&(s.percentChangeY=this.options.friction));const r=this.parent.plugins.get("drag",!0)||{},n=this.parent.plugins.get("pinch",!0)||{};if(s=s||{},!(null!=r&&r.active||null!=n&&n.active||this.toX&&this.toY||s.x&&s.y)){i=i||this.oob();const t=i.topLeft,e=i.bottomRight;if(!this.toX&&!s.x){let s=null;i.left&&this.left?s=this.parent.screenWorldWidth<this.parent.screenWidth?this.calcUnderflowX():-t.x:i.right&&this.right&&(s=this.parent.screenWorldWidth<this.parent.screenWidth?this.calcUnderflowX():-e.x),null!==s&&this.parent.x!==s&&(this.toX={time:0,start:this.parent.x,delta:s-this.parent.x,end:s},this.parent.emit("bounce-x-start",this.parent))}if(!this.toY&&!s.y){let s=null;i.top&&this.top?s=this.parent.screenWorldHeight<this.parent.screenHeight?this.calcUnderflowY():-t.y:i.bottom&&this.bottom&&(s=this.parent.screenWorldHeight<this.parent.screenHeight?this.calcUnderflowY():-e.y),null!==s&&this.parent.y!==s&&(this.toY={time:0,start:this.parent.y,delta:s-this.parent.y,end:s},this.parent.emit("bounce-y-start",this.parent))}}}reset(){this.toX=this.toY=null,this.bounce()}}const Zv={left:!1,right:!1,top:!1,bottom:!1,direction:null,underflow:"center"};class Qv extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"last"),Xv(this,"noUnderflow"),Xv(this,"underflowX"),Xv(this,"underflowY"),this.options=Object.assign({},Zv,e),this.options.direction&&(this.options.left="x"===this.options.direction||"all"===this.options.direction||null,this.options.right="x"===this.options.direction||"all"===this.options.direction||null,this.options.top="y"===this.options.direction||"all"===this.options.direction||null,this.options.bottom="y"===this.options.direction||"all"===this.options.direction||null),this.parseUnderflow(),this.last={x:null,y:null,scaleX:null,scaleY:null},this.update()}parseUnderflow(){const t=this.options.underflow.toLowerCase();"none"===t?this.noUnderflow=!0:"center"===t?(this.underflowX=this.underflowY=0,this.noUnderflow=!1):(this.underflowX=-1!==t.indexOf("left")?-1:-1!==t.indexOf("right")?1:0,this.underflowY=-1!==t.indexOf("top")?-1:-1!==t.indexOf("bottom")?1:0,this.noUnderflow=!1)}move(){return this.update(),!1}update(){if(this.paused||this.parent.x===this.last.x&&this.parent.y===this.last.y&&this.parent.scale.x===this.last.scaleX&&this.parent.scale.y===this.last.scaleY)return;const t=new gf(this.parent.x,this.parent.y),e=this.parent.plugins.decelerate||{};if(null!==this.options.left||null!==this.options.right){let i=!1;if(!this.noUnderflow&&this.parent.screenWorldWidth<this.parent.screenWidth)switch(this.underflowX){case-1:0!==this.parent.x&&(this.parent.x=0,i=!0);break;case 1:this.parent.x!==this.parent.screenWidth-this.parent.screenWorldWidth&&(this.parent.x=this.parent.screenWidth-this.parent.screenWorldWidth,i=!0);break;default:this.parent.x!==(this.parent.screenWidth-this.parent.screenWorldWidth)/2&&(this.parent.x=(this.parent.screenWidth-this.parent.screenWorldWidth)/2,i=!0)}else null!==this.options.left&&this.parent.left<(!0===this.options.left?0:this.options.left)&&(this.parent.x=-(!0===this.options.left?0:this.options.left)*this.parent.scale.x,e.x=0,i=!0),null!==this.options.right&&this.parent.right>(!0===this.options.right?this.parent.worldWidth:this.options.right)&&(this.parent.x=-(!0===this.options.right?this.parent.worldWidth:this.options.right)*this.parent.scale.x+this.parent.screenWidth,e.x=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-x"})}if(null!==this.options.top||null!==this.options.bottom){let i=!1;if(!this.noUnderflow&&this.parent.screenWorldHeight<this.parent.screenHeight)switch(this.underflowY){case-1:0!==this.parent.y&&(this.parent.y=0,i=!0);break;case 1:this.parent.y!==this.parent.screenHeight-this.parent.screenWorldHeight&&(this.parent.y=this.parent.screenHeight-this.parent.screenWorldHeight,i=!0);break;default:this.parent.y!==(this.parent.screenHeight-this.parent.screenWorldHeight)/2&&(this.parent.y=(this.parent.screenHeight-this.parent.screenWorldHeight)/2,i=!0)}else null!==this.options.top&&this.parent.top<(!0===this.options.top?0:this.options.top)&&(this.parent.y=-(!0===this.options.top?0:this.options.top)*this.parent.scale.y,e.y=0,i=!0),null!==this.options.bottom&&this.parent.bottom>(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)&&(this.parent.y=-(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)*this.parent.scale.y+this.parent.screenHeight,e.y=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-y"})}this.last.x=this.parent.x,this.last.y=this.parent.y,this.last.scaleX=this.parent.scale.x,this.last.scaleY=this.parent.scale.y}reset(){this.update()}}const tx={minWidth:null,minHeight:null,maxWidth:null,maxHeight:null,minScale:null,maxScale:null};class ex extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),this.options=Object.assign({},tx,e),this.clamp()}resize(){this.clamp()}clamp(){if(!this.paused)if(this.options.minWidth||this.options.minHeight||this.options.maxWidth||this.options.maxHeight){let t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight;if(null!==this.options.minWidth&&t<this.options.minWidth){const i=this.parent.scale.x;this.parent.fitWidth(this.options.minWidth,!1,!1,!0),this.parent.scale.y*=this.parent.scale.x/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.maxWidth&&t>this.options.maxWidth){const i=this.parent.scale.x;this.parent.fitWidth(this.options.maxWidth,!1,!1,!0),this.parent.scale.y*=this.parent.scale.x/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.minHeight&&e<this.options.minHeight){const i=this.parent.scale.y;this.parent.fitHeight(this.options.minHeight,!1,!1,!0),this.parent.scale.x*=this.parent.scale.y/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.maxHeight&&e>this.options.maxHeight){const t=this.parent.scale.y;this.parent.fitHeight(this.options.maxHeight,!1,!1,!0),this.parent.scale.x*=this.parent.scale.y/t,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}}else if(this.options.minScale||this.options.maxScale){const t={x:null,y:null},e={x:null,y:null};if("number"==typeof this.options.minScale)t.x=this.options.minScale,t.y=this.options.minScale;else if(null!==this.options.minScale){const e=this.options.minScale;t.x=typeof e.x>"u"?null:e.x,t.y=typeof e.y>"u"?null:e.y}if("number"==typeof this.options.maxScale)e.x=this.options.maxScale,e.y=this.options.maxScale;else if(null!==this.options.maxScale){const t=this.options.maxScale;e.x=typeof t.x>"u"?null:t.x,e.y=typeof t.y>"u"?null:t.y}let i=this.parent.scale.x,s=this.parent.scale.y;null!==t.x&&i<t.x&&(i=t.x),null!==e.x&&i>e.x&&(i=e.x),null!==t.y&&s<t.y&&(s=t.y),null!==e.y&&s>e.y&&(s=e.y),(i!==this.parent.scale.x||s!==this.parent.scale.y)&&(this.parent.scale.set(i,s),this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"}))}}reset(){this.clamp()}}const ix={friction:.98,bounce:.8,minSpeed:.01},sx=16;class rx extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"x"),Xv(this,"y"),Xv(this,"percentChangeX"),Xv(this,"percentChangeY"),Xv(this,"saved"),Xv(this,"timeSinceRelease"),this.options=Object.assign({},ix,e),this.saved=[],this.timeSinceRelease=0,this.reset(),this.parent.on("moved",t=>this.handleMoved(t))}down(){return this.saved=[],this.x=this.y=null,!1}isActive(){return!(!this.x&&!this.y)}move(){if(this.paused)return!1;const t=this.parent.input.count();return(1===t||t>1&&!this.parent.plugins.get("pinch",!0))&&(this.saved.push({x:this.parent.x,y:this.parent.y,time:performance.now()}),this.saved.length>60&&this.saved.splice(0,30)),!1}handleMoved(t){if(this.saved.length){const e=this.saved[this.saved.length-1];"clamp-x"===t.type&&t.original?e.x===t.original.x&&(e.x=this.parent.x):"clamp-y"===t.type&&t.original&&e.y===t.original.y&&(e.y=this.parent.y)}}up(){if(0===this.parent.input.count()&&this.saved.length){const t=performance.now();for(const e of this.saved)if(e.time>=t-100){const i=t-e.time;this.x=(this.parent.x-e.x)/i,this.y=(this.parent.y-e.y)/i,this.percentChangeX=this.percentChangeY=this.options.friction,this.timeSinceRelease=0;break}}return!1}activate(t){typeof(t=t||{}).x<"u"&&(this.x=t.x,this.percentChangeX=this.options.friction),typeof t.y<"u"&&(this.y=t.y,this.percentChangeY=this.options.friction)}update(t){if(this.paused)return;const e=this.x||this.y,i=this.timeSinceRelease,s=this.timeSinceRelease+t;if(this.x){const e=this.percentChangeX,r=Math.log(e);this.parent.x+=this.x*sx/r*(Math.pow(e,s/sx)-Math.pow(e,i/sx)),this.x*=Math.pow(this.percentChangeX,t/sx)}if(this.y){const e=this.percentChangeY,r=Math.log(e);this.parent.y+=this.y*sx/r*(Math.pow(e,s/sx)-Math.pow(e,i/sx)),this.y*=Math.pow(this.percentChangeY,t/sx)}this.timeSinceRelease+=t,this.x&&this.y?Math.abs(this.x)<this.options.minSpeed&&Math.abs(this.y)<this.options.minSpeed&&(this.x=0,this.y=0):(Math.abs(this.x||0)<this.options.minSpeed&&(this.x=0),Math.abs(this.y||0)<this.options.minSpeed&&(this.y=0)),e&&this.parent.emit("moved",{viewport:this.parent,type:"decelerate"})}reset(){this.x=this.y=null}}const nx={direction:"all",pressDrag:!0,wheel:!0,wheelScroll:1,reverse:!1,clampWheel:!1,underflow:"center",factor:1,mouseButtons:"all",keyToPress:null,ignoreKeyToPressOnTouch:!1,lineHeight:20,wheelSwapAxes:!1};class ox extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"moved"),Xv(this,"reverse"),Xv(this,"xDirection"),Xv(this,"yDirection"),Xv(this,"keyIsPressed"),Xv(this,"mouse"),Xv(this,"underflowX"),Xv(this,"underflowY"),Xv(this,"last"),Xv(this,"current"),Xv(this,"windowEventHandlers",[]),this.options=Object.assign({},nx,e),this.moved=!1,this.reverse=this.options.reverse?1:-1,this.xDirection=!this.options.direction||"all"===this.options.direction||"x"===this.options.direction,this.yDirection=!this.options.direction||"all"===this.options.direction||"y"===this.options.direction,this.keyIsPressed=!1,this.parseUnderflow(),this.mouseButtons(this.options.mouseButtons),this.options.keyToPress&&this.handleKeyPresses(this.options.keyToPress)}handleKeyPresses(t){this.addWindowEventHandler("keyup",e=>{t.includes(e.code)&&(this.keyIsPressed=!1)}),this.addWindowEventHandler("keydown",e=>{t.includes(e.code)&&(this.keyIsPressed=!0)})}addWindowEventHandler(t,e){window.addEventListener(t,e),this.windowEventHandlers.push({event:t,handler:e})}destroy(){this.windowEventHandlers.forEach(({event:t,handler:e})=>{window.removeEventListener(t,e)})}mouseButtons(t){this.mouse=t&&"all"!==t?[-1!==t.indexOf("left"),-1!==t.indexOf("middle"),-1!==t.indexOf("right")]:[!0,!0,!0]}parseUnderflow(){const t=this.options.underflow.toLowerCase();"center"===t?(this.underflowX=0,this.underflowY=0):(t.includes("left")?this.underflowX=-1:t.includes("right")?this.underflowX=1:this.underflowX=0,t.includes("top")?this.underflowY=-1:t.includes("bottom")?this.underflowY=1:this.underflowY=0)}checkButtons(t){const e="mouse"===t.pointerType,i=this.parent.input.count();return!(!(1===i||i>1&&!this.parent.plugins.get("pinch",!0))||e&&!this.mouse[t.button])}checkKeyPress(t){return!this.options.keyToPress||this.keyIsPressed||this.options.ignoreKeyToPressOnTouch&&"touch"===t.data.pointerType}down(t){return!(this.paused||!this.options.pressDrag)&&(this.checkButtons(t)&&this.checkKeyPress(t)?(this.last={x:t.global.x,y:t.global.y},this.current=t.pointerId,!0):(this.last=null,!1))}get active(){return this.moved}move(t){if(this.paused||!this.options.pressDrag)return!1;if(this.last&&this.current===t.data.pointerId){const e=t.global.x,i=t.global.y,s=this.parent.input.count();if(1===s||s>1&&!this.parent.plugins.get("pinch",!0)){const s=e-this.last.x,r=i-this.last.y;if(this.moved||this.xDirection&&this.parent.input.checkThreshold(s)||this.yDirection&&this.parent.input.checkThreshold(r)){const s={x:e,y:i};return this.xDirection&&(this.parent.x+=(s.x-this.last.x)*this.options.factor),this.yDirection&&(this.parent.y+=(s.y-this.last.y)*this.options.factor),this.last=s,this.moved||this.parent.emit("drag-start",{event:t,screen:new gf(this.last.x,this.last.y),world:this.parent.toWorld(new gf(this.last.x,this.last.y)),viewport:this.parent}),this.moved=!0,this.parent.emit("moved",{viewport:this.parent,type:"drag"}),!0}}else this.moved=!1}return!1}up(t){if(this.paused)return!1;const e=this.parent.input.touches;if(1===e.length){const t=e[0];return t.last&&(this.last={x:t.last.x,y:t.last.y},this.current=t.id),this.moved=!1,!0}if(this.last&&this.moved){const e=new gf(this.last.x,this.last.y);return this.parent.emit("drag-end",{event:t,screen:e,world:this.parent.toWorld(e),viewport:this.parent}),this.last=null,this.moved=!1,!0}return!1}wheel(t){if(this.paused)return!1;if(this.options.wheel){const e=this.parent.plugins.get("wheel",!0);if(!e||!e.options.wheelZoom&&!t.ctrlKey){const e=t.deltaMode?this.options.lineHeight:1,i=[t.deltaX,t.deltaY],[s,r]=this.options.wheelSwapAxes?i.reverse():i;return this.xDirection&&(this.parent.x+=s*e*this.options.wheelScroll*this.reverse),this.yDirection&&(this.parent.y+=r*e*this.options.wheelScroll*this.reverse),this.options.clampWheel&&this.clamp(),this.parent.emit("wheel-scroll",this.parent),this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.options.passiveWheel||t.preventDefault(),this.parent.options.stopPropagation&&t.stopPropagation(),!0}}return!1}resume(){this.last=null,this.paused=!1}clamp(){const t=this.parent.plugins.get("decelerate",!0)||{};if("y"!==this.options.clampWheel)if(this.parent.screenWorldWidth<this.parent.screenWidth)switch(this.underflowX){case-1:this.parent.x=0;break;case 1:this.parent.x=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:this.parent.x=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}else this.parent.left<0?(this.parent.x=0,t.x=0):this.parent.right>this.parent.worldWidth&&(this.parent.x=-this.parent.worldWidth*this.parent.scale.x+this.parent.screenWidth,t.x=0);if("x"!==this.options.clampWheel)if(this.parent.screenWorldHeight<this.parent.screenHeight)switch(this.underflowY){case-1:this.parent.y=0;break;case 1:this.parent.y=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:this.parent.y=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}else this.parent.top<0&&(this.parent.y=0,t.y=0),this.parent.bottom>this.parent.worldHeight&&(this.parent.y=-this.parent.worldHeight*this.parent.scale.y+this.parent.screenHeight,t.y=0)}}const ax={speed:0,acceleration:null,radius:null};class lx extends Wv{constructor(t,e,i={}){super(t),Xv(this,"options"),Xv(this,"target"),Xv(this,"velocity"),this.target=e,this.options=Object.assign({},ax,i),this.velocity={x:0,y:0}}update(t){if(this.paused)return;const e=this.parent.center;let i=this.target.x,s=this.target.y;if(this.options.radius){if(!(Math.sqrt(Math.pow(this.target.y-e.y,2)+Math.pow(this.target.x-e.x,2))>this.options.radius))return;{const t=Math.atan2(this.target.y-e.y,this.target.x-e.x);i=this.target.x-Math.cos(t)*this.options.radius,s=this.target.y-Math.sin(t)*this.options.radius}}const r=i-e.x,n=s-e.y;if(r||n)if(this.options.speed)if(this.options.acceleration){const t=Math.atan2(s-e.y,i-e.x),o=Math.sqrt(Math.pow(r,2)+Math.pow(n,2));if(o){const a=(Math.pow(this.velocity.x,2)+Math.pow(this.velocity.y,2))/(2*this.options.acceleration);this.velocity=o>a?{x:Math.min(this.velocity.x+(this.options.acceleration,this.options.speed)),y:Math.min(this.velocity.y+(this.options.acceleration,this.options.speed))}:{x:Math.max(this.velocity.x-this.options.acceleration*this.options.speed,0),y:Math.max(this.velocity.y-this.options.acceleration*this.options.speed,0)};const l=Math.cos(t)*this.velocity.x,h=Math.sin(t)*this.velocity.y,u=Math.abs(l)>Math.abs(r)?i:e.x+l,c=Math.abs(h)>Math.abs(n)?s:e.y+h;this.parent.moveCenter(u,c),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}else{const t=Math.atan2(s-e.y,i-e.x),o=Math.cos(t)*this.options.speed,a=Math.sin(t)*this.options.speed,l=Math.abs(o)>Math.abs(r)?i:e.x+o,h=Math.abs(a)>Math.abs(n)?s:e.y+a;this.parent.moveCenter(l,h),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}else this.parent.moveCenter(i,s),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}const hx={radius:null,distance:null,top:null,bottom:null,left:null,right:null,speed:8,reverse:!1,noDecelerate:!1,linear:!1,allowButtons:!1};let ux=class extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"reverse"),Xv(this,"radiusSquared"),Xv(this,"left"),Xv(this,"top"),Xv(this,"right"),Xv(this,"bottom"),Xv(this,"horizontal"),Xv(this,"vertical"),this.options=Object.assign({},hx,e),this.reverse=this.options.reverse?1:-1,this.radiusSquared="number"==typeof this.options.radius?Math.pow(this.options.radius,2):null,this.resize()}resize(){const t=this.options.distance;null!==t?(this.left=t,this.top=t,this.right=this.parent.screenWidth-t,this.bottom=this.parent.screenHeight-t):this.options.radius||(this.left=this.options.left,this.top=this.options.top,this.right=null===this.options.right?null:this.parent.screenWidth-this.options.right,this.bottom=null===this.options.bottom?null:this.parent.screenHeight-this.options.bottom)}down(){return this.paused||this.options.allowButtons||(this.horizontal=this.vertical=null),!1}move(t){if(this.paused||"mouse"!==t.pointerType&&1!==t.pointerId||!this.options.allowButtons&&0!==t.buttons)return!1;const e=t.global.x,i=t.global.y;if(this.radiusSquared){const t=this.parent.toScreen(this.parent.center);if(Math.pow(t.x-e,2)+Math.pow(t.y-i,2)>=this.radiusSquared){const s=Math.atan2(t.y-i,t.x-e);this.options.linear?(this.horizontal=Math.round(Math.cos(s))*this.options.speed*this.reverse*.06,this.vertical=Math.round(Math.sin(s))*this.options.speed*this.reverse*.06):(this.horizontal=Math.cos(s)*this.options.speed*this.reverse*.06,this.vertical=Math.sin(s)*this.options.speed*this.reverse*.06)}else this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=0}else null!==this.left&&e<this.left?this.horizontal=Number(this.reverse)*this.options.speed*.06:null!==this.right&&e>this.right?this.horizontal=-1*this.reverse*this.options.speed*.06:(this.decelerateHorizontal(),this.horizontal=0),null!==this.top&&i<this.top?this.vertical=Number(this.reverse)*this.options.speed*.06:null!==this.bottom&&i>this.bottom?this.vertical=-1*this.reverse*this.options.speed*.06:(this.decelerateVertical(),this.vertical=0);return!1}decelerateHorizontal(){const t=this.parent.plugins.get("decelerate",!0);this.horizontal&&t&&!this.options.noDecelerate&&t.activate({x:this.horizontal*this.options.speed*this.reverse/(1e3/60)})}decelerateVertical(){const t=this.parent.plugins.get("decelerate",!0);this.vertical&&t&&!this.options.noDecelerate&&t.activate({y:this.vertical*this.options.speed*this.reverse/(1e3/60)})}up(){return this.paused||(this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=null),!1}update(){if(!this.paused&&(this.horizontal||this.vertical)){const t=this.parent.center;this.horizontal&&(t.x+=this.horizontal*this.options.speed),this.vertical&&(t.y+=this.vertical*this.options.speed),this.parent.moveCenter(t),this.parent.emit("moved",{viewport:this.parent,type:"mouse-edges"})}}};const cx={noDrag:!1,percent:1,center:null,factor:1,axis:"all"};class dx extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"active",!1),Xv(this,"pinching",!1),Xv(this,"moved",!1),Xv(this,"lastCenter"),this.options=Object.assign({},cx,e)}down(){return this.parent.input.count()>=2&&(this.active=!0,!0)}isAxisX(){return["all","x"].includes(this.options.axis)}isAxisY(){return["all","y"].includes(this.options.axis)}move(t){if(this.paused||!this.active)return!1;const e=t.global.x,i=t.global.y,s=this.parent.input.touches;if(s.length>=2){const r=s[0],n=s[1],o=r.last&&n.last?Math.sqrt(Math.pow(n.last.x-r.last.x,2)+Math.pow(n.last.y-r.last.y,2)):null;if(r.id===t.pointerId?r.last={x:e,y:i,data:t}:n.id===t.pointerId&&(n.last={x:e,y:i,data:t}),o){let t;const e=new gf(r.last.x+(n.last.x-r.last.x)/2,r.last.y+(n.last.y-r.last.y)/2);this.options.center||(t=this.parent.toLocal(e));let i=Math.sqrt(Math.pow(n.last.x-r.last.x,2)+Math.pow(n.last.y-r.last.y,2));i=0===i?i=1e-10:i;const s=(1-o/i)*this.options.percent*(this.isAxisX()?this.parent.scale.x:this.parent.scale.y);this.isAxisX()&&(this.parent.scale.x+=s),this.isAxisY()&&(this.parent.scale.y+=s),this.parent.emit("zoomed",{viewport:this.parent,type:"pinch",center:e});const a=this.parent.plugins.get("clamp-zoom",!0);if(a&&a.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=(e.x-i.x)*this.options.factor,this.parent.y+=(e.y-i.y)*this.options.factor,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})}!this.options.noDrag&&this.lastCenter&&(this.parent.x+=(e.x-this.lastCenter.x)*this.options.factor,this.parent.y+=(e.y-this.lastCenter.y)*this.options.factor,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})),this.lastCenter=e,this.moved=!0}else this.pinching||(this.parent.emit("pinch-start",this.parent),this.pinching=!0);return!0}return!1}up(){return!!(this.pinching&&this.parent.input.touches.length<=1)&&(this.active=!1,this.lastCenter=null,this.pinching=!1,this.moved=!1,this.parent.emit("pinch-end",this.parent),!0)}}const px={topLeft:!1,friction:.8,time:1e3,ease:"easeInOutSine",interrupt:!0,removeOnComplete:!1,removeOnInterrupt:!1,forceStart:!1};class fx extends Wv{constructor(t,e,i,s={}){super(t),Xv(this,"options"),Xv(this,"ease"),Xv(this,"x"),Xv(this,"y"),Xv(this,"percent"),Xv(this,"snapping"),Xv(this,"deltaX"),Xv(this,"deltaY"),Xv(this,"startX"),Xv(this,"startY"),this.options=Object.assign({},px,s),this.ease=zv(s.ease,"easeInOutSine"),this.x=e,this.y=i,this.options.forceStart&&this.snapStart()}snapStart(){this.percent=0,this.snapping={time:0};const t=this.options.topLeft?this.parent.corner:this.parent.center;this.deltaX=this.x-t.x,this.deltaY=this.y-t.y,this.startX=t.x,this.startY=t.y,this.parent.emit("snap-start",this.parent)}wheel(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("snap"),!1}down(){return this.options.removeOnInterrupt?this.parent.plugins.remove("snap"):this.options.interrupt&&(this.snapping=null),!1}up(){if(0===this.parent.input.count()){const t=this.parent.plugins.get("decelerate",!0);t&&(t.x||t.y)&&(t.percentChangeX=t.percentChangeY=this.options.friction)}return!1}update(t){if(!(this.paused||this.options.interrupt&&0!==this.parent.input.count()))if(this.snapping){const e=this.snapping;let i,s,r;e.time+=t;const n=this.startX,o=this.startY,a=this.deltaX,l=this.deltaY;if(e.time>this.options.time)i=!0,s=n+a,r=o+l;else{const t=this.ease(e.time,0,1,this.options.time);s=n+a*t,r=o+l*t}this.options.topLeft?this.parent.moveCorner(s,r):this.parent.moveCenter(s,r),this.parent.emit("moved",{viewport:this.parent,type:"snap"}),i&&(this.options.removeOnComplete&&this.parent.plugins.remove("snap"),this.parent.emit("snap-end",this.parent),this.snapping=null)}else{const t=this.options.topLeft?this.parent.corner:this.parent.center;(t.x!==this.x||t.y!==this.y)&&this.snapStart()}}}const mx={width:0,height:0,time:1e3,ease:"easeInOutSine",center:null,interrupt:!0,removeOnComplete:!1,removeOnInterrupt:!1,forceStart:!1,noMove:!1};class gx extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"ease"),Xv(this,"xScale"),Xv(this,"yScale"),Xv(this,"xIndependent"),Xv(this,"yIndependent"),Xv(this,"snapping"),this.options=Object.assign({},mx,e),this.ease=zv(this.options.ease),this.xIndependent=!1,this.yIndependent=!1,this.xScale=0,this.yScale=0,this.options.width>0&&(this.xScale=t.screenWidth/this.options.width,this.xIndependent=!0),this.options.height>0&&(this.yScale=t.screenHeight/this.options.height,this.yIndependent=!0),this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale,0===this.options.time?(t.container.scale.x=this.xScale,t.container.scale.y=this.yScale,this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom")):e.forceStart&&this.createSnapping()}createSnapping(){const t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,i=this.parent.screenWidth/this.xScale,s=this.parent.screenHeight/this.yScale;this.snapping={time:0,startX:t,startY:e,deltaX:i-t,deltaY:s-e},this.parent.emit("snap-zoom-start",this.parent)}resize(){this.snapping=null,this.options.width>0&&(this.xScale=this.parent.screenWidth/this.options.width),this.options.height>0&&(this.yScale=this.parent.screenHeight/this.options.height),this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale}wheel(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("snap-zoom"),!1}down(){return this.options.removeOnInterrupt?this.parent.plugins.remove("snap-zoom"):this.options.interrupt&&(this.snapping=null),!1}update(t){if(this.paused||this.options.interrupt&&0!==this.parent.input.count())return;let e;if(!this.options.center&&!this.options.noMove&&(e=this.parent.center),this.snapping){if(this.snapping){const i=this.snapping;if(i.time+=t,i.time>=this.options.time)this.parent.scale.set(this.xScale,this.yScale),this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom"),this.parent.emit("snap-zoom-end",this.parent),this.snapping=null;else{const t=this.snapping,e=this.ease(t.time,t.startX,t.deltaX,this.options.time),i=this.ease(t.time,t.startY,t.deltaY,this.options.time);this.parent.scale.x=this.parent.screenWidth/e,this.parent.scale.y=this.parent.screenHeight/i}const s=this.parent.plugins.get("clamp-zoom",!0);s&&s.clamp(),this.options.noMove||(this.options.center?this.parent.moveCenter(this.options.center):this.parent.moveCenter(e))}}else(this.parent.scale.x!==this.xScale||this.parent.scale.y!==this.yScale)&&this.createSnapping()}resume(){this.snapping=null,super.resume()}}const yx={percent:.1,smooth:!1,interrupt:!0,reverse:!1,center:null,lineHeight:20,axis:"all",keyToPress:null,trackpadPinch:!1,wheelZoom:!0};class vx extends Wv{constructor(t,e={}){super(t),Xv(this,"options"),Xv(this,"smoothing"),Xv(this,"smoothingCenter"),Xv(this,"smoothingCount"),Xv(this,"keyIsPressed"),this.options=Object.assign({},yx,e),this.keyIsPressed=!1,this.options.keyToPress&&this.handleKeyPresses(this.options.keyToPress)}handleKeyPresses(t){window.addEventListener("keydown",e=>{t.includes(e.code)&&(this.keyIsPressed=!0)}),window.addEventListener("keyup",e=>{t.includes(e.code)&&(this.keyIsPressed=!1)})}checkKeyPress(){return!this.options.keyToPress||this.keyIsPressed}down(){return this.options.interrupt&&(this.smoothing=null),!1}isAxisX(){return["all","x"].includes(this.options.axis)}isAxisY(){return["all","y"].includes(this.options.axis)}update(){if(this.smoothing){const t=this.smoothingCenter,e=this.smoothing;let i;this.options.center||(i=this.parent.toLocal(t)),this.isAxisX()&&(this.parent.scale.x+=e.x),this.isAxisY()&&(this.parent.scale.y+=e.y),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const s=this.parent.plugins.get("clamp-zoom",!0);if(s&&s.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const e=this.parent.toGlobal(i);this.parent.x+=t.x-e.x,this.parent.y+=t.y-e.y}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.smoothingCount++,this.smoothingCount>=this.options.smooth&&(this.smoothing=null)}}pinch(t){if(this.paused)return;const e=this.parent.input.getPointerPosition(t),i=-t.deltaY*(t.deltaMode?this.options.lineHeight:1)/200,s=Math.pow(2,(1+this.options.percent)*i);let r;this.options.center||(r=this.parent.toLocal(e)),this.isAxisX()&&(this.parent.scale.x*=s),this.isAxisY()&&(this.parent.scale.y*=s),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const n=this.parent.plugins.get("clamp-zoom",!0);if(n&&n.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const t=this.parent.toGlobal(r);this.parent.x+=e.x-t.x,this.parent.y+=e.y-t.y}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.emit("wheel-start",{event:t,viewport:this.parent})}wheel(t){if(this.paused||!this.checkKeyPress())return!1;if(t.ctrlKey&&this.options.trackpadPinch)this.pinch(t);else if(this.options.wheelZoom){const e=this.parent.input.getPointerPosition(t),i=(this.options.reverse?-1:1)*-t.deltaY*(t.deltaMode?this.options.lineHeight:1)/500,s=Math.pow(2,(1+this.options.percent)*i);if(this.options.smooth){const t={x:this.smoothing?this.smoothing.x*(this.options.smooth-this.smoothingCount):0,y:this.smoothing?this.smoothing.y*(this.options.smooth-this.smoothingCount):0};this.smoothing={x:((this.parent.scale.x+t.x)*s-this.parent.scale.x)/this.options.smooth,y:((this.parent.scale.y+t.y)*s-this.parent.scale.y)/this.options.smooth},this.smoothingCount=0,this.smoothingCenter=e}else{let t;this.options.center||(t=this.parent.toLocal(e)),this.isAxisX()&&(this.parent.scale.x*=s),this.isAxisY()&&(this.parent.scale.y*=s),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const i=this.parent.plugins.get("clamp-zoom",!0);if(i&&i.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=e.x-i.x,this.parent.y+=e.y-i.y}}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.emit("wheel-start",{event:t,viewport:this.parent})}return!this.parent.options.passiveWheel}}let xx=class{constructor(t){Xv(this,"viewport"),Xv(this,"clickedAvailable"),Xv(this,"isMouseDown"),Xv(this,"last"),Xv(this,"wheelFunction"),Xv(this,"touches"),this.viewport=t,this.touches=[],this.addListeners()}addListeners(){this.viewport.eventMode="static",this.viewport.forceHitArea||(this.viewport.hitArea=new vf(0,0,this.viewport.worldWidth,this.viewport.worldHeight)),this.viewport.on("pointerdown",this.down,this),this.viewport.options.allowPreserveDragOutside?this.viewport.on("globalpointermove",this.move,this):this.viewport.on("pointermove",this.move,this),this.viewport.on("pointerup",this.up,this),this.viewport.on("pointerupoutside",this.up,this),this.viewport.on("pointercancel",this.up,this),this.viewport.options.allowPreserveDragOutside||this.viewport.on("pointerleave",this.up,this),this.wheelFunction=t=>this.handleWheel(t),this.viewport.options.events.domElement.addEventListener("wheel",this.wheelFunction,{passive:this.viewport.options.passiveWheel}),this.isMouseDown=!1}destroy(){this.viewport.options.events.domElement.removeEventListener("wheel",this.wheelFunction)}down(t){if(!this.viewport.pause&&this.viewport.worldVisible){if("mouse"===t.pointerType?this.isMouseDown=!0:this.get(t.pointerId)||this.touches.push({id:t.pointerId,last:null}),1===this.count()){this.last=t.global.clone();const e=this.viewport.plugins.get("decelerate",!0),i=this.viewport.plugins.get("bounce",!0);e&&e.isActive()||i&&i.isActive()?this.clickedAvailable=!1:this.clickedAvailable=!0}else this.clickedAvailable=!1;this.viewport.plugins.down(t)&&this.viewport.options.stopPropagation&&t.stopPropagation()}}clear(){this.isMouseDown=!1,this.touches=[],this.last=null}checkThreshold(t){return Math.abs(t)>=this.viewport.threshold}move(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.plugins.move(t);if(this.clickedAvailable&&this.last){const e=t.global.x-this.last.x,i=t.global.y-this.last.y;(this.checkThreshold(e)||this.checkThreshold(i))&&(this.clickedAvailable=!1)}e&&this.viewport.options.stopPropagation&&t.stopPropagation()}up(t){if(this.viewport.pause||!this.viewport.worldVisible)return;"mouse"===t.pointerType&&(this.isMouseDown=!1),"mouse"!==t.pointerType&&this.remove(t.pointerId);const e=this.viewport.plugins.up(t);this.clickedAvailable&&0===this.count()&&this.last&&(this.viewport.emit("clicked",{event:t,screen:this.last,world:this.viewport.toWorld(this.last),viewport:this.viewport}),this.clickedAvailable=!1),e&&this.viewport.options.stopPropagation&&t.stopPropagation()}getPointerPosition(t){const e=new gf;return this.viewport.options.events.mapPositionToPoint(e,t.clientX,t.clientY),e}handleWheel(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.toLocal(this.getPointerPosition(t));this.viewport.left<=e.x&&e.x<=this.viewport.right&&this.viewport.top<=e.y&&e.y<=this.viewport.bottom&&this.viewport.plugins.wheel(t)&&!this.viewport.options.passiveWheel&&t.preventDefault()}pause(){this.touches=[],this.isMouseDown=!1}get(t){for(const e of this.touches)if(e.id===t)return e;return null}remove(t){for(let e=0;e<this.touches.length;e++)if(this.touches[e].id===t)return void this.touches.splice(e,1)}count(){return(this.isMouseDown?1:0)+this.touches.length}};const bx=["drag","pinch","wheel","follow","mouse-edges","decelerate","animate","bounce","snap-zoom","clamp-zoom","snap","clamp"];class wx{constructor(t){Xv(this,"plugins"),Xv(this,"list"),Xv(this,"viewport"),this.viewport=t,this.list=[],this.plugins={}}add(t,e,i=bx.length){const s=this.plugins[t];s&&s.destroy(),this.plugins[t]=e;const r=bx.indexOf(t);-1!==r&&bx.splice(r,1),bx.splice(i,0,t),this.sort()}get(t,e){var i;return e&&null!=(i=this.plugins[t])&&i.paused?null:this.plugins[t]}update(t){for(const e of this.list)e.update(t)}resize(){for(const t of this.list)t.resize()}reset(){for(const t of this.list)t.reset()}removeAll(){this.list.forEach(t=>{t.destroy()}),this.plugins={},this.sort()}remove(t){var e;this.plugins[t]&&(null==(e=this.plugins[t])||e.destroy(),delete this.plugins[t],this.viewport.emit("plugin-remove",t),this.sort())}pause(t){var e;null==(e=this.plugins[t])||e.pause()}resume(t){var e;null==(e=this.plugins[t])||e.resume()}sort(){this.list=[];for(const t of bx)this.plugins[t]&&this.list.push(this.plugins[t])}down(t){let e=!1;for(const i of this.list)i.down(t)&&(e=!0);return e}move(t){let e=!1;for(const i of this.viewport.plugins.list)i.move(t)&&(e=!0);return e}up(t){let e=!1;for(const i of this.list)i.up(t)&&(e=!0);return e}wheel(t){let e=!1;for(const i of this.list)i.wheel(t)&&(e=!0);return e}}const _x={screenWidth:window.innerWidth,screenHeight:window.innerHeight,worldWidth:null,worldHeight:null,threshold:5,passiveWheel:!0,stopPropagation:!1,forceHitArea:null,noTicker:!1,disableOnContextMenu:!1,ticker:Tg.shared,allowPreserveDragOutside:!1};class Px extends qg{constructor(t){super(),Xv(this,"moving"),Xv(this,"screenWidth"),Xv(this,"screenHeight"),Xv(this,"threshold"),Xv(this,"input"),Xv(this,"plugins"),Xv(this,"zooming"),Xv(this,"lastViewport"),Xv(this,"options"),Xv(this,"_dirty"),Xv(this,"_forceHitArea"),Xv(this,"_hitAreaDefault"),Xv(this,"_pause"),Xv(this,"tickerFunction"),Xv(this,"_worldWidth"),Xv(this,"_worldHeight"),Xv(this,"_disableOnContextMenu",t=>t.preventDefault()),this.options={..._x,...t},this.screenWidth=this.options.screenWidth,this.screenHeight=this.options.screenHeight,this._worldWidth=this.options.worldWidth,this._worldHeight=this.options.worldHeight,this.forceHitArea=this.options.forceHitArea,this.threshold=this.options.threshold,this.options.disableOnContextMenu&&this.options.events.domElement.addEventListener("contextmenu",this._disableOnContextMenu),this.options.noTicker||(this.tickerFunction=()=>this.update(this.options.ticker.elapsedMS),this.options.ticker.add(this.tickerFunction)),this.input=new xx(this),this.plugins=new wx(this)}destroy(t){!this.options.noTicker&&this.tickerFunction&&this.options.ticker.remove(this.tickerFunction),this.options.disableOnContextMenu&&this.options.events.domElement.removeEventListener("contextmenu",this._disableOnContextMenu),this.input.destroy(),super.destroy(t)}update(t){this.pause||(this.plugins.update(t),this.lastViewport&&(this.lastViewport.x!==this.x||this.lastViewport.y!==this.y?this.moving=!0:this.moving&&(this.emit("moved-end",this),this.moving=!1),this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y?this.zooming=!0:this.zooming&&(this.emit("zoomed-end",this),this.zooming=!1)),this.forceHitArea||(this._hitAreaDefault=new vf(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight),this.hitArea=this._hitAreaDefault),this._dirty=this._dirty||!this.lastViewport||this.lastViewport.x!==this.x||this.lastViewport.y!==this.y||this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y,this.lastViewport={x:this.x,y:this.y,scaleX:this.scale.x,scaleY:this.scale.y},this.emit("frame-end",this))}resize(t=window.innerWidth,e=window.innerHeight,i,s){this.screenWidth=t,this.screenHeight=e,typeof i<"u"&&(this._worldWidth=i),typeof s<"u"&&(this._worldHeight=s),this.plugins.resize(),this.dirty=!0}get worldWidth(){return this._worldWidth?this._worldWidth:this.width/this.scale.x}set worldWidth(t){this._worldWidth=t,this.plugins.resize()}get worldHeight(){return this._worldHeight?this._worldHeight:this.height/this.scale.y}set worldHeight(t){this._worldHeight=t,this.plugins.resize()}getVisibleBounds(){return new vf(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight)}toWorld(t,e){return 2===arguments.length?this.toLocal(new gf(t,e)):this.toLocal(t)}toScreen(t,e){return 2===arguments.length?this.toGlobal(new gf(t,e)):this.toGlobal(t)}get worldScreenWidth(){return this.screenWidth/this.scale.x}get worldScreenHeight(){return this.screenHeight/this.scale.y}get screenWorldWidth(){return this.worldWidth*this.scale.x}get screenWorldHeight(){return this.worldHeight*this.scale.y}get center(){return new gf(this.worldScreenWidth/2-this.x/this.scale.x,this.worldScreenHeight/2-this.y/this.scale.y)}set center(t){this.moveCenter(t)}moveCenter(...t){let e,i;"number"==typeof t[0]?(e=t[0],i=t[1]):(e=t[0].x,i=t[0].y);const s=(this.worldScreenWidth/2-e)*this.scale.x,r=(this.worldScreenHeight/2-i)*this.scale.y;return(this.x!==s||this.y!==r)&&(this.position.set(s,r),this.plugins.reset(),this.dirty=!0),this}get corner(){return new gf(-this.x/this.scale.x,-this.y/this.scale.y)}set corner(t){this.moveCorner(t)}moveCorner(...t){let e,i;return 1===t.length?(e=-t[0].x*this.scale.x,i=-t[0].y*this.scale.y):(e=-t[0]*this.scale.x,i=-t[1]*this.scale.y),(e!==this.x||i!==this.y)&&(this.position.set(e,i),this.plugins.reset(),this.dirty=!0),this}get screenWidthInWorldPixels(){return this.screenWidth/this.scale.x}get screenHeightInWorldPixels(){return this.screenHeight/this.scale.y}findFitWidth(t){return this.screenWidth/t}findFitHeight(t){return this.screenHeight/t}findFit(t,e){const i=this.screenWidth/t,s=this.screenHeight/e;return Math.min(i,s)}findCover(t,e){const i=this.screenWidth/t,s=this.screenHeight/e;return Math.max(i,s)}fitWidth(t=this.worldWidth,e,i=!0,s){let r;e&&(r=this.center),this.scale.x=this.screenWidth/t,i&&(this.scale.y=this.scale.x);const n=this.plugins.get("clamp-zoom",!0);return!s&&n&&n.clamp(),e&&r&&this.moveCenter(r),this}fitHeight(t=this.worldHeight,e,i=!0,s){let r;e&&(r=this.center),this.scale.y=this.screenHeight/t,i&&(this.scale.x=this.scale.y);const n=this.plugins.get("clamp-zoom",!0);return!s&&n&&n.clamp(),e&&r&&this.moveCenter(r),this}fitWorld(t){let e;t&&(e=this.center),this.scale.x=this.screenWidth/this.worldWidth,this.scale.y=this.screenHeight/this.worldHeight,this.scale.x<this.scale.y?this.scale.y=this.scale.x:this.scale.x=this.scale.y;const i=this.plugins.get("clamp-zoom",!0);return i&&i.clamp(),t&&e&&this.moveCenter(e),this}fit(t,e=this.worldWidth,i=this.worldHeight){let s;t&&(s=this.center),this.scale.x=this.screenWidth/e,this.scale.y=this.screenHeight/i,this.scale.x<this.scale.y?this.scale.y=this.scale.x:this.scale.x=this.scale.y;const r=this.plugins.get("clamp-zoom",!0);return r&&r.clamp(),t&&s&&this.moveCenter(s),this}setZoom(t,e){let i;e&&(i=this.center),this.scale.set(t);const s=this.plugins.get("clamp-zoom",!0);return s&&s.clamp(),e&&i&&this.moveCenter(i),this}zoomPercent(t,e){return this.setZoom(this.scale.x+this.scale.x*t,e)}zoom(t,e){return this.fitWidth(t+this.worldScreenWidth,e),this}get scaled(){return this.scale.x}set scaled(t){this.setZoom(t,!0)}snapZoom(t){return this.plugins.add("snap-zoom",new gx(this,t)),this}OOB(){return{left:this.left<0,right:this.right>this.worldWidth,top:this.top<0,bottom:this.bottom>this.worldHeight,cornerPoint:new gf(this.worldWidth*this.scale.x-this.screenWidth,this.worldHeight*this.scale.y-this.screenHeight)}}get right(){return-this.x/this.scale.x+this.worldScreenWidth}set right(t){this.x=-t*this.scale.x+this.screenWidth,this.plugins.reset()}get left(){return-this.x/this.scale.x}set left(t){this.x=-t*this.scale.x,this.plugins.reset()}get top(){return-this.y/this.scale.y}set top(t){this.y=-t*this.scale.y,this.plugins.reset()}get bottom(){return-this.y/this.scale.y+this.worldScreenHeight}set bottom(t){this.y=-t*this.scale.y+this.screenHeight,this.plugins.reset()}get dirty(){return!!this._dirty}set dirty(t){this._dirty=t}get forceHitArea(){return this._forceHitArea}set forceHitArea(t){t?(this._forceHitArea=t,this.hitArea=t):(this._forceHitArea=null,this.hitArea=new vf(0,0,this.worldWidth,this.worldHeight))}drag(t){return this.plugins.add("drag",new ox(this,t)),this}clamp(t){return this.plugins.add("clamp",new Qv(this,t)),this}decelerate(t){return this.plugins.add("decelerate",new rx(this,t)),this}bounce(t){return this.plugins.add("bounce",new Kv(this,t)),this}pinch(t){return this.plugins.add("pinch",new dx(this,t)),this}snap(t,e,i){return this.plugins.add("snap",new fx(this,t,e,i)),this}follow(t,e){return this.plugins.add("follow",new lx(this,t,e)),this}wheel(t){return this.plugins.add("wheel",new vx(this,t)),this}animate(t){return this.plugins.add("animate",new qv(this,t)),this}clampZoom(t){return this.plugins.add("clamp-zoom",new ex(this,t)),this}mouseEdges(t){return this.plugins.add("mouse-edges",new ux(this,t)),this}get pause(){return!!this._pause}set pause(t){this._pause=t,this.lastViewport=null,this.moving=!1,this.zooming=!1,t&&this.input.pause()}ensureVisible(t,e,i,s,r){r&&(i>this.worldScreenWidth||s>this.worldScreenHeight)&&(this.fit(!0,i,s),this.emit("zoomed",{viewport:this,type:"ensureVisible"}));let n=!1;t<this.left?(this.left=t,n=!0):t+i>this.right&&(this.right=t+i,n=!0),e<this.top?(this.top=e,n=!0):e+s>this.bottom&&(this.bottom=e+s,n=!0),n&&this.emit("moved",{viewport:this,type:"ensureVisible"})}}const Ex=100;var Tx,Ax={exports:{}};var Ix=function(){if(Tx)return Ax.exports;function t(){}return Tx=1,t.prototype={on:function(t,e,i){var s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var s=this;function r(){s.off(t,r),e.apply(i,arguments)}return r._=e,this.on(t,r,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),s=0,r=i.length;s<r;s++)i[s].fn.apply(i[s].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),s=i[t],r=[];if(s&&e)for(var n=0,o=s.length;n<o;n++)s[n].fn!==e&&s[n].fn._!==e&&r.push(s[n]);return r.length?i[t]=r:delete i[t],this}},Ax.exports=t,Ax.exports.TinyEmitter=t,Ax.exports}();class Sx extends Ix.TinyEmitter{constructor({floorPlan:t,helperId:e}){super(),this.floorPlan=t,this.helperId=e}destroy(){delete this.floorPlan.helper[this.helperId],this.floorPlan=null}}class Cx extends Sx{constructor({floorPlan:t,parentEl:e,helperId:i}){super({floorPlan:t,helperId:i}),e&&t&&(this.data={cursor:["0","0"]},this.floorPlan.on("mousemove",this.update,this),this.mount(e),this.update())}update(){this.rootEl&&this.setData({cursor:[c(this.floorPlan.interaction.cursor[0],this.floorPlan.settings.units.system,this.floorPlan.settings.units.lengthDecimals),c(this.floorPlan.interaction.cursor[1],this.floorPlan.settings.units.system,this.floorPlan.settings.units.lengthDecimals)]})}setData(t={}){for(let e in t)this.data[e]=t[e];this.rootEl.innerHTML=this.template(this.data)}template(t={}){return`<span class="fpe-coordinates__unit">x:${t.cursor[0]}</span>\n <span class="fpe-coordinates__unit">z:${t.cursor[1]}</span>`}mount(t){this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.classList.add("fpe-coordinates"),t.appendChild(this.rootEl))}destroy(){this.floorPlan.off("mousemove",this.update),this.rootEl.remove(),delete this.floorPlan,delete this.data}}class Mx extends Sx{constructor({floorPlan:t,parentEl:e,helperId:i}){super({floorPlan:t,helperId:i}),e&&t&&(this.data={width:100,height:4,margin:2,style:"lines",box:{},scaleStep:null,scaleDisplay:null,steps:[],leftHanded:!1,isImperial:"imperial"===t.settings.units.system},this.floorPlan.view.on("zoom",this.update,this),this.floorPlan.on("update-settings",this.update,this),this.mount(e),this.update())}update(){this.data.isImperial="imperial"===this.floorPlan.settings.units.system;const t=this.data.isImperial?3.28084:1;if(!this.floorPlan.view.viewbox)return;this.data.box.length=this.floorPlan.view.viewbox.max[0]-this.floorPlan.view.viewbox.min[0],this.data.box.width=this.floorPlan.view.viewbox.max[1]-this.floorPlan.view.viewbox.min[1];const e=Math.min(this.floorPlan.view.client[0],this.floorPlan.view.client[1]),i=Math.min(this.data.box.length,this.data.box.width),s=e/i;if(!s)return;const r=200/s;this.data.scaleStep=i<=.5/t?.01/t:i<=1/t?.05/t:i<=2.5/t?.1/t:i<=5.4/t?.2/t:i<=12/t?.5/t:i<=25/t?1/t:i<=50/t?2/t:i<=100/t?5/t:i<=200/t?10/t:i<=550/t?20/t:50/t,this.data.scaleDisplay=this.data.scaleStep*t;const n=this.data.width,o=n*this.data.scaleStep/r,a=this.leftHanded?0:n;let l=0,h=[];if(this.data.leftHanded)for(;l<n-o;){let t=o<n-l?o:n-l;h.push([l+a,t]),l+=o}else for(;l>-n+o;){let t=o;h.push([l+a,-t]),l-=o}this.data.steps=h,this.setData()}setData(t={}){for(let e in t)this.data[e]=t[e];this.rootEl.setAttribute("viewBox",`-${this.data.margin} -${3*this.data.margin} ${this.data.width+2*this.data.margin} ${this.data.height+2*this.data.margin}`),this.rootEl.innerHTML=this.template(this.data)}template(t={}){let e="";return t.steps[0]&&(e+=`<rect\n class="fpe-scale-bar__background"\n style="fill:${this.backgroundClr()}"\n y="${2.5*-t.height}"\n x="${t.width+t.steps[0][1]-t.margin}"\n width="${-t.steps[0][1]+2*t.margin}"\n height="${4*t.height}"\n />`),e+=`<text x="${t.leftHanded?0:t.width}" text-anchor="${t.leftHanded?"start":"end"}" y="-3">\n ${t.scaleDisplay} ${t.isImperial?"ft":"m"}\n </text>`,"lines"===t.style&&(e+=`<path d="${this.stepStr(t.steps)}" />`),"solid"===t.style&&(e+="<g>",t.steps.forEach((t,i)=>{e+=`<rect\n class="${i%2!=0?"white":""}"\n x="${t[0]}"\n y="0"\n width="${t[1]}"\n height="0.5"\n />`}),e+="</g>"),e}backgroundClr(){let t=this.floorPlan.settings&&function(t,e=1){if(null!==f(t).match(/^#[a-f0-9]{6}$/i)){const{r:i,g:s,b:r}=g(t);return`rgba(${i},${s},${r},${e})`}}(this.floorPlan.settings.theme.background.color);return t||(t="rgba(255, 255, 255, 0.8)"),t+"!important"}stepStr(t){if(!t)return"";let e="",i=this.data.height;return t.forEach((t,s)=>{if(s>=1&&!this.data.leftHanded)return;t=t.map(t=>Math.round(1e3*t)/1e3);let r=s%2==0?0:i,n=s%2==0?i:0;0===s&&(e+=`M ${t[0]} ${i} L ${t[0]} 0`),e+=`L ${t[0]+t[1]} ${r} `,e+=`L ${t[0]+t[1]} ${n} `}),e}mount(t){this.rootEl||(this.rootEl=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.rootEl.classList.add("fpe-scale-bar"),t.appendChild(this.rootEl))}destroy(){this.floorPlan.view.off("viewbox",this.update),this.floorPlan.off("update-settings",this.update),this.rootEl.remove(),delete this.floorPlan.helper.scaleBar,delete this.floorPlan,delete this.data}}const Ox=100,Nx=80;class Lx{constructor({width:t,height:e,position:i=[0,0],html:s="",closeButton:r=!0,floorPlan:n}={}){this._floorPlan=n,this.position=i,this.html=s,this.closeButton=r,this._anchorPos=null;let o=t||Ox;this.width=Math.max(100,o);let a=e||Nx;this.height=Math.max(50,a),this._getPosition=()=>{this._anchorPos=this._floorPlan.getScreenPosition(this.position),this._updateInfoWindow()},this._getPosition(),this._createInfoWindow(),this._floorPlan.view.on("viewbox",this._getPosition,this),this._floorPlan.view.on("resize-canvas",this._getPosition,this)}_createInfoWindow(){const t=document.querySelector(`#${this._floorPlan.fpeId}.fpe`),e=t.querySelector("canvas");this.el||(this.el=document.createElement("div"),this.el.classList.add("fpe-info-window"),t.appendChild(this.el),this.el.addEventListener("wheel",t=>{let i=new WheelEvent(t.type,t);e.dispatchEvent(i)})),this._setContent(),this._updateInfoWindow()}_setContent(){let t=`<div class="fpe-info-window__content">${this.html}</div>`;this.closeButton&&(t+='<div class="fpe-info-window__close" @click="infoWindow.remove"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">\n <g fill="none" stroke="#000" stroke-width="1.2" stroke-miterlimit="10">\n <path d="M11.8 11.8l16.4 16.4M11.8 28.2l16.3-16.4" />\n </g>\n</svg></div>'),this.el.innerHTML=t;const e=this.el.querySelector(".fpe-info-window__close");e&&e.addEventListener("click",this.remove.bind(this))}_updateInfoWindow(){if(!this.el)return;const t=this._floorPlan.interaction.isPanning?"pointer-events: none;":"",e=this._anchorPos[0]-47,i=this._anchorPos[1]-this.height-15,s=1e3+2*this.position[1],r=this.height,n=this.width;this.el.setAttribute("style",`transform: translate(${e}px, ${i}px);${t} height:${r}px; width:${n}px; z-index:${s}`)}set({width:t,height:e,position:i,html:s,closeButton:r}){void 0!==i&&(this.position=i),void 0!==t&&(this.width=Math.max(100,t)),void 0!==e&&(this.height=Math.max(50,e)),void 0!==s&&(this.html=s),void 0!==r&&(this.closeButton=r),void 0===s&&void 0===r||this._setContent(),this._getPosition()}remove(){this._floorPlan.view.off("viewbox",this._getPosition),this._floorPlan.view.off("resize-canvas",this._getPosition),this.el.remove(),this._floorPlan=null}}class Rx{constructor({position:t=[0,0],offset:e=[0,0],el:i,floorPlan:s}){if(this._isPanning=!1,this._updateHtmlMarker=()=>{if(!this.el)return;const t=this.isHidden;this.isHidden=!(([t,e],i,s=0)=>i.min[0]-s<t&&i.max[0]+s>t&&i.min[1]-s<e&&i.max[1]+s>e)(this.position,this._floorPlan.view.viewbox,5),t!==this.isHidden&&this.el.classList.toggle("fpe-marker--hidden",this.isHidden),this.isHidden||(this._anchorPos=this._floorPlan.getScreenPosition(this.position),this._updateHtmlMarkerStyle())},!s)return;if(i instanceof HTMLElement==!1)return void Nl.warn("no Element provided");this.el=i;const r=document.querySelector(`#${s.fpeId}.fpe`),n=r.querySelector("canvas");r.appendChild(this.el),this.el.classList.add("fpe-marker");const{width:o,height:a}=i.getBoundingClientRect();this.el.addEventListener("wheel",t=>{let e=new WheelEvent(t.type,t);n.dispatchEvent(e)}),this.id=O(),this._floorPlan=s,this.position=t,this.size=[o,a],this.offset=e,this._updateHtmlMarker(),this._floorPlan.view.on("viewbox",this._updateHtmlMarker),this._floorPlan.view.on("resize-canvas",this._updateHtmlMarker)}_updateHtmlMarkerStyle(){const t=this._floorPlan.interaction.isPanning;this._isPanning!==t&&(this._isPanning=t,this.el.style.pointerEvents=t?"none":"");const e=this.offset?this.offset:[0,0],i=this._anchorPos[0]-this.size[0]/2+e[0],s=this._anchorPos[1]-this.size[1]/2+e[1];this.el.style.transform=`translate(${i}px, ${s}px)`}set({position:t,offset:e}){void 0!==t&&(this.position=t),void 0!==e&&(this.offset=e),this._updateHtmlMarker()}remove(){this._floorPlan.view.off("viewbox",this._updateHtmlMarker),this._floorPlan.view.off("resize-canvas",this._updateHtmlMarker),this.el.remove(),this._floorPlan=null}}var Bx={grad:.9,turn:360,rad:360/(2*Math.PI)},kx=function(t){return"string"==typeof t?t.length>0:"number"==typeof t},Fx=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=Math.pow(10,e)),Math.round(i*t)/i+0},Dx=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=1),t>i?i:t>e?t:e},Ux=function(t){return(t=isFinite(t)?t%360:0)>0?t:t+360},Gx=function(t){return{r:Dx(t.r,0,255),g:Dx(t.g,0,255),b:Dx(t.b,0,255),a:Dx(t.a)}},Xx=function(t){return{r:Fx(t.r),g:Fx(t.g),b:Fx(t.b),a:Fx(t.a,3)}},Wx=/^#([0-9a-f]{3,8})$/i,Yx=function(t){var e=t.toString(16);return e.length<2?"0"+e:e},Hx=function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=Math.max(e,i,s),o=n-Math.min(e,i,s),a=o?n===e?(i-s)/o:n===i?2+(s-e)/o:4+(e-i)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},$x=function(t){var e=t.h,i=t.s,s=t.v,r=t.a;e=e/360*6,i/=100,s/=100;var n=Math.floor(e),o=s*(1-i),a=s*(1-(e-n)*i),l=s*(1-(1-e+n)*i),h=n%6;return{r:255*[s,a,o,o,l,s][h],g:255*[l,s,s,a,o,o][h],b:255*[o,o,l,s,s,a][h],a:r}},jx=function(t){return{h:Ux(t.h),s:Dx(t.s,0,100),l:Dx(t.l,0,100),a:Dx(t.a)}},zx=function(t){return{h:Fx(t.h),s:Fx(t.s),l:Fx(t.l),a:Fx(t.a,3)}},Vx=function(t){return $x((i=(e=t).s,{h:e.h,s:(i*=((s=e.l)<50?s:100-s)/100)>0?2*i/(s+i)*100:0,v:s+i,a:e.a}));var e,i,s},qx=function(t){return{h:(e=Hx(t)).h,s:(r=(200-(i=e.s))*(s=e.v)/100)>0&&r<200?i*s/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,i,s,r},Jx=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Kx=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Zx=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Qx=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,tb={string:[[function(t){var e=Wx.exec(t);return e?(t=e[1]).length<=4?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16),a:4===t.length?Fx(parseInt(t[3]+t[3],16)/255,2):1}:6===t.length||8===t.length?{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16),a:8===t.length?Fx(parseInt(t.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(t){var e=Zx.exec(t)||Qx.exec(t);return e?e[2]!==e[4]||e[4]!==e[6]?null:Gx({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:void 0===e[7]?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(t){var e=Jx.exec(t)||Kx.exec(t);if(!e)return null;var i,s,r=jx({h:(i=e[1],s=e[2],void 0===s&&(s="deg"),Number(i)*(Bx[s]||1)),s:Number(e[3]),l:Number(e[4]),a:void 0===e[5]?1:Number(e[5])/(e[6]?100:1)});return Vx(r)},"hsl"]],object:[[function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=void 0===r?1:r;return kx(e)&&kx(i)&&kx(s)?Gx({r:Number(e),g:Number(i),b:Number(s),a:Number(n)}):null},"rgb"],[function(t){var e=t.h,i=t.s,s=t.l,r=t.a,n=void 0===r?1:r;if(!kx(e)||!kx(i)||!kx(s))return null;var o=jx({h:Number(e),s:Number(i),l:Number(s),a:Number(n)});return Vx(o)},"hsl"],[function(t){var e=t.h,i=t.s,s=t.v,r=t.a,n=void 0===r?1:r;if(!kx(e)||!kx(i)||!kx(s))return null;var o,a=(o={h:Number(e),s:Number(i),v:Number(s),a:Number(n)},{h:Ux(o.h),s:Dx(o.s,0,100),v:Dx(o.v,0,100),a:Dx(o.a)});return $x(a)},"hsv"]]},eb=function(t,e){for(var i=0;i<e.length;i++){var s=e[i][0](t);if(s)return[s,e[i][1]]}return[null,void 0]},ib=function(t,e){var i=qx(t);return{h:i.h,s:Dx(i.s+100*e,0,100),l:i.l,a:i.a}},sb=function(t){return(299*t.r+587*t.g+114*t.b)/1e3/255},rb=function(t,e){var i=qx(t);return{h:i.h,s:i.s,l:Dx(i.l+100*e,0,100),a:i.a}},nb=function(){function t(t){this.parsed=function(t){return"string"==typeof t?eb(t.trim(),tb.string):"object"==typeof t&&null!==t?eb(t,tb.object):[null,void 0]}(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return t.prototype.isValid=function(){return null!==this.parsed},t.prototype.brightness=function(){return Fx(sb(this.rgba),2)},t.prototype.isDark=function(){return sb(this.rgba)<.5},t.prototype.isLight=function(){return sb(this.rgba)>=.5},t.prototype.toHex=function(){return e=(t=Xx(this.rgba)).r,i=t.g,s=t.b,n=(r=t.a)<1?Yx(Fx(255*r)):"","#"+Yx(e)+Yx(i)+Yx(s)+n;var t,e,i,s,r,n},t.prototype.toRgb=function(){return Xx(this.rgba)},t.prototype.toRgbString=function(){return e=(t=Xx(this.rgba)).r,i=t.g,s=t.b,(r=t.a)<1?"rgba("+e+", "+i+", "+s+", "+r+")":"rgb("+e+", "+i+", "+s+")";var t,e,i,s,r},t.prototype.toHsl=function(){return zx(qx(this.rgba))},t.prototype.toHslString=function(){return e=(t=zx(qx(this.rgba))).h,i=t.s,s=t.l,(r=t.a)<1?"hsla("+e+", "+i+"%, "+s+"%, "+r+")":"hsl("+e+", "+i+"%, "+s+"%)";var t,e,i,s,r},t.prototype.toHsv=function(){return t=Hx(this.rgba),{h:Fx(t.h),s:Fx(t.s),v:Fx(t.v),a:Fx(t.a,3)};var t},t.prototype.invert=function(){return ob({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},t.prototype.saturate=function(t){return void 0===t&&(t=.1),ob(ib(this.rgba,t))},t.prototype.desaturate=function(t){return void 0===t&&(t=.1),ob(ib(this.rgba,-t))},t.prototype.grayscale=function(){return ob(ib(this.rgba,-1))},t.prototype.lighten=function(t){return void 0===t&&(t=.1),ob(rb(this.rgba,t))},t.prototype.darken=function(t){return void 0===t&&(t=.1),ob(rb(this.rgba,-t))},t.prototype.rotate=function(t){return void 0===t&&(t=15),this.hue(this.hue()+t)},t.prototype.alpha=function(t){return"number"==typeof t?ob({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):Fx(this.rgba.a,3);var e},t.prototype.hue=function(t){var e=qx(this.rgba);return"number"==typeof t?ob({h:t,s:e.s,l:e.l,a:e.a}):Fx(e.h)},t.prototype.isEqual=function(t){return this.toHex()===ob(t).toHex()},t}(),ob=function(t){return t instanceof nb?t:new nb(t)},ab=[];!function(t){t.forEach(function(t){ab.indexOf(t)<0&&(t(nb,tb),ab.push(t))})}([function(t,e){var i={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},s={};for(var r in i)s[i[r]]=r;var n={};t.prototype.toName=function(e){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var r,o,a=s[this.toHex()];if(a)return a;if(null==e?void 0:e.closest){var l=this.toRgb(),h=1/0,u="black";if(!n.length)for(var c in i)n[c]=new t(i[c]).toRgb();for(var d in i){var p=(r=l,o=n[d],Math.pow(r.r-o.r,2)+Math.pow(r.g-o.g,2)+Math.pow(r.b-o.b,2));p<h&&(h=p,u=d)}return u}},e.string.push([function(e){var s=e.toLowerCase(),r="transparent"===s?"#0000":i[s];return r?new t(r).toRgb():null},"name"])}]);const lb=class t{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(t){return this.value=t,this}set value(e){if(e instanceof t)this._value=this.cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(null===e)throw new Error("Cannot set PIXI.Color#value to null");(null===this._value||!this.isSourceEqual(this._value,e))&&(this.normalize(e),this._value=this.cloneSource(e))}}get value(){return this._value}cloneSource(t){return"string"==typeof t||"number"==typeof t||t instanceof Number||null===t?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):"object"==typeof t&&null!==t?{...t}:t}isSourceEqual(t,e){const i=typeof t;if(i!==typeof e)return!1;if("number"===i||"string"===i||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length===e.length&&t.every((t,i)=>t===e[i]);if(null!==t&&null!==e){const i=Object.keys(t),s=Object.keys(e);return i.length===s.length&&i.every(i=>t[i]===e[i])}return t===e}toRgba(){const[t,e,i,s]=this._components;return{r:t,g:e,b:i,a:s}}toRgb(){const[t,e,i]=this._components;return{r:t,g:e,b:i}}toRgbaString(){const[t,e,i]=this.toUint8RgbArray();return`rgba(${t},${e},${i},${this.alpha})`}toUint8RgbArray(t){const[e,i,s]=this._components;return(t=t??[])[0]=Math.round(255*e),t[1]=Math.round(255*i),t[2]=Math.round(255*s),t}toRgbArray(t){t=t??[];const[e,i,s]=this._components;return t[0]=e,t[1]=i,t[2]=s,t}toNumber(){return this._int}toLittleEndianNumber(){const t=this._int;return(t>>16)+(65280&t)+((255&t)<<16)}multiply(e){const[i,s,r,n]=t.temp.setValue(e)._components;return this._components[0]*=i,this._components[1]*=s,this._components[2]*=r,this._components[3]*=n,this.refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this.refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(1===t)return(255<<24)+this._int;if(0===t)return e?0:this._int;let i=this._int>>16&255,s=this._int>>8&255,r=255&this._int;return e&&(i=i*t+.5|0,s=s*t+.5|0,r=r*t+.5|0),(255*t<<24)+(i<<16)+(s<<8)+r}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const t=Math.round(255*this._components[3]).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(t){return this._components[3]=this._clamp(t),this}round(t){const[e,i,s]=this._components;return this._components[0]=Math.round(e*t)/t,this._components[1]=Math.round(i*t)/t,this._components[2]=Math.round(s*t)/t,this.refreshInt(),this._value=null,this}toArray(t){t=t??[];const[e,i,s,r]=this._components;return t[0]=e,t[1]=i,t[2]=s,t[3]=r,t}normalize(e){let i,s,r,n;if(("number"==typeof e||e instanceof Number)&&e>=0&&e<=16777215){i=(e>>16&255)/255,s=(e>>8&255)/255,r=(255&e)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[i,s,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[i,s,r,n=255]=e,i/=255,s/=255,r/=255,n/=255;else if("string"==typeof e||"object"==typeof e){if("string"==typeof e){const i=t.HEX_PATTERN.exec(e);i&&(e=`#${i[2]}`)}const o=ob(e);o.isValid()&&(({r:i,g:s,b:r,a:n}=o.rgba),i/=255,s/=255,r/=255)}if(void 0===i)throw new Error(`Unable to convert color ${e}`);this._components[0]=i,this._components[1]=s,this._components[2]=r,this._components[3]=n,this.refreshInt()}refreshInt(){this._clamp(this._components);const[t,e,i]=this._components;this._int=(255*t<<16)+(255*e<<8)+(255*i|0)}_clamp(t,e=0,i=1){return"number"==typeof t?Math.min(Math.max(t,e),i):(t.forEach((s,r)=>{t[r]=Math.min(Math.max(s,e),i)}),t)}};lb.shared=new lb,lb.temp=new lb,lb.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let hb=lb;class ub{constructor({position:t,color:e,size:i,floorPlan:s}){this.position=t,this.color=e,this.size=i,this.floorPlan=s,this.id=O(),this.draw()}draw(){const t=this.size/4e3;this.layer=this.floorPlan.addLayer({id:"fpe-markers"});let e=[{type:"curve:composite",segments:[{type:"curve:arc",position:[0,-27.8],radius:12.4,startAngle:-25,endAngle:205},{type:"curve:line",end:[0,0],start:[-11.2,-22.5]}],style:{fill:new hb(this.color).toNumber(),stroke:6710886,strokeWidth:.5/t}},{type:"curve:circle",position:[0,-28],radius:5,style:{fill:1,fillOpacity:.2}}];this.graphic=this.layer.addGraphic({shapes:e,position:this.position,id:"marker_"+this.id,scale:t,scaleOnZoom:!0})}remove(){this.off("click"),this.layer.deleteGraphic(this.graphic),delete this.floorPlan,0===this.layer.graphics.size&&this.layer.destroy()}on(t="click",e,i){this.graphic.gfx.eventMode="static",this.graphic.gfx.on(t,e,i)}off(t="click",e){this.graphic.gfx.off(t,e)}set(t){let e=["position","color","size"];Object.keys(t).forEach(i=>{e.includes(i)&&(this[i]=t[i])}),this.draw()}}const cb=t=>{if(t?.children)for(var e=t.children.length-1;e>=0;e--)t.children[e].destroy({children:!0}),t.removeChild(t.children[e])};function db(t,e,i){const s=new Zg(t);return s.x=0,s.y=0,s.anchor.x=.5,s.anchor.y=.5,s.rotation=0,e&&(s.width=e),i&&(s.height=i),s}function pb(t=[]){return(t=t.sort((t,e)=>K(t)>K(e)?-1:1))&&t.length?[{type:"curve:polygonWithHoles",polygons:t}]:[]}function fb(t,e,i=!1,s=16,r=8){let n=[];for(let m=0;m<e.length-1;m+=2)n.push({x:e[m],y:e[m+1]});let o,a,l,h=0,u=0,c=i?1:0;for(o=0;o<n.length-c;o++){a=n[o],l=o==n.length-1?n[0]:n[o+1];let e=l.x-a.x,i=l.y-a.y;var d=Math.sqrt(e*e+i*i),p={x:e/d,y:i/d},f=0;for(t.moveTo(a.x+u*p.x,a.y+u*p.y);f<=d;)f+=u,(f+=h>0?h:s)>d?(h=f-d,f=d):h=0,t.lineTo(a.x+f*p.x,a.y+f*p.y),(f+=r)>d&&0==h?u=f-d:(u=0,t.moveTo(a.x+f*p.x,a.y+f*p.y))}}function mb(t){return t.stroke?{alpha:t.strokeOpacity||1,color:eh(t.stroke),native:"native"===t.strokeWidth,width:"number"==typeof t.strokeWidth?t.strokeWidth:1,alignment:"number"==typeof t.alignment?t.alignment:.5}:{}}const gb=t=>["curve:line","curve:polyline","curve:arc"].includes(t);function yb({shape:t,settings:e,gfx:i,style:s={},view:r}){if(!i||!i.lineStyle)return;const n={...s,...t.style};t.style||(n.stroke??=vl),n.strokeWidth??="native";const o=Ex,a="string"==typeof n?.fill&&n.fill.startsWith("url("),l=!gb(t.type)&&Boolean(n.fill)&&!a;if(a&&function({shape:t,settings:e,style:i,gfx:s,view:r}){if("string"!=typeof i?.fill||gb(t.type))return;let n,o,a=[0,0];const l=i.fill.match(/url\((.*?)\)/)?.[1];if(!l||!l.startsWith("data:image")&&!l.startsWith("https://"))return;let h;r?.textureCache.has(l)?h=r.textureCache.get(l):(h=tf.from(l,{scaleMode:wh.NEAREST}),r&&!h.valid&&h.once("loaded",()=>{r.viewportNeedsUpdate=!0}),r?.textureCache.set(l,h));const u=Zg.from(h);switch(t.type){case"curve:polygon":case"curve:circle":case"curve:polygonWithHoles":{if("radius"in t)n=o=2*t.radius,a=ui(t.position,[t.radius,t.radius]);else{const{min:e,max:i}=W("points"in t?[t.points]:t.polygons);n=i[0]-e[0],o=i[1]-e[1],a=e}const i=new Ty;yb({shape:{...t,style:{fill:16777215}},settings:e,gfx:i}),s.addChild(i),u.mask=i;break}case"curve:rectangle":n=t.dimensions[0],o=t.dimensions[1],a=t.position;break;default:return}u.width=n*Ex,u.height=o*Ex,u.x=a[0]*Ex,u.y=a[1]*Ex,u.anchor.set(0),u.alpha=i.fillOpacity??1,s.addChild(u)}({shape:t,settings:e,style:n,gfx:i,view:r}),l&&n.fill&&i.beginFill(eh(n.fill),n.fillOpacity),i.lineStyle(mb(n)),"curve:rectangle"===t.type){let{position:e,dimensions:s}=t;i.drawRect(e[0]*o,e[1]*o,s[0]*o,s[1]*o)}else if("curve:circle"===t.type||"curve:composite"===t.type){vb((t=>{const e={type:"curve:polygon",points:[],style:t.style};switch(t.type){case"curve:circle":const i=t.radius,s=lh(2*Math.PI,i),r=t.position,n=2*Math.PI/s;let o=0;for(let t=0;t<s;t++)e.points.push([i*Math.cos(o)+r[0],-i*Math.sin(o)+r[1]]),o+=n;break;case"curve:polygon":e.points=t.points;break;case"curve:rectangle":const a=t.dimensions,[l,h]=t.position||[0,0];e.points=[[l,h],[l,h+a[1]],[l+a[0],h+a[1]],[l+a[0],h]];break;case"curve:composite":for(const u of t.segments){let t=hh(u);e.points.push(...t.points)}}return e})(t).points,[],n,o,i,l)}else if("curve:arc"===t.type||"curve:quadraticBezier"===t.type){hh(t).points.forEach((t,e)=>{0===e?i.moveTo(t[0]*o,t[1]*o):i.lineTo(t[0]*o,t[1]*o)})}else if("curve:polygon"===t.type)vb(t.points,[],n,o,i,l);else if("curve:polygonWithHoles"===t.type){let{polygons:e}=t;vb(e[0],e.slice(1),n,o,i,l)}else if("curve:line"===t.type){let{start:e,end:s}=t;i.moveTo(e[0]*o,e[1]*o),i.lineTo(s[0]*o,s[1]*o)}else if("curve:polyline"===t.type){let{points:e}=t;n.dash?fb(i,e.flat().map(t=>t*o),!0):e.forEach((t,e)=>{0===e?i.moveTo(t[0]*o,t[1]*o):i.lineTo(t[0]*o,t[1]*o)})}else if("group"===t.type){let{position:n=[0,0],rotation:a=0}=t,l=new Ty;l.x=n[0]*o,l.y=n[1]*o,l.rotation=-Math.PI/180*a,t.children.forEach(t=>yb({shape:t,settings:e,gfx:l,style:s,view:r})),i.addChild(l)}else if("text"===t.type){let s=t.style?.fill?eh(t.style.fill):0,r=t.style?.stroke?eh(t.style.stroke):16777215,{position:n=[0,0],rotation:a=0,text:l,alignH:h="center",alignV:u="center",fontSize:c=16}=t;const d=new Ny({fontFamily:e?.theme?.fontFamily||Sl.theme?.fontFamily,fontSize:c,fill:s,align:h,stroke:r,strokeThickness:3});let p=new Fy(l,d);p.x=n[0]*o,p.y=n[1]*o,p.rotation=-Math.PI/180*a,p.anchor.x=.5,p.anchor.y="center"===u?.5:"bottom"===u?1:0,i.addChild(p)}l&&i.endFill()}function vb(t=[],e=[],i={},s=100,r,n){if(!t||!Array.isArray(t)||!t.length)return r;r.lineStyle(mb(i));let o=t.flat().map(t=>t*s);if(i.dash?(fb(r,o),n&&(r.lineStyle(0),r.drawPolygon(o))):r.drawPolygon(o),e.length){n&&r.beginHole();for(const t of e){let e=t.flat().map(t=>t*s);r.drawPolygon(e)}n&&r.endHole()}return r}function xb(t,e){e.on("product-load-texture",({resourceId:i})=>{!function(t,e){let i=t.resources.productJson.get(e);if(!i.boundingBox)return void Nl.warn("product boundingBox missing");const{boundingBox:s}=i,r=$l(s);let n={x:s.min[0],y:s.min[2]},o={x:Math.abs(s.min[0]/r[0]),y:Math.abs(s.min[2]/r[2])},a={x:s.max[0]-r[0]/2,y:s.max[2]-r[2]/2},l=t.resources.texture.get(e);l.offset=a,l.anchor=o,l.position=n}(e,i),bb({view:t,resourceId:i,loader:e})});const i=new Ty;i.lineStyle({native:!0,color:3355443}),i.drawCircle(0,0,1),t._dummyTexture=t._renderer.generateTexture(i)}function bb({resourceId:t,loader:e,view:i}){if(!e.resources.texture.has(t))return Promise.reject(`no texture data to load ${t}`);const s=e.resources.texture.get(t);if(s.texture)return Promise.resolve();let{textureUrl:r}=s;return Mp(),function(t){return new Promise((e,i)=>{var s=new Image;s.addEventListener("load",()=>{URL.revokeObjectURL(s.src),e(new Em(new tf(s)))}),s.addEventListener("error",()=>{URL.revokeObjectURL(s.src),i("image loading failed: "+t)});const r=t.includes("/storage/get/"),n=t.startsWith("https://")?t:Ml+t;s.src=n,s.crossOrigin=r?"use-credentials":"anonymous"})}(r).then(r=>{s.imageData=r,function(t,e,i){const s=e?._renderer;if(!s)return;const r=i.resources.texture.get(t),n=r.error;if(Mp(),!r.texture){const e=i.resources.productJson.get(t),o=new qg;let a,l;n||(a=new Zg(r.imageData),a=_b(a,r.applyFilter),o.addChild(a));const h=i.resources.productContour.get(t),u=h?.length?[{type:"curve:polygon",points:h[0],holes:h.slice(1)}]:[];if(u.length&&e?.boundingBox){let t;n?t={strokeWidth:.5,stroke:1,fill:16316664}:(t=nh({settings:{theme:{showAssetTextures:!0,byType:{}}},elementType:"element:asset"}),t.stroke=vl),l=wb(u,t);const i=new Zg(l);i.anchor.x=r.anchor.x,i.anchor.y=r.anchor.y;const s=$l(e.boundingBox);if(!n){let t=a.width/s[0],e=r?.offset||{x:0,y:0};i.scale.x=a.width/i.width,i.scale.y=a.height/i.height,i.x=a.width/2-e.x*t,i.y=a.height/2-e.y*t}o.addChild(i)}r.texture=s.generateTexture(o,{scaleMode:wh.LINEAR,resolution:1.5}),o.destroy(!0),l&&l.destroy(!0)}i.emit("resource-loaded",{resourceId:t})}(t,i,e)}).catch(i=>{Nl.warn(i),s.error={message:i},e.emit("resource-loaded",{resourceId:t})})}function wb(t,e){let i,s=new Ty;for(const r of t)yb({shape:r,gfx:s,style:e});return i=s.generateCanvasTexture(wh.LINEAR,2),s.destroy(),i}function _b(t,e){switch(e){case Xl.Default:{const e=new Dy;e.matrix=[.7,0,0,0,.25,0,.7,0,0,.25,0,0,.7,0,.25,0,0,0,1,0],t.filters=[e];break}case Xl.Grayscale:{const e=new Dy;e.blackAndWhite(!0),t.filters=[e];break}case Xl.None:}return t}function Pb(t,e,i,s,r,n,o){const a=$l(t.boundingBox),l=db(e.texture,a[0]*o,a[2]*o);l.anchor.x=e.anchor.x,l.anchor.y=e.anchor.y,l.zIndex=1,function(t,e,i,s){if(!e.categories?.includes("tables")&&!e.categories?.includes("seating")||!i[0]?.polygons[0])return;const r=new wf(i[0].polygons[0].flatMap(e=>[e[0]*s/t.scale.x,e[1]*s/t.scale.y]));t.hitArea=r,t.eventMode="static"}(l,t,i,o);const h=[];let u=[];if(!n&&(null!=r.fill||null!=r.stroke)&&i?.length){const t=function(t,e,i,s,r,n){const o=null!=i.fill,a=null!=i.stroke,l=e.fillOpacity??1;if(!o&&!a)return null;if(o&&l<=0&&!a)return null;const h={fill:o?e.fill:void 0,fillOpacity:o?l:0,stroke:a?e.stroke:void 0,strokeWidth:a?e.strokeWidth:void 0,strokeOpacity:a?e.strokeOpacity:void 0},u=JSON.stringify(h);n.themeOverlayTexture&&n.themeOverlayStyleKey===u||(n.themeOverlayTexture&&n.themeOverlayTexture.destroy(!0),n.themeOverlayTexture=wb(t,h),n.themeOverlayStyleKey=u);const c=new Zg(n.themeOverlayTexture);return c.anchor.x=s,c.anchor.y=r,c.zIndex=2,c.eventMode="none",c}(i,s,r,e.anchor.x,e.anchor.y,e);t&&h.push(t)}if("selected"===n)h.push(function(t,e,i,s){e.contourTexture||(e.contourTexture=wb(t,{stroke:i.stroke,strokeWidth:i.strokeWidth||1}));const r=new Zg(e.contourTexture);return r.anchor.x=e.anchor.x,r.anchor.y=e.anchor.y,r.zIndex=5,r.eventMode="none",i.fill&&(s.tint=eh(i.fill)),r}(i,e,s,l));else if(n){const{overlay:t,shapes:e}=function(t){const e=new Ty;return e.zIndex=5,e.eventMode="none",{overlay:e,shapes:t||[]}}(i);h.push(t),u=e}return{gfx:l,overlays:h,shapes:u}}function Eb(t,e,i,s){!function(t,e){const i=t.product?.id,{loader:s}=e,r=s.resources.nodes.get(i);if(i&&!r?.has(t))Ll(e.loader,t).catch(t=>Nl.warn(t))}(t,i);const{view:r,settings:n,loader:o}=i,{theme:a,showCeilingLamps:l}=n;let h,u=[];const c=[],d=t.product?.id,p=o.resources.productJson.get(d)||{subCategories:[]},f="product:component"===t.product?.type,m=o.resources.productContour.get(d),g=o.resources.texture.get(d),y=pb(m);if(p?.subCategories.includes("ceilingLight")&&!l)return[];const v=function(t,e,i){if(!i)return ch(e);let s=0;for(const r of t.elements){if("element:asset"!==r.type||!r.product)continue;const t=ch(r.product.attributes);t>s&&(s=t)}return s}(t,p,f),x=th(t.type,v);e.zIndex=x||0;let b=nh({element:t,settings:n,style:s});if(m||f||!p.boundingBox)if(a.showAssetTextures&&!g?.error||!m)if(a.showAssetTextures&&g?.texture){const e=t.parent?.id,i=Pb(p,g,y,b,sh({settings:n,nodeId:t.id,parentId:e,nodeType:t.type}),s,100);h=i.gfx,c.push(...i.overlays),u=i.shapes}else h=new Zg(r._dummyTexture);else{const e={...a,showAssetTextures:!1};b=nh({element:t,settings:{...n,theme:e},style:s}),u=y,h=new Ty}else{u=pb(function(t){const e=t;if(e){let t;return t=[[e.min[0],e.min[2]],[e.min[0],e.max[2]],[e.max[0],e.max[2]],[e.max[0],e.min[2]]],[t]}return[]}(p.boundingBox)),h=new Ty}const w=c.length>0?c[c.length-1]:h;for(const _ of u)yb({shape:_,settings:n,gfx:w,style:b,view:r});return[h,...c].filter(Boolean)}function Tb(t,e){const i=[];if("element:wall"===t.type)i.push(...function(t){let{valid:e,points:i}=t.geometryProfile,s=[];if(t.layout?.debugIds){for(let t of i)s.push({type:"curve:circle",radius:.02,position:t,style:{stroke:0,fill:e?32768:16711680,fillOpacity:.2}});let r=nh({element:t});e||(r.stroke=16711680),s.push({type:"curve:polygon",points:i,style:r})}else s.push({type:"curve:polygon",points:i});return s}(t));else if("element:opening"===t.type)i.push(...jl(t));else if("spatialGraph:edge"===t.type)i.push(...function(t,e={}){let[i,s]=t.vertices,r="selected"===e,n=[{type:"curve:line",start:i.position,end:s.position}];if(t.layout.debugIds){let e,r=fl(t.id)?t.id.substring(0,4):t.id;t.element&&(e=fl(t.element.id)?t.element.id.substring(0,4):t.element.id);let o=t.element?`${r} (${e})`:r;n.push({type:"text",position:ti(i.position,hi(ui(s.position,i.position),.5)),text:o,fontSize:10})}if(null===t.element||"element:spaceDivider"===t.element.type){let t=ai(li(ui(s.position,i.position))),e=.02,o=ti(i.position,hi(t,-e)),a=ti(i.position,hi(t,e)),l=ti(s.position,hi(t,e)),h=ti(s.position,hi(t,-e));n.unshift({type:"curve:polygon",points:[o,a,l,h],style:{stroke:null,fill:r?Tl:El,fillOpacity:.1}})}return n}(t));else if("layout:space"===t.type){const e=t.geometry.polygons;e.length>0&&i.push({type:"curve:polygonWithHoles",polygons:e})}else if("geometries"in t&&t.geometries.length){const{shapes:s,maxY:r}=function(t){const e=dl(t).sort((t,e)=>t.boundingBox.max[1]<e.boundingBox.max[1]?-1:1);"element:door"!==t.type&&"element:window"!==t.type||e.pop();let i=e.length?e[e.length-1].boundingBox.max[1]:0,s=[];for(let r of e)for(let t=0;t<r.outlines.length;t++)s.push({type:"curve:polygonWithHoles",polygons:[r.outlines[t],...r.holes[t]||[]]});return{shapes:s,maxY:i}}(t);i.push(...s),e.zIndex=e.zIndex+r}return i}function Ab(t,e,i,s,r,n){if(!e||e.destroyed)return void Nl.warn(`graphic container for node ${t.id} is missing`);let o,a,l=[];const{view:h}=i;if("element:asset"!==t.type||t.isComponentInstance)if("annotation:floorPlanImage"===t.type){const s=function(t,e,i){const{view:s,settings:r,loader:n}=i,o=Ex;let a,l;e.x=t.position[0]*o,e.y=t.position[2]*o,e.rotation=-Math.PI/180*t.rotation||0;const{uri:h,length:u,width:c}=t.parameters,d=t.id,p=r.theme.byType["annotation:floorPlanImage"]?.grayscale?Xl.Grayscale:Xl.None,f=n.resources.texture.get(d);return f?.texture?(a=db(f.texture,u*o,c*o),a=_b(a,p),l=new Ty,a.zIndex=1,l.zIndex=5):(n.resources.nodes.set(d,/* @__PURE__ */new Set([t])),n.resources.texture.set(d,{textureUrl:h,applyFilter:p}),bb({loader:n,view:s,resourceId:d}),a=new Ty),[a,l]}(t,e,i);o=s[0],a=s[1]}else o=function(t,e,i,s){const{settings:r}=i,n=Tb(t,e),o=Zl(t);n.push(...o);const a=new Ty,l=nh({element:t,settings:r,style:s});for(const h of n)yb({shape:h,settings:r,gfx:a,style:l,view:i.view});return a}(t,e,i,s);else{const r=Eb(t,e,i,s);o=r[0],l=r.slice(1)}!function(t,e,i){if(!Wn(t))return;const s=t.parent&&t.parent.id!==i?.name?t.getWorldTransform():t.getTransform();e.x=s.position[0]*Ex,e.y=s.position[2]*Ex,e.rotation=-Math.PI/180*s.rotation||0}(t,e,n),!r&&o&&function(t,e,i,s){s.gfxNodes[t.id]=e,i.eventMode="static";let r=t.id;"element"in t&&t.element&&(r=t.element.id),i._nodeId=r}(t,e,o,h),o&&e.addChild(o),a&&e.addChild(a);for(const u of l)u&&e.addChild(u)}function Ib(t,e,{ctx:i,style:s,container:r,preview:n}){const{view:o,settings:a}=e;if(!t?.spaceGraph)return;let l;n||(s?o.styleCache[t.id]=s:!1===s?delete o.styleCache[t.id]:s=o.styleCache[t.id]),r?(l=r,cb(l)):l=new qg;const h=a.hideElements.includes(t.type)||"spatialGraph:edge"===t.type&&!a.showSpaceDividers||"element:spaceDivider"===t.type||"annotation:floorPlanImage"===t.type&&!a.showFloorPlan||"element:asset"===t.type&&"product"in t&&t.product?.attributes?.subCategories?.includes("ceilingLight")&&!a.showCeilingLamps||"space"in t||("element:window"===t.type||"element:door"===t.type)&&!t.parent||e.computed.wallContours.length&&["element:wall","element:boundaryWall","element:column","spatialGraph:edge"].includes(t.type),u=th(t.type);if(l.zIndex=u||0,l.name=t.id,h||Ab(t,l,e,s,n,i),t&&"elements"in t){t.elements.length&&(l.sortableChildren=!0);for(const i of t.elements)Ib(i,e,{ctx:l,style:s,preview:n})}r||i.addChild(l),o.viewportNeedsUpdate=!0}function Sb(t,e){const i=e.getChildByName(t);i?.destroy(!0)}function Cb(t,e,i,s){if(Sb(t.id,e),s.hideElements.includes("roomStamp"))return;const{text:r,textOutline:n=!0}=s.theme?.roomStamps||{},o=s.theme.background.color,a="transparent"!==o?o:"#eee",l=r?(h=r.map(t=>t/255),"#"+((255*h[0]<<16)+(255*h[1]<<8)+(255*h[2]|0)).toString(16).padStart(6,"0")):"#333333";var h;const u=new Ny({fontFamily:s.theme.fontFamily||Sl.theme.fontFamily,fontSize:16,align:"center",fill:l,stroke:a,strokeThickness:n?3:0});let p=t.geometry.polygons;if(0===p.length)return;let f=Pi(p),m=function(t,e){let i=t.getArea(),s=t.attributes.usage;if("void"===Ql(s))return[];let{roomStampDisplay:r}=e.theme?.roomStamps||{};const n=e.spaceLabelMapping||{};let o,a;switch(void 0!==n[s]&&(o=n[s]),void 0!==n[t.id]&&(o=n[t.id]),e.units?.roomDimensions){case"area":a=d(i,e.units.system,e.units.areaDecimals);break;case"boundingBox":{const{min:i,max:s}=t.getBoundingBox(),r=s[0]-i[0],n=s[2]-i[2];a=`${c(r,e.units.system,e.units.lengthDecimals)} x ${c(n,e.units.system,e.units.lengthDecimals)}`;break}default:a=""}let l="";l||"undefined"===s||(l=(s||"").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/^./,t=>t.toUpperCase()).trim()),void 0!==o&&("string"!=typeof o?Nl.warn("space label mapping has to be a string"):o.length>50?Nl.warn("space label mapping has to be less than 50 characters"):l=o),r||(r=[],t.layout.debugIds?r.push("id"):r.push("usage","area"));const h=[];return r.forEach(e=>{switch(e){case"id":let i=fl(t.id)?t.id.substring(0,4):t.id;h.push(i);break;case"name":t.name&&h.push(t.name);break;case"customId":t.customId&&h.push(t.customId);break;case"usage":h.push(l);break;case"area":h.push(a);break;default:Array.isArray(e)&&"customAttribute"===e[0]&&t.customAttributes[e[1]]&&h.push(String(t.customAttributes[e[1]]))}}),h}(t,s),g=m.join("\n");const y=new Fy(g,u);y.x=f[0]*Ex,y.y=f[1]*Ex,y.anchor.x=.5,y.anchor.y=.5,Mb(y,i,t),y.name=t.id,y.eventMode="none",e.addChild(y)}function Mb(t,e,i){let s=Math.min(1/e,2);t.scale.x=s,t.scale.y=s,t.visible=i.getArea()>1.5*s}function Ob(t="linear"){return Yy[t]}function Nb({bb:t,animate:e=!1,view:i}){const s=i._viewport;if(!s)throw new Error("no viewport");return s.destroyed||!s.transform?Promise.resolve(!1):(i.viewportPaused&&i.startAnimationLoop(),new Promise(r=>{if(!Number.isFinite(t.min?.[0]))return r(!1);const{min:n,max:o}=t;let a=n[0],l=n[1];let h=o[0]-a,u=o[1]-l;a*=Ex,l*=Ex,h*=Ex,u*=Ex;let c=0;"number"==typeof e&&Number.isFinite(e)?c=e:!0===e&&(c=500);let d={x:a+h/2,y:l+u/2,width:h,height:u};if(c){let t={x:s.center.x,y:s.center.y,width:s.worldScreenWidth,height:s.worldScreenHeight},e={x:t.x-d.x,y:t.y-d.y,width:t.width-d.width,height:t.height-d.height};i._zoomTarget={delta:e,start:t,target:d,time:0,duration:c,destroy:()=>{i.ticker.remove("animateView"),delete i._zoomTarget,r(!0)},ease:Ob("easeInOutQuad"),updateViewport:Rb.bind(i)},i.ticker.add("animateView",Lb,i)}else s.fit(!1,d.width,d.height).moveCenter(d.x,d.y),Rb.bind(i)({type:"animation"}),i.viewportNeedsUpdate=!0,r(!0)}))}function Lb(t){if(!this._viewport||this._viewport.destroyed||!this._viewport.transform)return void this._zoomTarget?.destroy();let e=this._zoomTarget,i=!1;e.time+=t;let s=e.ease(e.time,0,1,e.duration),r={x:e.start.x-e.delta.x*s,y:e.start.y-e.delta.y*s,width:e.start.width-e.delta.width*s,height:e.start.height-e.delta.height*s};e.time>e.duration&&(r=e.target,i=!0),this._viewport.fit(!1,r.width,r.height).moveCenter(r.x,r.y),this.viewportNeedsUpdate=!0,e.updateViewport({type:"animation"});const n=0!==this._viewport.input.count();(i||n)&&e.destroy()}function Rb(t){this.viewportNeedsUpdate=!0,this.viewportPaused&&this.startAnimationLoop(),"animation"!==t.type&&this._zoomTarget&&this._zoomTarget.destroy();const e=this._viewport,i=Ex,s=e.scale._x,r=e.left,n=e.top,o=e.worldScreenWidth,a=e.worldScreenHeight;this.viewbox={min:[r/i,n/i],max:[(r+o)/i,(n+a)/i]},this.client=[e.screenWidth,e.screenHeight];const l=this.zoom!==s;this.zoom=s;const h={sourceEvent:{type:t.type},viewbox:this.viewbox,zoom:this.zoom};l?this.emit("zoom",h):this.emit("pan",h),this.emit("viewbox",h)}function Bb({position:t,nodeId:e}){kb(this.interaction,{cursor:t,cursorTarget:e&&this.layout&&(this.layout.elementsById[e]||this.layout.spacesById[e])})}function kb(t,e){for(const i in e)t[i]=e[i],"cursorAction"===i&&Fb(e[i])}function Fb(t){let e="";switch(t){case"split-wall":e="var(--fpe-split-cursor) 16 16, pointer";break;case"duplicate":e="var(--fpe-duplicate-cursor) 16 16, pointer";break;case"move":e="move";break;default:e="default"}document.body.style.cursor=e}function Db(t){if(2===t?.data?.originalEvent?.button)return;if(!this||!this.view)throw new Error("Viewport context is missing");let e=this.interaction._dragStart||{x:0,y:0},i=t.data.global||{x:0,y:0},s=Math.abs(i.x-e.x),r=Math.abs(i.y-e.y);if(!(s<5&&r<5))return;let n,o=/* @__PURE__ */(new Date).getTime();if(this.interaction.lastClick){let t=o-this.interaction.lastClick.time,e=this.interaction.lastClick.position&&Math.max(Math.abs(i.x-this.interaction.lastClick.position.x),Math.abs(i.y-this.interaction.lastClick.position.y));n=t<400&&e<10}this.interaction.lastClick={time:o,position:{...i}};const a=n?"dblclick":"click",l=t.target?._nodeId,{x:h,y:u}=t.data?.global||{},c=this.getPlanPosition([h,u]);kb(this.interaction,{cursor:[c[0],c[1]]});let d={sourceEvent:t,nodeId:l,position:c,isDoubleClick:!!n};this.emit(a,d)}function Ub(t){const{x:e,y:i}=t.data.global;this.view.windowPos=[e,i];const s=this.getPlanPosition(this.view.windowPos);this.interaction.lastSceneClick=s;const r=t.target?._nodeId;this.emit("context-menu",{sourceEvent:t,nodeId:r,position:s})}function Gb(t){t.drag().pinch({percent:4}).wheel()}function Xb(t){t.plugins.remove("wheel"),t.plugins.remove("pinch"),t.plugins.remove("drag")}function Wb(t){const{settings:e,view:i}=t;e.panZoom&&Gb(i._viewport),i._viewport.on("pointerdown",Yb,t).on("pointerup",Hb,t).on("pointerup",Db,t).on("rightup",Ub,t).on("pointerupoutside",Hb,t).on("globalpointermove",$b,t).on("moved",Rb,i).on("zoomed",Rb,i);const s=jb(t),r=(t=>{const{view:e,interaction:i}=t,s=(s,r)=>{e.viewportInFocus&&("Alt"===s.key&&"keyup"===r&&i.preventFocusoutOnAltKeyup&&s.preventDefault(),i.shiftKey=s.shiftKey,i.ctrlKey=s.ctrlKey,i.altKey=s.altKey,i.metaKey=s.metaKey,t.emit(r,{key:s.key,lowerCaseKey:s.key&&s.key.toLowerCase(),sourceEvent:s}))},r=t=>s(t,"keyup"),n=t=>s(t,"key");return document.addEventListener("keydown",n),document.addEventListener("keyup",r),()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r)}})(t);return t.on("mousemove",Bb,t),()=>{e.panZoom&&Xb(i._viewport),i._viewport.destroyed||i._viewport.off("pointerdown",Yb).off("pointerup",Hb).off("pointerup",Db).off("rightup",Ub).off("pointerupoutside",Hb).off("globalpointermove",$b).off("moved",Rb).off("zoomed",Rb),s?.(),r?.(),t.off("mousemove",Bb)}}function Yb(t){this.interaction._dragStart={x:t.data.global.x,y:t.data.global.y};const e=t.data.getLocalPosition(this.view._viewport);this.emit("drag-start",{position:this.interaction.cursor,sourceEvent:t,screenPos:[e.x,e.y]})}function Hb(t){this.view.resume("drag");const e=t.data.getLocalPosition(this.view._viewport);this.emit("drag-end",{position:this.interaction.cursor,sourceEvent:t,screenPos:[e.x,e.y]}),this.interaction.isDragging=!1,this.interaction.dragOffset=null}function $b(t){const{srcElement:e}=t?.data?.originalEvent||{};if(!e||!this.view._renderer)return;if(!(e===this.view._renderer.view)&&!this.interaction.isDragging)return;const i=t.data.getLocalPosition(this.view._viewport);let s=[i.x/Ex,i.y/Ex];const r=t.target&&t.target._nodeId;if(this.interaction.cursor=s,this.interaction.isDragging){const e=[i.x,i.y];this.emit("drag-move",{position:this.interaction.cursor,screenPos:e,sourceEvent:t})}this.emit("mousemove",{sourceEvent:t,nodeId:r,position:s})}const jb=t=>{const e=document.querySelector(`#${t.fpeId} .fpe__plan`);if(!e)return()=>{};const i=()=>t.view.emit("focus",!1,t.view),s=()=>t.view.emit("focus",!0,t.view),r=()=>t.view.emit("focus","visible"===document.visibilityState,t.view),n=t=>(t.preventDefault(),!1);return e.addEventListener("mouseleave",i),e.addEventListener("mouseenter",s),document.addEventListener("visibilitychange",r),e.addEventListener("contextmenu",n,!1),()=>{e.removeEventListener("mouseleave",i),e.removeEventListener("mouseenter",s),document.removeEventListener("visibilitychange",r),e.removeEventListener("contextmenu",n,!1)}};const zb=t=>`floor-${t.id}`,Vb=t=>`fpe-room-stamp-floor-${t.id.substring(0,8)}`;function qb(t,e){t.x=e.position[0]*Ex,t.y=e.position[2]*Ex,t.rotation=-Math.PI/180*e.rotation||0}function Jb(t,e,i,s){for(let r of e.spaces)Ib(r,t,i);for(let r of e.elements)Ib(r,t,i);for(let r of e.annotations)Ib(r,t,i);for(let r of e.spatialGraph.edges)Ib(r,t,i);t.computed.wallContours.length&&function(t,e){const{ctx:i,style:s}=e,{wallContours:r}=t.computed,n="wallContours",o=r.map(t=>({type:"curve:polygonWithHoles",polygons:t}));let a=i.getChildByName(n);a?cb(a):(a=new qg,a.name=n);const l=th("element:wall");a.zIndex=l||0;const h=nh({style:s,settings:t.settings,elementType:"element:wall"}),u=new Ty;for(const c of o)yb({shape:c,gfx:u,style:h});a.addChild(u),i.addChild(a)}(t,i),Qb(t,!0,s,e)}const Kb=t=>`fpe-room-stamp-${t.id.substring(0,8)}`;function Zb({floorPlan:t,update:e=!1}){const{layout:i,view:s,settings:r}=t,{_renderer:n,_viewport:o}=s;if(!n||!i)return;let a=r.theme.background.color;4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),n.background.color=new hb(a).toNumber();const l=s.gfxLayers.scene;if(cb(l),e||(s.styleCache={}),s.floorContainers.clear(),s.roomStampLayers.clear(),t.building&&r.loadFloorLevel){const e=t.building.floorsByLevel[r.loadFloorLevel]||[];for(const i of e){const e=i.layouts[0];if(!e)continue;const r=new qg;r.name=zb(i),qb(r,i),l.addChild(r),s.floorContainers.set(i.id,r);const n=t.addLayer({id:Vb(i),baseLayer:"annotation"});qb(n.container,i),s.roomStampLayers.set(i.id,n),Jb(t,e,{ctx:r},n)}}else Jb(t,i,{ctx:l});s.emit("scene-rendered",{update:e}),s.viewportNeedsUpdate=!0,e&&(r.panZoom?Gb(o):Xb(o)),s.viewportPaused&&s.startAnimationLoop()}function Qb(t,e=!1,i,s){const{view:r,settings:n}=t,o=s??t.layout;o&&(i??=t.addLayer({id:Kb(o),baseLayer:"annotation"}),e?(cb(i.container),o.spaces.forEach(t=>Cb(t,i.container,r.zoom,n))):i.container.children.forEach(t=>{let e=o.spaces.find(e=>e.id===t.name);Mb(t,r.zoom,e)}))}function tw(t){const{shapeLayers:e}=t.settings;for(const i in e){const s=e[i];t.addLayer({id:i}).addGraphic({shapes:s})}}Wp.add(um),Wp.add(ov),Wp.add(wv),Wp.add(Fv),Wp.add(Uv);class ew extends Px{}const iw=(t,e,i)=>{const s=t.getChildByName(e);if(s)return cb(s),s;{const s=new qg;return s.sortableChildren=!0,s.zIndex=i,s.name=e,t.addChild(s),s}},sw={top:0,left:0,center:.5,right:1,bottom:1};class rw{constructor(){this.methods={},this.add=(t,e,i)=>{this.methods[t]={fn:e,ctx:i}},this.remove=t=>{delete this.methods[t]}}}class nw extends Ix.TinyEmitter{constructor(t,e,i){super(),this.windowPos=[0,0],this.zoom=1,this.client=[0,0],this.layers=/* @__PURE__ */new Map,this.viewbox={min:[0,0],max:[0,0]},this.styleCache={},this.viewportNeedsUpdate=!1,this.viewportPaused=!1,this.viewportInFocus=!1,this.wallNodesToUpdate=[],this.wallNodeUpdateInProgress=!1,this.floorContainers=/* @__PURE__ */new Map,this.roomStampLayers=/* @__PURE__ */new Map,this.textureCache=/* @__PURE__ */new Map,this.gfxNodes={},this._canvasMargin={x:0,y:0},this.ticker=new rw,this._resizeRafId=null,this._oldTime=Date.now(),this.parentEl=i;const s=this.parentEl.querySelector(".fpe__canvas");let r=this.parentEl.clientWidth,n=this.parentEl.clientHeight;this._settings=e;const o=window.devicePixelRatio||1;let a=e.theme.background.color;const l="transparent"===a;4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),this._renderer=function(t){for(const e of Ig)if(e.test(t))return new e(t);throw new Error("Unable to auto-detect a suitable renderer.")}({width:r,height:n,view:s,antialias:!0,hello:!1,backgroundAlpha:l?0:1,autoDensity:!0,resolution:o,powerPreference:"high-performance",preserveDrawingBuffer:!0,backgroundColor:l?new hb(a).toNumber():void 0}),this.parentEl.appendChild(this._renderer.view),4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),l||(this._renderer.background.color=new hb(a).toNumber()),this._stage=new qg,this._stage.sortableChildren=!0,this._viewport=new ew({screenWidth:r,screenHeight:n,worldWidth:r,worldHeight:n,events:this._renderer.events,noTicker:!0,passiveWheel:!1,allowPreserveDragOutside:!0}),Tg?.system&&Tg.system.stop(),this.startAnimationLoop(),this.watchResize(),this._stage.addChild(this._viewport),this.on("focus",t=>{t&&this.viewportPaused?this.startAnimationLoop():t||this.stopAnimationLoop(),this.viewportInFocus=t}),this.gfxLayers=ow(this._viewport),xb(this,t)}draw(){if(this.parentEl&&!this.parentEl.isConnected)return void this.destroy();if(!this._viewport||this._viewport?.destroyed||!this._renderer)return;const t=Date.now();let e=t-this._oldTime;this._oldTime=t,e<0&&(e=0),e>1e3&&(e=1e3);let i=Object.keys(this.ticker.methods).length;(this.viewportNeedsUpdate||i)&&(this.ticker?.methods&&Object.values(this.ticker.methods).forEach(({fn:t,ctx:i})=>{"function"==typeof t&&(i?t.call(i,e):t(e))}),this._viewport.update(e),this._renderer.render(this._stage)),this.viewportPaused||requestAnimationFrame(()=>this.draw()),this.viewportNeedsUpdate=!1}startAnimationLoop(){this._oldTime=Date.now(),this.viewportNeedsUpdate=!0,this.viewportPaused=!1,requestAnimationFrame(()=>this.draw())}stopAnimationLoop(){this.viewportPaused=!0}updateView(){if(this._viewport?.destroyed||!this._renderer)return;if(!this.parentEl.clientWidth||!this.parentEl.clientHeight)return;const t=this._viewport,e=this._renderer,i=Ex,s=t.screenWidth,r=t.screenHeight,n=this.parentEl.clientWidth-this._canvasMargin.x,o=this.parentEl.clientHeight-this._canvasMargin.y;e.resize(n,o),t.resize(n,o);const a=this._settings.preserveViewbox;if("screen-space"===a&&this._lastCanvasRect){const e=this.parentEl.getBoundingClientRect(),i=e.left-this._lastCanvasRect.left,s=e.top-this._lastCanvasRect.top;t.position.set(t.x-i,t.y-s),this._lastCanvasRect=e}else{const e=s-n,i=r-o,[l=.5,h=.5]=a.split("-").map(t=>sw[t]),u=l*e,c=h*i;t.position.set(t.x-u,t.y-c)}t.plugins.get("clamp-zoom")||t.clampZoom({minHeight:this._settings.zoomRange[0]*i,maxHeight:this._settings.zoomRange[1]*i}),e.render(this._stage);let l=t.left,h=t.top,u=t.worldScreenWidth,c=t.worldScreenHeight;this.viewbox={min:[l/i,h/i],max:[(l+u)/i,(h+c)/i]},this.client=[t.screenWidth,t.screenHeight]}async watchResize(){this._canvasMargin.x=this.parentEl.clientWidth-this._viewport.screenWidth,this._canvasMargin.y=this.parentEl.clientHeight-this._viewport.screenHeight,"screen-space"===this._settings.preserveViewbox&&(this._lastCanvasRect=this.parentEl.getBoundingClientRect()),this._resizeObserver=new ResizeObserver(()=>{null===this._resizeRafId&&(this.updateView(),this.emit("resize-canvas",this.viewbox),this._resizeRafId=requestAnimationFrame(()=>{if(this._resizeRafId=null,!this.parentEl)return;const t=this.parentEl.clientWidth-this._canvasMargin.x,e=this.parentEl.clientHeight-this._canvasMargin.y;t===this._viewport.screenWidth&&e===this._viewport.screenHeight||(this.updateView(),this.emit("resize-canvas",this.viewbox))}))}),this._resizeObserver.observe(this.parentEl)}get gfxNodeCount(){return Object.keys(this.gfxNodes).length}reset(){this.styleCache={},this.gfxNodes={},this.floorContainers.clear(),this.roomStampLayers.clear(),this.textureCache.forEach(t=>t.destroy()),this.textureCache.clear(),this.gfxLayers=ow(this._viewport)}pause(t="drag"){this._viewport.plugins.pause(t)}resume(t="drag"){this._viewport.plugins.resume(t)}destroy(){this.stopAnimationLoop(),null!==this._resizeRafId&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=null),this._resizeObserver?.disconnect(),this.textureCache.forEach(t=>t.destroy()),this.textureCache.clear(),this._viewport&&!this._viewport.destroyed&&this._viewport.destroy(),this._renderer?.destroy(!0),this._renderer=void 0}}const ow=t=>{t.sortableChildren=!0;return{base:iw(t,"base",0),scene:iw(t,"scene",1),preview:iw(t,"preview",2),annotation:iw(t,"annotation",3),helper:iw(t,"helper",4)}};function aw(t,e,i){e=e||this;const{view:s,settings:r}=e,n=s.gfxNodes[t.id];if(n&&!n.destroyed){if("layout:space"===t.type){const e=Kb(t.layout),i=s.layers.get(e);i&&Cb(t,i.container,s.zoom,r)}Ib(t,e,{ctx:n.parent,container:n,...i}),s.viewportNeedsUpdate=!0,s.viewportPaused&&s.startAnimationLoop()}}class lw{constructor({shapes:t=[],position:e=[0,0],alpha:i=1,scale:s=1,clearLayer:r=!1,interactive:n=!1,id:o,isHandler:a=!1,scaleOnZoom:l=!1,updatePositionOnDrag:h=!1,baseLayer:u,container:c,floorPlan:d}){if(this.shapes=t,this.gfxScale=s,this.scaleOnZoom=l,this.container=c,this.floorPlan=d,!this.container)return;r&&cb(this.container);let p=new Ty;this.gfx=p,p.alpha=i;const f=Math.min(1/this.floorPlan.view.zoom)*this.gfxScale;e&&(p.x=e[0]*Ex,p.y=e[1]*Ex),p.eventMode=n?"static":"none",p._nodeId=o,a&&(p._isHandler=!0),h&&this.on("drag",this.doUpdatePositionOnDrag,this),f&&l&&(p.scale.x=p.scale.y=f),u.addChild(this.container),this.container.addChild(p),t.forEach(t=>yb({shape:t,settings:this.floorPlan.settings,gfx:p,view:this.floorPlan.view})),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}set({position:t,rotation:e,style:i,shapes:s}={}){const r=Math.min(1/this.floorPlan.view.zoom)*this.gfxScale,n=this.gfx;if(function(t,{position:e,rotation:i}){e&&(t.x=e[0]*Ex,t.y=e[1]*Ex),i&&(t.rotation=-Math.PI/180*i)}(n,{position:t,rotation:e}),s&&(this.shapes=s,n.clear(),cb(n),s.forEach(t=>yb({shape:t,settings:this.floorPlan.settings,gfx:n,view:this.floorPlan.view}))),r&&this.scaleOnZoom&&(n.scale.x=n.scale.y=r),i){const t=mb(i);i.fill&&(n.geometry.graphicsData[0].fillStyle.color=eh(i.fill)),n.geometry.graphicsData[0].lineStyle.color=Number(t.color),n.geometry.graphicsData[0].lineStyle.width=t.width,n.geometry.graphicsData[0].lineStyle.native=t.native,n.geometry.invalidate()}this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}doUpdatePositionOnDrag({position:t}){this.set({position:t})}on(t,e,i){return this.gfx.eventMode="static","drag"===t?this.addDragEvent(e,i):this.gfx.on(t,e,i),this}off(t,e){return"drag"===t?this.removeDragEvent():this.gfx.off(t,e),this}destroy(){this.off("drag"),this.gfx.destroy(),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}addDragEvent(t,e){function i(){this.floorPlan.interaction.isDragging=!1,this.floorPlan.view.resume("drag"),this.floorPlan.off("mousemove",t)}this.on("pointerdown",function(){this.floorPlan.interaction.isDragging=!0,this.floorPlan.view.pause("drag"),this.floorPlan.on("mousemove",t,e)},this),this.on("pointerup",i,this),this.on("pointerupoutside",i,this),this.on("pointercancel",i,this)}removeDragEvent(){this.off("pointerdown"),this.off("pointerup"),this.off("pointerupoutside"),this.off("pointercancel")}}class hw{constructor(t,e,i){this.graphics=/* @__PURE__ */new Set,this.container=new qg,this.id=i,this.baseLayer=t.view.gfxLayers[e]||t.view.gfxLayers.helper,this.floorPlan=t,this.baseLayer.addChild(this.container)}addGraphic(t){const e=new lw({...t,floorPlan:this.floorPlan,baseLayer:this.baseLayer,container:this.container});return this.graphics.add(e),e}findGraphic(t){return this.container.getChildByName(t)}deleteGraphic(t){this.graphics.delete(t),t.destroy()}clear(){cb(this.container),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}destroy(){this.container&&(this.floorPlan.view.layers.delete(this.id),this.container.destroy({children:!0,texture:!0,baseTexture:!0}),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop(),delete this.container,delete this.floorPlan)}}function uw(t,{format:e,fileName:i,quality:s}={}){if("svg"===e)return;const r=new Image;r.src=t,r.onload=function(){const t=document.createElement("canvas");t.width=r.naturalWidth,t.height=r.naturalHeight;const n=t.getContext("2d");n.imageSmoothingEnabled=!1,n.drawImage(r,0,0),function(t,{format:e="png",fileName:i="floorplan",quality:s=.95}){let r="png"===e?"image/png":"image/jpeg";t.toBlob(function(t){!function({fileName:t,href:e,ext:i}){const s=document.createElement("a");Object.assign(s,{href:e,download:p(t,i),target:"_blank",rel:"noopener",style:"display:none;"}),document.body.appendChild(s),s.click(),document.body.removeChild(s)}({fileName:i,href:URL.createObjectURL(t),ext:e})},r,s)}(t,{format:e,fileName:i,quality:s})}}const cw=Tl,dw=Tl,pw=Tl,fw=Tl,mw=Tl,gw=gl;class yw extends Sx{constructor({floorPlan:t,helperId:e,mode:i="distance"}){super({floorPlan:t,helperId:e}),this.drawing=!1,this.polygonsOrPolylines=[],this.floorPlan=t,this.mode=i,this.floorPlan.on("mousemove",this.handlePointerMove,this),this.floorPlan.on("click",this.handlePointerDown,this),this.floorPlan.on("dblclick",this.handlePointerDown,this),this.floorPlan.on("update-settings",this.draw,this),this.startDrawing()}get isInAreaMode(){return"area"===this.mode}get isDrawing(){return this.drawing}set({mode:t}){this.mode=t,this.draw()}handlePointerMove(t){this.setSnapCursor(t)}handlePointerDown(t){this.setSnapCursor(t),this.drawPoint(t)}setSnapCursor({position:t}){this._snapCursor??=this.floorPlan.addHelper("snapCursor",{position:t});const{snapPoints:e,snapMargin:i}=this.floorPlan.computed;if(!e.length)return this._snapCursor.set({position:t}),void this.draw();const s=uh(t,e,i);this._snapCursor.isSnapping=!!s,this._snapCursor.set({position:s||t}),this.draw()}stopDrawing(){this.polygonsOrPolylines[this.polygonsOrPolylines.length-1].points.length>1&&this.drawing&&this.polygonDone()}cancelDrawing(){this.destroy()}startDrawing(){this.drawing=!0,this.polygonsOrPolylines.push({points:[],isClosed:!1,length:0,area:0,areaDisplay:"",lengthDisplay:"",contour:null,label:null,pointGraphics:[]})}removeLastPoint(){const t=this.polygonsOrPolylines[this.polygonsOrPolylines.length-1];if(t?.points.length>0){t.points.pop();const e=t.pointGraphics.pop();e&&this.layer.deleteGraphic(e),t.points.length<=1&&(t.contour&&(this.layer?.deleteGraphic(t.contour),t.contour=null),t.label&&(this.layer?.deleteGraphic(t.label),t.label=null)),0===t.points.length?(this.polygonsOrPolylines.pop(),this.drawing=!1):this.draw()}}polygonDone(){this.drawing=!1,this.emit("polygon-done",{}),this.draw()}drawPoint(t){this.drawing||this.startDrawing();const e=this.polygonsOrPolylines.length-1,i=this.polygonsOrPolylines[e],s=t.nodeId?.startsWith(`point/${e}/`);if(s||t.isDoubleClick){const s=t.nodeId===`point/${e}/0`;return"distance"===this.mode&&s&&(i.isClosed=!0),void this.polygonDone()}const{position:r}=this._snapCursor;i.points.push([...r]);const n=i.points.length-1,o=`point/${e}/${n}`;this.layer||(this.layer=this.floorPlan.addLayer());const a=this.layer.addGraphic({shapes:[{type:"curve:circle",position:[0,0],radius:.15,style:{fill:fw,fillOpacity:.1}},{type:"curve:circle",position:[0,0],radius:.05,style:{stroke:mw,fill:gw,strokeWidth:1.5}}],position:r,scaleOnZoom:!0,id:o,isHandler:!0});i.pointGraphics[n]=a,a.on("drag",function(){this.updatePolygon(e,n,this.floorPlan.interaction.cursor),a.set({position:i.points[n]})},this)}updatePolygon(t,e,i){const s=i,{snapPoints:r,snapMargin:n}=this.floorPlan.computed,o=r.length&&uh(s,r,n);this.polygonsOrPolylines[t].points[e]=o||s,this.draw()}getLengthText(t){const{units:e}=this.floorPlan.settings;return c(t,e.system,e.lengthDecimals)}getAreaText(t){const{units:e}=this.floorPlan.settings;return d(t,e.system,e.areaDecimals)}reset(){this.drawing=!1,this.polygonsOrPolylines=[],this.floorPlan.removeHelper("snapCursor"),this._snapCursor=null,this.layer&&(this.layer.destroy(),this.layer=null)}draw(){this.polygonsOrPolylines.length&&(this.layer||(this.layer=this.floorPlan.addLayer()),this.polygonsOrPolylines.forEach((t,e)=>{if(!t.points.length)return;const i=this.drawing&&this._snapCursor&&e===this.polygonsOrPolylines.length-1?[...t.points,this._snapCursor.position]:t.points;if(i.length<2)return;t.length=function(t,e=!0){let i=0,s=e?t.length:t.length-1;for(var r=0;r<s;r++){let e=r,s=r<t.length-1?r+1:0;i+=ni(t[e],t[s])}return i}(i,t.isClosed),t.lengthDisplay=this.getLengthText(t.length);const s=i.length<2?0:180*gi(i[0],i[1])/Math.PI,r=i.map(t=>t.map(t=>Number(t.toFixed(10)))).slice(0,this.isInAreaMode?void 0:2),n=this.isInAreaMode?Pi([r]):[r[0][0]+(r[1][0]-r[0][0])/2,r[0][1]+(r[1][1]-r[0][1])/2];t.area=Math.abs(J(i)),t.areaDisplay=this.getAreaText(t.area);const o=this.isInAreaMode||t.isClosed?"curve:polygon":"curve:polyline",a={stroke:pw,dash:!0,strokeWidth:"native"};let l=t.lengthDisplay,h=-s;this.isInAreaMode&&(a.fill=dw,a.fillOpacity=.04,l=t.areaDisplay,h=0);const u=[{type:o,points:i,style:a}],c={shapes:[{type:"text",text:l,position:[0,0],rotation:h,alignV:"bottom",fontSize:15,style:{fill:cw}}],id:"text",position:n,scaleOnZoom:!0};t.contour?t.contour.set({shapes:u}):t.contour=this.layer.addGraphic({shapes:u}),t.label?t.label.set(c):t.label=this.layer.addGraphic(c);const d=this.isInAreaMode?{area:t.area}:{distance:t.length};this.emit("polygon-draw",d)}))}destroy(){this.reset(),this.floorPlan.off("mousemove",this.handlePointerMove),this.floorPlan.off("click",this.handlePointerDown),this.floorPlan.off("dblclick",this.handlePointerDown),this.floorPlan.off("update-settings",this.draw),super.destroy()}}class vw extends Sx{constructor({floorPlan:t,helperId:e,position:i}){super({floorPlan:t,helperId:e}),this.position=[0,0],this.floorPlan.on("mousemove",this.draw,this),this.isSnapping=!1,this.isEdge=!1,this.isError=!1,i&&(this.position=i)}draw(){if(this.floorPlan)if(this.layer||(this.layer=this.floorPlan.addLayer({id:"fpe-snap-cursor"})),this.cursor){let t=vl;this.isError?t=Il:this.isSnapping&&(t=Tl);const e=this.isSnapping?2:1.5;this.cursor.set({position:this.position,style:{stroke:t,strokeWidth:e}})}else this.cursor=this.layer.addGraphic({shapes:[{type:"curve:circle",position:[0,0],radius:.06,style:{stroke:Tl,strokeWidth:1.5}}],position:this.position,scaleOnZoom:!0})}set({position:t,isSnapping:e,isEdge:i,isError:s}){this.position=t,this.isSnapping=e,this.isEdge=i,this.isError=s,this.draw()}snapState(){return this.isSnapping?this.isEdge?"edge":"point":""}destroy(){this.floorPlan?.off("mousemove",this.draw),this.layer&&this.layer.destroy(),this.layer=void 0,this.cursor=null,super.destroy()}}function xw(t,e){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: node ID change, type ${t.type}, previous ID ${e}`),this.drawNodeUpdate(t.id))}function bw(t,e){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: node property change, type ${t.type}, property name ${e}`),this.drawNodeUpdate(t.id))}function ww(t){this.preventUpdateOnSpaceGraphEvent||Nl.debug(`${t.id}: vertex create`)}function _w(t){this.preventUpdateOnSpaceGraphEvent||Nl.debug(`${t.id}: vertex delete`)}function Pw(t){if(!this.preventUpdateOnSpaceGraphEvent){Nl.debug(`${t.id}: vertex set position`);for(let e of t.edges)this.drawNodeUpdate(e.id)}}function Ew(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: edge create`),this.drawNodeUpdate(t.id))}function Tw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: edge delete`),this.drawNodeUpdate(t.id))}function Aw(t,e){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: edge set vertices`),this.drawNodeUpdate(t.id))}function Iw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: space create`),this.drawNodeUpdate(t.id))}function Sw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: space delete`),this.drawNodeUpdate(t.id))}function Cw(t,e){this.preventUpdateOnSpaceGraphEvent||Nl.debug(`${t.id}: space split into ${e[0].id} and ${e[1].id}`)}function Mw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: space attributes change`),this.drawNodeUpdate(t.id))}function Ow(t){this.preventUpdateOnSpaceGraphEvent||"layout:space"!==t.type||(Nl.debug(`${t.id}: custom attributes change`),this.drawNodeUpdate(t.id))}function Nw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: element create, type ${t.type}`),this.drawNodeUpdate(t.id))}function Lw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: element delete, type ${t.type}`),this.drawNodeUpdate(t.id))}function Rw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: element transform change, type ${t.type}`),this.drawNodeUpdate(t.id))}function Bw(t){if(!this.preventUpdateOnSpaceGraphEvent)if(Nl.debug(`${t.id}: element parameters change, type ${t.type}`),"element:wall"===t.type){let e=t.getAdjacentElementsByVertex().flat();if(this.view.wallNodesToUpdate.push(t.id,...e.map(t=>t.id)),this.view.wallNodeUpdateInProgress)return;this.view.wallNodeUpdateInProgress=!0,setTimeout(()=>{const t=new Set(this.view.wallNodesToUpdate);Ia(this.layout);for(const e of t)this.drawNodeUpdate(e);this.view.wallNodeUpdateInProgress=!1,this.view.wallNodesToUpdate=[]})}else Br(t),this.drawNodeUpdate(t.id)}function kw(t){this.preventUpdateOnSpaceGraphEvent||queueMicrotask(()=>this.drawNodeUpdate(t.id))}function Fw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: annotation change, type ${t.type}`),this.drawNodeUpdate(t.id))}function Dw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: geometry profile update`),this.drawNodeUpdate(t.id))}function Uw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: geometry update`),["element:boundaryWall","element:generic"].includes(t.type)&&this.drawNodeUpdate(t.id))}function Gw(t){this.preventUpdateOnSpaceGraphEvent||(Nl.debug(`${t.id}: floor transform change`),function(t,e){const{view:i}=t,s=i.floorContainers.get(e.id),r=i.roomStampLayers.get(e.id);s&&!s.destroyed&&qb(s,e),r?.container&&!r.container.destroyed&&qb(r.container,e),i.viewportNeedsUpdate=!0}(this,t))}function Xw(t){const e=t.addLayer({id:"fpe-grid-lines",baseLayer:"base"});let i;function s(t,e,s=!1){const r=Ex;if(!t)return;let n;if(n=e.view.zoom>2?.1:e.view.zoom>.25?1:(e.view.zoom,10),!s&&n===i)return;if(cb(t),!e.settings.theme.background.showGrid)return;const o=new Ty;let a=eh(Pl);o.lineStyle({width:1,color:a,native:!0});for(let i=-100;i<100;i+=n)Math.round(100*i)/100==0?o.lineStyle({width:2,color:a,native:!0}):(Math.round(100*i)/100%10==0||Math.round(100*i),o.lineStyle({width:1,color:a,native:!0})),o.moveTo(-1e4,i*r),o.lineTo(1e4,i*r),o.moveTo(i*r,-1e4),o.lineTo(i*r,1e4);t.addChild(o),i=n}return s(e?.container,t),{update:i=>s(e.container,t,i)}}function Ww(t,e="Floor plan engine couldn't load properly on this page. For technical details check the browser console."){const i=t.querySelector(".fpe-err")??function(t){const e=document.createElement("div"),i=document.createElement("div"),s=document.createElement("div"),r=document.createElement("div");return e.classList.add("fpe-err"),i.classList.add("fpe-err__box"),s.classList.add("fpe-err__title"),r.classList.add("fpe-err__msg"),t.append(e),e.append(i),i.append(s),i.append(r),s.textContent="Something went wrong",t.append(e),t}(t);i.querySelector(".fpe-err__msg").textContent=e}const Yw={lastSceneClick:[0,0],cursor:[0,0],cursorTarget:null,isDragging:!1,altKey:!1,shiftKey:!1,metaKey:!1,ctrlKey:!1,dragOffset:null,cursorAction:"none",isPanning:!1,lastClick:{time:null,position:{x:0,y:0}},_dragStart:{x:0,y:0},preventFocusoutOnAltKeyup:!1};class Hw extends Jl{constructor({container:t,options:e={}}={}){let i;super({options:e}),this.interaction=Yw,this.availableHelpers={cursorCoordinates:Cx,scaleBar:Mx},this.helper={},this.preventUpdateOnSpaceGraphEvent=!1,this.#t=Sl.theme.fontFamily,i=t instanceof Element?t:document.body,this.mountFloorPlan(i),this.availableHelpers.polygonHelper=yw,this.availableHelpers.snapCursor=vw,this.on("space-api-floor-error",(t,e)=>{Ww(this.fpeNode,e)}),this.on("space-api-floor-loaded",()=>{!function(t){t.querySelector(".fpe-err")?.remove()}(this.fpeNode)})}#t;#e;prevent(t){t.preventDefault()}on(t,e,i){return this._emitter.on(t,e,i),this}once(t,e,i){return this._emitter.once(t,e,i),this}off(t,e,i){return this._emitter.off(t,e),this}emit(t,...e){return this._emitter.emit(t,...e),this}handleDrop(t){t.preventDefault(),t.stopPropagation();const e=[t.offsetX,t.offsetY],i=this.getPlanPosition(e);this.interaction.cursor=[...i];const{spaces:s}=this.getResourcesFromPosition(i),r=s[0]?.slabs.find(t=>"element:floor"===t.type),n=r?.parameters.elevation||0;this.emit("drop",{position:i,sourceEvent:t,verticalPos:n,screenPos:e})}set(t){super.set(t),this.view&&(Zb({floorPlan:this,update:!0}),tw(this),Xw(this))}drawNodePreview(t,e,i,s){Ib(e?.elementsById[t]||e?.spacesById[t]||e?.spatialGraph.edgesById[t],this,{preview:!0,style:s,ctx:i.container})}#i(t){let e=this.layout?.elementsById[t]||this.layout?.spacesById[t]||this.layout?.annotationsById[t]||this.layout?.spatialGraph.edgesById[t];if(!e&&this.building&&this.settings.loadFloorLevel){const i=this.building.floorsByLevel[this.settings.loadFloorLevel]||[];for(const s of i){const i=s.layouts[0];if(i&&(e=i.elementsById[t]||i.spacesById[t]||i.annotationsById[t]||i.spatialGraph.edgesById[t],e))break}}return e}drawNodeUpdate(t,e){if(!this.layout)return;let i=this.#i(t);if(function(t,e){const i=t.settings?.theme?.byFilter,s=t.settings?.theme?.byResolvedFilter;if(i&&s&&t.layout){delete s[e];for(const r of i)Va(t.layout,{id:e,where:r.where})&&"style"in r&&(s[e]=r.style)}}(this,t),i)if(this.view.gfxNodes[t]&&!this.view.gfxNodes[t].destroyed)aw(i,this,{style:e});else{let t=this.view.gfxLayers.scene;"parent"in i&&this.view.gfxNodes[i.parent?.id]&&(t=this.view.gfxNodes[i.parent.id]),Ib(i,this,{ctx:t,style:e})}else!function(t,e){const i=e.view.gfxNodes[t];if(i&&(i.parent?.removeChild(i),i.destroy({children:!0})),delete e.view.gfxNodes[t],delete e.view.styleCache[t],e.layout){const i=Kb(e.layout),s=e.getLayer(i);s?.container&&Sb(t,s.container)}e.view.viewportNeedsUpdate=!0,e.view.viewportPaused&&e.view.startAnimationLoop()}(t,this);if(i&&"getEdges"in i)for(const s of i.getEdges())this.drawNodeUpdate(s.id,e)}drawResourceUpdate({resourceId:t}){const e=this.loader.resources.nodes.get(t);if(e)for(const i of e)aw(i,this,{})}mountFloorPlan(t){const e=t.querySelector(".fpe");e&&e.remove();const i=document.createElement("div");i.id=this.fpeId,i.classList.add("fpe"),t.appendChild(i);const s=document.createElement("div");s.classList.add("fpe__plan");const r=document.createElement("canvas");r.setAttribute("alt","fpe-canvas"),r.classList.add("fpe__canvas"),i.appendChild(s),s.appendChild(r),this.fpeNode=i;try{i.style.setProperty("--fpe-font-family",this.settings.theme.fontFamily)}catch(n){console.warn("Failed to set font-family",n)}this.view=new nw(this.loader,this.settings,s),this.loader.on("resource-loaded",this.drawResourceUpdate,this),this.loader.on("spaces-loaded",this.initDrawing,this),r.addEventListener("drop",this.handleDrop.bind(this)),r.addEventListener("gesturestart",this.prevent),r.addEventListener("gesturechange",this.prevent),r.addEventListener("gestureend",this.prevent),r.addEventListener("dragover",this.prevent),this.settings.destroyOnDomRemove&&function(t,e,i){const s=new MutationObserver(()=>{(function t(i){return i.parentNode!==e&&(null===i.parentNode||t(i.parentNode))})(t)&&(s.disconnect(),i())});s.observe(e,{childList:!0,subtree:!0})}(i,t,()=>this.destroy()),this.#e=Wb(this),this.view.on("scene-rendered",({update:t})=>{t||this.zoomExtents(1,0)}),this.view.on("zoom",()=>{if(this.view.layers.forEach(t=>{t.graphics.forEach(t=>{t.scaleOnZoom&&!t.gfx.destroyed&&t.set()})}),this.building&&this.settings.loadFloorLevel){const t=this.building.floorsByLevel[this.settings.loadFloorLevel]||[];for(const e of t){const t=e.layouts[0],i=this.view.roomStampLayers.get(e.id);t&&i&&Qb(this,!1,i,t)}}else Qb(this);Xw(this)}),this.view&&Xw(this),this.#s(this.settings.theme.fontFamily),this.on("update-settings",t=>{this.#s(t.theme.fontFamily)}),this.generateUi()}initDrawing(){!this.loader.initialLoading&&this.view.gfxLayers?.scene&&cb(this.view.gfxLayers.scene),Zb({floorPlan:this}),tw(this),this.initDrawingEvents()}initDrawingEvents(){this.spaceGraph&&(this.spaceGraph.on("node-id-change",xw,this),this.spaceGraph.on("node-property-change",bw,this),this.spaceGraph.on("node-custom-attributes-change",Ow,this),this.spaceGraph.on("vertex-create",ww,this),this.spaceGraph.on("vertex-delete",_w,this),this.spaceGraph.on("vertex-set-position",Pw,this),this.spaceGraph.on("edge-create",Ew,this),this.spaceGraph.on("edge-delete",Tw,this),this.spaceGraph.on("edge-set-vertices",Aw,this),this.spaceGraph.on("space-create",Iw,this),this.spaceGraph.on("space-delete",Sw,this),this.spaceGraph.on("space-split",Cw,this),this.spaceGraph.on("space-attributes-change",Mw,this),this.spaceGraph.on("element-create",Nw,this),this.spaceGraph.on("element-delete",Lw,this),this.spaceGraph.on("element-transform-change",Rw,this),this.spaceGraph.on("element-parameters-change",Bw,this),this.spaceGraph.on("element-edges-change",kw,this),this.spaceGraph.on("geometry-profile-update",Dw,this),this.spaceGraph.on("geometry-update",Uw,this),this.spaceGraph.on("annotation-transform-change",Fw,this),this.spaceGraph.on("annotation-parameters-change",Fw,this),this.spaceGraph.on("floor-transform-change",Gw,this))}freeDrawingEvents(){this.spaceGraph&&(this.spaceGraph.off("node-id-change",xw),this.spaceGraph.off("node-property-change",bw),this.spaceGraph.off("vertex-create",ww),this.spaceGraph.off("vertex-delete",_w),this.spaceGraph.off("vertex-set-position",Pw),this.spaceGraph.off("edge-create",Ew),this.spaceGraph.off("edge-delete",Tw),this.spaceGraph.off("edge-set-vertices",Aw),this.spaceGraph.off("space-create",Iw),this.spaceGraph.off("space-delete",Sw),this.spaceGraph.off("space-split",Cw),this.spaceGraph.off("space-attributes-change",Mw),this.spaceGraph.off("element-create",Nw),this.spaceGraph.off("element-delete",Lw),this.spaceGraph.off("element-transform-change",Rw),this.spaceGraph.off("element-parameters-change",Bw),this.spaceGraph.off("geometry-profile-update",Dw),this.spaceGraph.off("geometry-update",Uw),this.spaceGraph.off("annotation-transform-change",Fw),this.spaceGraph.off("annotation-parameters-change",Fw),this.spaceGraph.off("floor-transform-change",Gw))}generateUi(){this.settings.ui.coordinates?this.addHelper("cursorCoordinates",{parentEl:this.fpeNode}):this.helper.cursorCoordinates&&this.removeHelper("cursorCoordinates"),this.settings.ui.scale?this.addHelper("scaleBar",{parentEl:this.fpeNode}):this.helper.scaleBar&&this.removeHelper("scaleBar")}getZoomExtentsBoundingBox(t,e,i,s,r,n,o){return function({layoutBoundingBox:t,rectLeft:e,rectTop:i,rectRight:s,rectBottom:r,viewportWidth:n,viewportHeight:o}){if([e,i,s,r].some(t=>t>0)&&n&&o){const a=s-e,l=r-i,h=function(t,e,i){const{min:s,max:r}=t;let n=s[0],o=s[1],a=r[0],l=r[1],h=a-n,u=l-o;const c=e/i;if(h/u>c){const t=u;u=h/c;const e=(t-u)/2;o+=e,l-=e}else{const t=h;h=u*c;const e=(t-h)/2;n+=e,a-=e}return{min:[n,o],max:[a,l]}}(t,a,l);let{min:u,max:c}=h,d=u[0],p=u[1],f=c[0]-d,m=c[1]-p;return f*=n/a,m*=o/l,d-=e/n*f,p-=i/o*m,{min:[d,p],max:[d+f,p+m]}}return t}({layoutBoundingBox:t,rectLeft:e,rectTop:i,rectRight:s,rectBottom:r,viewportWidth:n,viewportHeight:o})}zoomExtents(t=1,e=!1,i=null){return function({margin:t=0,animate:e,floorPlan:i,boundingBox:s}){return i.view.gfxLayers.scene?Nb(s?{bb:s,animate:e,view:i.view}:{bb:i.getBoundingBox(t),animate:e,view:i.view}):Promise.resolve(!1)}({margin:t,animate:e,floorPlan:this,boundingBox:i})}zoomToElement(t,e=1,i){let s;if("string"==typeof t){const e=t;s=this.layout.elementsById[e]||this.layout.spacesById[e]||this.layout.spatialGraph.edgesById[e]||null}else s=t;if(!s)return Promise.resolve(!0);const{min:[r,n,o],max:[a,l,h]}=s.getAxisAlignedBoundingBox();return Nb({bb:{min:[r-e,o-e],max:[a+e,h+e]},animate:i,view:this.view})}setZoom(t,e=!0){return Nb({bb:t,animate:e,view:this.view})}zoomByFactor(t,e=!0){if(!Number.isFinite(t)||t<=0)return Promise.reject("factor is not a positive number");let{min:i,max:s}=this.view.viewbox,r=i[0],n=i[1],o=s[0]-r,a=s[1]-n;const l=o/t,h=a/t;r-=(l-o)/2,n-=(h-a)/2;const u=r+l,c=n+h;return this.setZoom({min:[r,n],max:[u,c]},e)}addInfoWindow(t={}){return new Lx({...t,floorPlan:this})}addHtmlMarker(t={}){return new Rx({...t,floorPlan:this})}addMarker({position:t=[0,0],color:e="#669cff",size:i=40}={}){return new ub({position:t,color:e,size:i,floorPlan:this})}getPlanPosition(t){if(!this.view._viewport||this.view._viewport.destroyed)throw Error("No viewport present");const e=this.view._viewport.toWorld(t[0],t[1]);return[e.x/Ex,e.y/Ex]}getScreenPosition(t){if(!this.view._viewport||this.view._viewport.destroyed)throw Error("No viewport present");const e=this.view._viewport.toScreen(t[0]*Ex,t[1]*Ex);return[e.x,e.y]}addLayer({id:t,baseLayer:e}={}){if(!this.view?.layers)return;if(t||(t=O()),this.view.layers.has(t)){const e=this.view.layers.get(t);if(e?.container)return e}const i=new hw(this,e,t);return this.view.layers.set(t,i),i}getLayer(t){return this.view.layers.get(t)}addHelper(t,e={}){let i=e?.helperId;return i||(i="string"==typeof t?t:O()),this.helper[i]&&this.removeHelper(i),"string"==typeof t?this.availableHelpers[t]?this.helper[i]=new this.availableHelpers[t]({floorPlan:this,helperId:i,...e}):Nl.warn(`No helper registered for: ${t}`):this.helper[i]=new t({floorPlan:this,helperId:i,...e}),this.helper[i]}removeHelper(t){this.helper[t]?.destroy?.(),delete this.helper[t]}async exportImage({format:t="png",fileName:e,quality:i=90,output:s="base64",maxWidth:r,download:n=!1}={}){let o={format:t,quality:i};n&&(o.format="png");const a=document.querySelector("#"+this.fpeId+" canvas"),l=await function(t,{format:e="png",quality:i=.95}){return new Promise(s=>{let r;r="jpg"===e?t.toDataURL("image/jpeg",i):t.toDataURL(),s(r)})}(a,o).catch(t=>t);if(!n)return l;uw(l,{format:t,fileName:e,quality:i})}#s(t){if(t!==this.#t){this.#t=t;try{this.fpeNode.style.setProperty("--fpe-font-family",t)}catch(e){console.warn("Failed to set font-family",e)}}}destroy(){this.#e?.(),this.view.destroy(),this.loader.reset(),this.freeDrawingEvents(),this.layout=null,this.fpeNode&&this.fpeNode.remove(),this.fpeNode=null}}export{Hw as FloorPlanEngine,Ol as setApiUrls};
|