From b23c9d77563698693ab8290c2470f5ac8038acba Mon Sep 17 00:00:00 2001 From: z3dev Date: Fri, 3 Jan 2025 10:32:22 +0900 Subject: [PATCH 1/2] build(all): changed to publish prepatch releases --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 3c04f956b..743056a3f 100644 --- a/package.json +++ b/package.json @@ -14,8 +14,8 @@ "graph": "lerna list --graph", "list": "lerna ls", "preversion": "pnpm run test && pnpm run test:tsd && pnpm run docs", - "publish": "lerna publish premajor --include-merged-tags --no-private --no-push --conventional-prerelease --dist-tag alpha --pre-dist-tag alpha", - "publish-dryrun": "lerna version premajor --include-merged-tags --no-push --conventional-prerelease" + "publish": "lerna publish prepatch --include-merged-tags --no-private --no-push --conventional-prerelease --dist-tag alpha --pre-dist-tag alpha", + "publish-dryrun": "lerna version prepatch --include-merged-tags --no-private --no-push --conventional-prerelease" }, "contributors": [ { From 0660b5c1f1a5faf54d4cfae1cb85bb94182a8d32 Mon Sep 17 00:00:00 2001 From: z3dev Date: Fri, 3 Jan 2025 10:42:19 +0900 Subject: [PATCH 2/2] chore(release): publish - @jscad/cli@3.0.1-alpha.0 - @jscad/core@3.0.1-alpha.0 - @jscad/3mf-deserializer@3.0.1-alpha.0 - @jscad/3mf-serializer@3.0.1-alpha.0 - @jscad/dxf-deserializer@3.0.1-alpha.0 - @jscad/dxf-serializer@3.0.1-alpha.0 - @jscad/io@3.0.1-alpha.0 - @jscad/io-utils@3.0.1-alpha.0 - @jscad/json-deserializer@3.0.1-alpha.0 - @jscad/json-serializer@3.0.1-alpha.0 - @jscad/obj-deserializer@3.0.1-alpha.0 - @jscad/obj-serializer@3.0.1-alpha.0 - @jscad/stl-deserializer@3.0.1-alpha.0 - @jscad/stl-serializer@3.0.1-alpha.0 - @jscad/svg-deserializer@3.0.1-alpha.0 - @jscad/svg-serializer@3.0.1-alpha.0 - @jscad/x3d-deserializer@3.0.1-alpha.0 - @jscad/x3d-serializer@3.0.1-alpha.0 - @jscad/modeling@3.0.1-alpha.0 - @jscad/array-utils@3.0.1-alpha.0 - @jscad/regl-renderer@3.0.1-alpha.0 --- packages/cli/CHANGELOG.md | 13 ++ packages/cli/package.json | 12 +- packages/core/CHANGELOG.md | 7 + packages/core/package.json | 10 +- packages/io/3mf-deserializer/CHANGELOG.md | 8 ++ .../dist/jscad-3mf-deserializer.es.js | 8 +- .../dist/jscad-3mf-deserializer.min.js | 8 +- packages/io/3mf-deserializer/package.json | 6 +- packages/io/3mf-serializer/CHANGELOG.md | 10 ++ .../dist/jscad-3mf-serializer.es.js | 4 +- .../dist/jscad-3mf-serializer.min.js | 4 +- packages/io/3mf-serializer/package.json | 8 +- packages/io/dxf-deserializer/CHANGELOG.md | 12 ++ .../dist/jscad-dxf-deserializer.es.js | 4 +- .../dist/jscad-dxf-deserializer.min.js | 4 +- packages/io/dxf-deserializer/package.json | 6 +- packages/io/dxf-serializer/CHANGELOG.md | 11 ++ .../dist/jscad-dxf-serializer.es.js | 10 +- .../dist/jscad-dxf-serializer.min.js | 10 +- packages/io/dxf-serializer/package.json | 6 +- packages/io/io-utils/CHANGELOG.md | 6 + packages/io/io-utils/package.json | 4 +- packages/io/io/CHANGELOG.md | 13 ++ packages/io/io/package.json | 36 ++--- packages/io/json-deserializer/CHANGELOG.md | 11 ++ .../dist/jscad-json-deserializer.es.js | 6 +- .../dist/jscad-json-deserializer.min.js | 6 +- packages/io/json-deserializer/package.json | 8 +- packages/io/json-serializer/CHANGELOG.md | 10 ++ .../dist/jscad-json-serializer.es.js | 4 +- .../dist/jscad-json-serializer.min.js | 4 +- packages/io/json-serializer/package.json | 6 +- packages/io/obj-deserializer/CHANGELOG.md | 11 ++ .../dist/jscad-obj-deserializer.es.js | 8 +- .../dist/jscad-obj-deserializer.min.js | 9 +- packages/io/obj-deserializer/package.json | 6 +- packages/io/obj-serializer/CHANGELOG.md | 11 ++ .../dist/jscad-obj-serializer.es.js | 6 +- .../dist/jscad-obj-serializer.min.js | 6 +- packages/io/obj-serializer/package.json | 6 +- packages/io/stl-deserializer/CHANGELOG.md | 10 ++ .../dist/jscad-stl-deserializer.es.js | 6 +- .../dist/jscad-stl-deserializer.min.js | 6 +- packages/io/stl-deserializer/package.json | 6 +- packages/io/stl-serializer/CHANGELOG.md | 10 ++ .../dist/jscad-stl-serializer.es.js | 6 +- .../dist/jscad-stl-serializer.min.js | 6 +- packages/io/stl-serializer/package.json | 6 +- packages/io/svg-deserializer/CHANGELOG.md | 11 ++ .../dist/jscad-svg-deserializer.es.js | 6 +- .../dist/jscad-svg-deserializer.min.js | 6 +- packages/io/svg-deserializer/package.json | 8 +- packages/io/svg-serializer/CHANGELOG.md | 10 ++ .../dist/jscad-svg-serializer.es.js | 6 +- .../dist/jscad-svg-serializer.min.js | 6 +- packages/io/svg-serializer/package.json | 6 +- packages/io/x3d-deserializer/CHANGELOG.md | 14 ++ .../dist/jscad-x3d-deserializer.es.js | 10 +- .../dist/jscad-x3d-deserializer.min.js | 11 +- packages/io/x3d-deserializer/package.json | 8 +- packages/io/x3d-serializer/CHANGELOG.md | 10 ++ .../dist/jscad-x3d-serializer.es.js | 6 +- .../dist/jscad-x3d-serializer.min.js | 6 +- packages/io/x3d-serializer/package.json | 8 +- packages/modeling/CHANGELOG.md | 35 +++++ packages/modeling/dist/jscad-modeling.es.js | 4 +- packages/modeling/dist/jscad-modeling.min.js | 4 +- packages/modeling/package.json | 2 +- packages/utils/array-utils/CHANGELOG.md | 7 + .../array-utils/dist/jscad-array-utils.es.js | 2 +- .../array-utils/dist/jscad-array-utils.min.js | 2 +- packages/utils/array-utils/package.json | 2 +- packages/utils/regl-renderer/CHANGELOG.md | 10 ++ .../dist/jscad-regl-renderer.es.js | 4 +- .../dist/jscad-regl-renderer.min.js | 4 +- packages/utils/regl-renderer/package.json | 6 +- pnpm-lock.yaml | 124 +++++++++--------- 77 files changed, 485 insertions(+), 247 deletions(-) diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 601d2ae0a..e231a9030 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -3,6 +3,19 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/cli@2.2.24...@jscad/cli@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **cli:** rework logic for generating blobs, both singular and multiple as parts ([f88669b](https://github.com/jscad/OpenJSCAD.org/commit/f88669b286d9564165f5c33944703fce730dfc1f)) + +### Features + +* **3mf-deserializer:** initial version of 3MF deserializer and tests ([b22a27f](https://github.com/jscad/OpenJSCAD.org/commit/b22a27fa14c4f42b9160553cdd7b3c126ac72459)) +* **cli:** reworked logic to use new io package exports and functions ([#1199](https://github.com/jscad/OpenJSCAD.org/issues/1199)) ([71a3d27](https://github.com/jscad/OpenJSCAD.org/commit/71a3d27a4cf416b1a9fea57a1fe40f5cfdaa905c)) +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) +* **regl-renderer:** added rollup configuration to create ES6 bundle, adjusted imports and exports ([#1259](https://github.com/jscad/OpenJSCAD.org/issues/1259)) ([47a66bc](https://github.com/jscad/OpenJSCAD.org/commit/47a66bc07a137a748ce8571ea5d043ebaab9418d)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/cli@2.2.24...@jscad/cli@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/cli/package.json b/packages/cli/package.json index c9673443d..177b9e917 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/cli", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "Command Line Interface (CLI) for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -36,11 +36,11 @@ ], "license": "MIT", "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/core": "workspace:3.0.0-alpha.0", - "@jscad/io": "workspace:3.0.0-alpha.0", - "@jscad/io-utils": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0", + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/core": "workspace:3.0.1-alpha.0", + "@jscad/io": "workspace:3.0.1-alpha.0", + "@jscad/io-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", "jszip": "^3.10.1" }, "devDependencies": { diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index ef2e0c223..a2235bd3d 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -3,6 +3,13 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/core@2.6.4...@jscad/core@3.0.1-alpha.0) (2025-01-03) + +### Features + +* **cli:** reworked logic to use new io package exports and functions ([#1199](https://github.com/jscad/OpenJSCAD.org/issues/1199)) ([71a3d27](https://github.com/jscad/OpenJSCAD.org/commit/71a3d27a4cf416b1a9fea57a1fe40f5cfdaa905c)) +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/core@2.6.4...@jscad/core@3.0.0-alpha.0) (2023-10-09) ### Features diff --git a/packages/core/package.json b/packages/core/package.json index 39ede29b2..cd47c6824 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/core", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "Core functionality for JSCAD Applications", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -36,10 +36,10 @@ ], "license": "MIT", "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/io": "workspace:3.0.0-alpha.0", - "@jscad/io-utils": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0", + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/io": "workspace:3.0.1-alpha.0", + "@jscad/io-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", "json5": "2.2.3", "strip-bom": "4.0.0" }, diff --git a/packages/io/3mf-deserializer/CHANGELOG.md b/packages/io/3mf-deserializer/CHANGELOG.md index 0264312b1..ca403e022 100644 --- a/packages/io/3mf-deserializer/CHANGELOG.md +++ b/packages/io/3mf-deserializer/CHANGELOG.md @@ -3,6 +3,14 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## 3.0.1-alpha.0 (2025-01-03) + +### Features + +* **3mf-deserializer:** initial version of 3MF deserializer and tests ([b22a27f](https://github.com/jscad/OpenJSCAD.org/commit/b22a27fa14c4f42b9160553cdd7b3c126ac72459)) +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) +* **regl-renderer:** added rollup configuration to create ES6 bundle, adjusted imports and exports ([#1259](https://github.com/jscad/OpenJSCAD.org/issues/1259)) ([47a66bc](https://github.com/jscad/OpenJSCAD.org/commit/47a66bc07a137a748ce8571ea5d043ebaab9418d)) + # 3.0.0-alpha.0 (2023-10-09) ### Features diff --git a/packages/io/3mf-deserializer/dist/jscad-3mf-deserializer.es.js b/packages/io/3mf-deserializer/dist/jscad-3mf-deserializer.es.js index 2630ef887..b93896979 100644 --- a/packages/io/3mf-deserializer/dist/jscad-3mf-deserializer.es.js +++ b/packages/io/3mf-deserializer/dist/jscad-3mf-deserializer.es.js @@ -1,17 +1,17 @@ /** * 3MF Deserializer for JSCAD * @module @jscad/3mf-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ var u8=Uint8Array,u16=Uint16Array,u32=Uint32Array,fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb=function(eb,start){for(var b=new u16(31),i=0;i<31;++i)b[i]=start+=1<>>1|(21845&i)<<1;x=(61680&(x=(52428&x)>>>2|(13107&x)<<2))>>>4|(3855&x)<<4,rev[i]=((65280&x)>>>8|(255&x)<<8)>>>1}var hMap=function(cd,mb,r){for(var s=cd.length,i=0,l=new u16(mb);i>>rvb]=sv}else for(co=new u16(s),i=0;i>>15-cd[i]);return co},flt=new u8(288);for(i=0;i<144;++i)flt[i]=8;for(i=144;i<256;++i)flt[i]=9;for(i=256;i<280;++i)flt[i]=7;for(i=280;i<288;++i)flt[i]=8;var fdt=new u8(32);for(i=0;i<32;++i)fdt[i]=5;var flrm=hMap(flt,9,1),fdrm=hMap(fdt,5,1),max=function(a){for(var m=a[0],i=1;im&&(m=a[i]);return m},bits=function(d,p,m){var o=p/8|0;return(d[o]|d[o+1]<<8)>>(7&p)&m},bits16=function(d,p){var o=p/8|0;return(d[o]|d[o+1]<<8|d[o+2]<<16)>>(7&p)},slc=function(v,s,e){(null==s||s<0)&&(s=0),(null==e||e>v.length)&&(e=v.length);var n=new(2==v.BYTES_PER_ELEMENT?u16:4==v.BYTES_PER_ELEMENT?u32:u8)(e-s);return n.set(v.subarray(s,e)),n},ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);if(e.code=ind,Error.captureStackTrace&&Error.captureStackTrace(e,err),!nt)throw e;return e},inflt=function(dat,buf,st){var sl=dat.length;if(!sl||st&&st.f&&!st.l)return buf||new u8(0);var noBuf=!buf||st,noSt=!st||st.i;st||(st={}),buf||(buf=new u8(3*sl));var cbuf=function(l){var bl=buf.length;if(l>bl){var nbuf=new u8(Math.max(2*bl,l));nbuf.set(buf),buf=nbuf}},final=st.f||0,pos=st.p||0,bt=st.b||0,lm=st.l,dm=st.d,lbt=st.m,dbt=st.n,tbts=8*sl;do{if(!lm){final=bits(dat,pos,1);var type=bits(dat,pos+1,3);if(pos+=3,!type){var l=dat[(s=4+((pos+7)/8|0))-4]|dat[s-3]<<8,t=s+l;if(t>sl){noSt&&err(0);break}noBuf&&cbuf(bt+l),buf.set(dat.subarray(s,t),bt),st.b=bt+=l,st.p=pos=8*t,st.f=final;continue}if(1==type)lm=flrm,dm=fdrm,lbt=9,dbt=5;else if(2==type){var hLit=bits(dat,pos,31)+257,hcLen=bits(dat,pos+10,15)+4,tl=hLit+bits(dat,pos+5,31)+1;pos+=14;for(var ldt=new u8(tl),clt=new u8(19),i=0;i>>4)<16)ldt[i++]=s;else{var c=0,n=0;for(16==s?(n=3+bits(dat,pos,3),pos+=2,c=ldt[i-1]):17==s?(n=3+bits(dat,pos,7),pos+=3):18==s&&(n=11+bits(dat,pos,127),pos+=7);n--;)ldt[i++]=c}}var lt=ldt.subarray(0,hLit),dt=ldt.subarray(hLit);lbt=max(lt),dbt=max(dt),lm=hMap(lt,lbt,1),dm=hMap(dt,dbt,1)}else err(1);if(pos>tbts){noSt&&err(0);break}}noBuf&&cbuf(bt+131072);for(var lms=(1<>>4;if((pos+=15&c)>tbts){noSt&&err(0);break}if(c||err(2),sym<256)buf[bt++]=sym;else{if(256==sym){lpos=pos,lm=null;break}var add=sym-254;if(sym>264){var b=fleb[i=sym-257];add=bits(dat,pos,(1<>>4;d||err(3),pos+=15&d;dt=fd[dsym];if(dsym>3){b=fdeb[dsym];dt+=bits16(dat,pos)&(1<tbts){noSt&&err(0);break}noBuf&&cbuf(bt+131072);for(var end=bt+add;bt>>0},b8=function(d,b){return b4(d,b)+4294967296*b4(d,b+4)};function inflateSync(data,out){return inflt(data,out)}var td="undefined"!=typeof TextDecoder&&new TextDecoder;try{td.decode(et,{stream:!0}),1}catch(e){}function strFromU8(dat,latin1){if(latin1){for(var r="",i=0;i127)+(c>223)+(c>239);if(i+eb>d.length)return[r,slc(d,i-1)];eb?3==eb?(c=((15&c)<<18|(63&d[i++])<<12|(63&d[i++])<<6|63&d[i++])-65536,r+=String.fromCharCode(55296|c>>10,56320|1023&c)):r+=1&eb?String.fromCharCode((31&c)<<6|63&d[i++]):String.fromCharCode((15&c)<<12|(63&d[i++])<<6|63&d[i++]):r+=String.fromCharCode(c)}}(dat),out=_a[0];return _a[1].length&&err(8),out}var slzh=function(d,b){return b+30+b2(d,b+26)+b2(d,b+28)},zh=function(d,b,z){var fnl=b2(d,b+28),fn=strFromU8(d.subarray(b+46,b+46+fnl),!(2048&b2(d,b+8))),es=b+46+fnl,bs=b4(d,b+20),_a=z&&4294967295==bs?z64e(d,es):[bs,b4(d,b+24),b4(d,b+42)],sc=_a[0],su=_a[1],off=_a[2];return[b2(d,b+10),sc,su,fn,es+b2(d,b+30)+b2(d,b+32),off]},z64e=function(d,b){for(;1!=b2(d,b);b+=4+b2(d,b+2));return[b8(d,b+12),b8(d,b+4),b8(d,b+20)]}; /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const hexToRgb=notation=>{if((notation=notation.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const r=parseInt(notation.substring(0,2),16)/255,g=parseInt(notation.substring(2,4),16)/255,b=parseInt(notation.substring(4,6),16)/255;return notation.length>=8?[r,g,b,parseInt(notation.substring(6,8),16)/255]:[r,g,b]},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n)));var saxes={},ed5$1={};!function(exports){ +const clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const hexToRgb=notation=>{if((notation=notation.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const r=parseInt(notation.substring(0,2),16)/255,g=parseInt(notation.substring(2,4),16)/255,b=parseInt(notation.substring(4,6),16)/255;return notation.length>=8?[r,g,b,parseInt(notation.substring(6,8),16)/255]:[r,g,b]},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),transform=(matrix,...objects)=>{const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?transform(matrix,...object):object));return 1===results.length?results[0]:results};var saxes={},ed5$1={};!function(exports){ /** * Character classes and associated utilities for the 5th edition of XML 1.0. * @@ -35,4 +35,4 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.CHAR="-퟿- * @license MIT * @copyright Louis-Dominique Dubeau */ -Object.defineProperty(exports,"__esModule",{value:!0}),exports.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",exports.NC_NAME_CHAR="-"+exports.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",exports.NC_NAME_START_CHAR_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]$","u"),exports.NC_NAME_CHAR_RE=new RegExp("^["+exports.NC_NAME_CHAR+"]$","u"),exports.NC_NAME_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]["+exports.NC_NAME_CHAR+"]*$","u"),exports.isNCNameStartChar=isNCNameStartChar,exports.isNCNameChar=function(c){return isNCNameStartChar(c)||45===c||46===c||c>=48&&c<=57||183===c||c>=768&&c<=879||c>=8255&&c<=8256}}(ed3),Object.defineProperty(saxes,"__esModule",{value:!0}),saxes.SaxesParser=saxes.EVENTS=void 0;var isS=ed5$1.isS,isChar10=ed5$1.isChar,isNameStartChar=ed5$1.isNameStartChar,isNameChar=ed5$1.isNameChar,S_LIST=ed5$1.S_LIST,NAME_RE=ed5$1.NAME_RE,isChar11=ed2$1.isChar,isNCNameStartChar=ed3.isNCNameStartChar,isNCNameChar=ed3.isNCNameChar,NC_NAME_RE=ed3.NC_NAME_RE;const XML_NAMESPACE="http://www.w3.org/XML/1998/namespace",XMLNS_NAMESPACE="http://www.w3.org/2000/xmlns/",rootNS={__proto__:null,xml:XML_NAMESPACE,xmlns:XMLNS_NAMESPACE},XML_ENTITIES={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},isQuote=c=>34===c||39===c,QUOTES=[34,39],DOCTYPE_TERMINATOR=[...QUOTES,91,62],DTD_TERMINATOR=[...QUOTES,60,93],XML_DECL_NAME_TERMINATOR=[61,63,...S_LIST],ATTRIB_VALUE_UNQUOTED_TERMINATOR=[...S_LIST,62,38,60];function nsPairCheck(parser,prefix,uri){switch(prefix){case"xml":uri!==XML_NAMESPACE&&parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);break;case"xmlns":uri!==XMLNS_NAMESPACE&&parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`)}switch(uri){case XMLNS_NAMESPACE:parser.fail(""===prefix?`the default namespace may not be set to ${uri}.`:`may not assign a prefix (even "xmlns") to the URI ${XMLNS_NAMESPACE}.`);break;case XML_NAMESPACE:switch(prefix){case"xml":break;case"":parser.fail(`the default namespace may not be set to ${uri}.`);break;default:parser.fail("may not assign the xml namespace to another prefix.")}}}const isNCName=name=>NC_NAME_RE.test(name),isName=name=>NAME_RE.test(name);saxes.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];const EVENT_NAME_TO_HANDLER_NAME={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};saxes.SaxesParser=class{constructor(opt){this.opt=null!=opt?opt:{},this.fragmentOpt=!!this.opt.fragment;const xmlnsOpt=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=!1!==this.opt.position,this.fileName=this.opt.fileName,xmlnsOpt){this.nameStartCheck=isNCNameStartChar,this.nameCheck=isNCNameChar,this.isName=isNCName,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},rootNS);const additional=this.opt.additionalNamespaces;null!=additional&&(!function(parser,mapping){for(const local of Object.keys(mapping))nsPairCheck(parser,local,mapping[local])}(this,additional),Object.assign(this.ns,additional))}else this.nameStartCheck=isNameStartChar,this.nameCheck=isNameChar,this.isName=isName,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var _a;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=0,this.attribList=[];const{fragmentOpt:fragmentOpt}=this;this.state=fragmentOpt?13:0,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=fragmentOpt,this.xmlDeclPossible=!fragmentOpt,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:defaultXMLVersion}=this.opt;if(void 0===defaultXMLVersion){if(!0===this.opt.forceXMLVersion)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");defaultXMLVersion="1.0"}this.setXMLVersion(defaultXMLVersion),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(XML_ENTITIES),null===(_a=this.readyHandler)||void 0===_a||_a.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(name,handler){this[EVENT_NAME_TO_HANDLER_NAME[name]]=handler}off(name){this[EVENT_NAME_TO_HANDLER_NAME[name]]=void 0}makeError(message){var _a;let msg=null!==(_a=this.fileName)&&void 0!==_a?_a:"";return this.trackPosition&&(msg.length>0&&(msg+=":"),msg+=`${this.line}:${this.column}`),msg.length>0&&(msg+=": "),new Error(msg+message)}fail(message){const err=this.makeError(message),handler=this.errorHandler;if(void 0===handler)throw err;return handler(err),this}write(chunk){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let end=!1;null===chunk?(end=!0,chunk=""):"object"==typeof chunk&&(chunk=chunk.toString()),void 0!==this.carriedFromPrevious&&(chunk=`${this.carriedFromPrevious}${chunk}`,this.carriedFromPrevious=void 0);let limit=chunk.length;const lastCode=chunk.charCodeAt(limit-1);!end&&(13===lastCode||lastCode>=55296&&lastCode<=56319)&&(this.carriedFromPrevious=chunk[limit-1],limit--,chunk=chunk.slice(0,limit));const{stateTable:stateTable}=this;for(this.chunk=chunk,this.i=0;this.i=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>=32||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:return 10===chunk.charCodeAt(i+1)&&(this.i=i+2),this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCode11(){const{chunk:chunk,i:i}=this;if(this.prevI=i,this.i=i+1,i>=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>31&&code<127||code>159&&8232!==code||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:{const next=chunk.charCodeAt(i+1);10!==next&&133!==next||(this.i=i+2)}case 133:case 8232:return this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCodeNorm(){const c=this.getCode();return-2===c?10:c}unget(){this.i=this.prevI,this.column--}captureTo(chars){let{i:start}=this;const{chunk:chunk}=this;for(;;){const c=this.getCode(),isNLLike=-2===c,final=isNLLike?10:c;if(-1===final||chars.includes(final))return this.text+=chunk.slice(start,this.prevI),final;isNLLike&&(this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i)}}captureToChar(char){let{i:start}=this;const{chunk:chunk}=this;for(;;){let c=this.getCode();switch(c){case-2:this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i,c=10;break;case-1:return this.text+=chunk.slice(start),!1}if(c===char)return this.text+=chunk.slice(start,this.prevI),!0}}captureNameChars(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCode();if(-1===c)return this.name+=chunk.slice(start),-1;if(!isNameChar(c))return this.name+=chunk.slice(start,this.prevI),-2===c?10:c}}skipSpaces(){for(;;){const c=this.getCodeNorm();if(-1===c||!isS(c))return c}}setXMLVersion(version){this.currentXMLVersion=version,"1.0"===version?(this.isChar=isChar10,this.getCode=this.getCode10):(this.isChar=isChar11,this.getCode=this.getCode11)}sBegin(){65279===this.chunk.charCodeAt(0)&&(this.i++,this.column++),this.state=1}sBeginWhitespace(){const iBefore=this.i,c=this.skipSpaces();switch(this.prevI!==iBefore&&(this.xmlDeclPossible=!1),c){case 60:if(this.state=15,0!==this.text.length)throw new Error("no-empty text at start");break;case-1:break;default:this.unget(),this.state=13,this.xmlDeclPossible=!1}}sDoctype(){var _a;const c=this.captureTo(DOCTYPE_TERMINATOR);switch(c){case 62:null===(_a=this.doctypeHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13,this.doctype=!0;break;case-1:break;default:this.text+=String.fromCodePoint(c),91===c?this.state=4:isQuote(c)&&(this.state=3,this.q=c)}}sDoctypeQuote(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.q=null,this.state=2)}sDTD(){const c=this.captureTo(DTD_TERMINATOR);-1!==c&&(this.text+=String.fromCodePoint(c),93===c?this.state=2:60===c?this.state=6:isQuote(c)&&(this.state=5,this.q=c))}sDTDQuoted(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.state=4,this.q=null)}sDTDOpenWaka(){const c=this.getCodeNorm();switch(this.text+=String.fromCodePoint(c),c){case 33:this.state=7,this.openWakaBang="";break;case 63:this.state=11;break;default:this.state=4}}sDTDOpenWakaBang(){const char=String.fromCodePoint(this.getCodeNorm()),owb=this.openWakaBang+=char;this.text+=char,"-"!==owb&&(this.state="--"===owb?8:4,this.openWakaBang="")}sDTDComment(){this.captureToChar(45)&&(this.text+="-",this.state=9)}sDTDCommentEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),this.state=45===c?10:8}sDTDCommentEnded(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c?this.state=4:(this.fail("malformed comment."),this.state=8)}sDTDPI(){this.captureToChar(63)&&(this.text+="?",this.state=12)}sDTDPIEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c&&(this.state=4)}sText(){0!==this.tags.length?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:start}=this;const{chunk:chunk}=this;loop:for(;;)switch(this.getCode()){case-2:this.entity+=`${chunk.slice(start,this.prevI)}\n`,start=this.i;break;case 59:{const{entityReturnState:entityReturnState}=this,entity=this.entity+chunk.slice(start,this.prevI);let parsed;this.state=entityReturnState,""===entity?(this.fail("empty entity name."),parsed="&;"):(parsed=this.parseEntity(entity),this.entity=""),13===entityReturnState&&void 0===this.textHandler||(this.text+=parsed);break loop}case-1:this.entity+=chunk.slice(start);break loop}}sOpenWaka(){const c=this.getCode();if(isNameStartChar(c))this.state=34,this.unget(),this.xmlDeclPossible=!1;else switch(c){case 47:this.state=43,this.xmlDeclPossible=!1;break;case 33:this.state=16,this.openWakaBang="",this.xmlDeclPossible=!1;break;case 63:this.state=23;break;default:this.fail("disallowed character in tag name"),this.state=13,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=20,this.openWakaBang="";break;case"--":this.state=17,this.openWakaBang="";break;case"DOCTYPE":this.state=2,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(45)&&(this.state=18)}sCommentEnding(){var _a;const c=this.getCodeNorm();45===c?(this.state=19,null===(_a=this.commentHandler)||void 0===_a||_a.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(c)}`,this.state=17)}sCommentEnded(){const c=this.getCodeNorm();62!==c?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(c)}`,this.state=17):this.state=13}sCData(){this.captureToChar(93)&&(this.state=21)}sCDataEnding(){const c=this.getCodeNorm();93===c?this.state=22:(this.text+=`]${String.fromCodePoint(c)}`,this.state=20)}sCDataEnding2(){var _a;const c=this.getCodeNorm();switch(c){case 62:null===(_a=this.cdataHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13;break;case 93:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(c)}`,this.state=20}}sPIFirstChar(){const c=this.getCodeNorm();this.nameStartCheck(c)?(this.piTarget+=String.fromCodePoint(c),this.state=24):63===c||isS(c)?(this.fail("processing instruction without a target."),this.state=63===c?26:25):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c),this.state=24)}sPIRest(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCodeNorm();if(-1===c)return void(this.piTarget+=chunk.slice(start));if(!this.nameCheck(c)){this.piTarget+=chunk.slice(start,this.prevI);const isQuestion=63===c;isQuestion||isS(c)?"xml"===this.piTarget?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=isQuestion?33:27):this.state=isQuestion?26:25:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c));break}}}sPIBody(){if(0===this.text.length){const c=this.getCodeNorm();63===c?this.state=26:isS(c)||(this.text=String.fromCodePoint(c))}else this.captureToChar(63)&&(this.state=26)}sPIEnding(){var _a;const c=this.getCodeNorm();if(62===c){const{piTarget:piTarget}=this;"xml"===piTarget.toLowerCase()&&this.fail("the XML declaration must appear at the start of the document."),null===(_a=this.piHandler)||void 0===_a||_a.call(this,{target:piTarget,body:this.text}),this.piTarget=this.text="",this.state=13}else 63===c?this.text+="?":(this.text+=`?${String.fromCodePoint(c)}`,this.state=25);this.xmlDeclPossible=!1}sXMLDeclNameStart(){const c=this.skipSpaces();63!==c?-1!==c&&(this.state=28,this.name=String.fromCodePoint(c)):this.state=33}sXMLDeclName(){const c=this.captureTo(XML_DECL_NAME_TERMINATOR);if(63===c)return this.state=33,this.name+=this.text,this.text="",void this.fail("XML declaration is incomplete.");if(isS(c)||61===c){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=61===c?30:29}}sXMLDeclEq(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(61!==c&&this.fail("value required."),this.state=30)}sXMLDeclValueStart(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(isQuote(c)?this.q=c:(this.fail("value must be quoted."),this.q=32),this.state=31)}sXMLDeclValue(){const c=this.captureTo([this.q,63]);if(63===c)return this.state=33,this.text="",void this.fail("XML declaration is incomplete.");if(-1===c)return;const value=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];const version=value;this.xmlDecl.version=version,/^1\.[0-9]+$/.test(version)?this.opt.forceXMLVersion||this.setXMLVersion(version):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=value;break;case"standalone":"yes"!==value&&"no"!==value&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=value}this.name="",this.state=32}sXMLDeclSeparator(){const c=this.getCodeNorm();63!==c?(isS(c)||(this.fail("whitespace required."),this.unget()),this.state=27):this.state=33}sXMLDeclEnding(){var _a;62===this.getCodeNorm()?("xml"!==this.piTarget?this.fail("processing instructions are not allowed before root."):"version"!==this.name&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),null===(_a=this.xmldeclHandler)||void 0===_a||_a.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=13):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var _a;const c=this.captureNameChars();if(-1===c)return;const tag=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=tag.ns=Object.create(null)),null===(_a=this.openTagStartHandler)||void 0===_a||_a.call(this,tag),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),c){case 62:this.openTag();break;case 47:this.state=35;break;default:isS(c)||this.fail("disallowed character in tag name."),this.state=36}}sOpenTagSlash(){62===this.getCode()?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=36)}sAttrib(){const c=this.skipSpaces();-1!==c&&(isNameStartChar(c)?(this.unget(),this.state=37):62===c?this.openTag():47===c?this.state=35:this.fail("disallowed character in attribute name."))}sAttribName(){const c=this.captureNameChars();61===c?this.state=39:isS(c)?this.state=38:62===c?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):-1!==c&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){const c=this.skipSpaces();switch(c){case-1:return;case 61:this.state=39;break;default:this.fail("attribute without value."),this.text="",this.name="",62===c?this.openTag():isNameStartChar(c)?(this.unget(),this.state=37):(this.fail("disallowed character in attribute name."),this.state=36)}}sAttribValue(){const c=this.getCodeNorm();isQuote(c)?(this.q=c,this.state=40):isS(c)||(this.fail("unquoted attribute value."),this.state=42,this.unget())}sAttribValueQuoted(){const{q:q,chunk:chunk}=this;let{i:start}=this;for(;;)switch(this.getCode()){case q:return this.pushAttrib(this.name,this.text+chunk.slice(start,this.prevI)),this.name=this.text="",this.q=null,void(this.state=41);case 38:return this.text+=chunk.slice(start,this.prevI),this.state=14,void(this.entityReturnState=40);case 10:case-2:case 9:this.text+=`${chunk.slice(start,this.prevI)} `,start=this.i;break;case 60:return this.text+=chunk.slice(start,this.prevI),void this.fail("disallowed character.");case-1:return void(this.text+=chunk.slice(start))}}sAttribValueClosed(){const c=this.getCodeNorm();isS(c)?this.state=36:62===c?this.openTag():47===c?this.state=35:isNameStartChar(c)?(this.fail("no whitespace between attributes."),this.unget(),this.state=37):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){const c=this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);switch(c){case 38:this.state=14,this.entityReturnState=42;break;case 60:this.fail("disallowed character.");break;case-1:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",62===c?this.openTag():this.state=36}}sCloseTag(){const c=this.captureNameChars();62===c?this.closeTag():isS(c)?this.state=44:-1!==c&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case 62:this.closeTag();break;case-1:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:start,forbiddenState:forbiddenState}=this;const{chunk:chunk,textHandler:handler}=this;scanLoop:for(;;)switch(this.getCode()){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}forbiddenState=0;break scanLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),forbiddenState=0;break scanLoop;case 93:switch(forbiddenState){case 0:forbiddenState=1;break;case 1:forbiddenState=2;break;case 2:break;default:throw new Error("impossible state")}break;case 62:2===forbiddenState&&this.fail('the string "]]>" is disallowed in char data.'),forbiddenState=0;break;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i,forbiddenState=0;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break scanLoop;default:forbiddenState=0}this.forbiddenState=forbiddenState}handleTextOutsideRoot(){let{i:start}=this;const{chunk:chunk,textHandler:handler}=this;let nonSpace=!1;outRootLoop:for(;;){const code=this.getCode();switch(code){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}break outRootLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),nonSpace=!0;break outRootLoop;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break outRootLoop;default:isS(code)||(nonSpace=!0)}}nonSpace&&(this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(name,value){var _a;const{prefix:prefix,local:local}=this.qname(name),attr={name:name,prefix:prefix,local:local,value:value};if(this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr),"xmlns"===prefix){const trimmed=value.trim();"1.0"===this.currentXMLVersion&&""===trimmed&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[local]=trimmed,nsPairCheck(this,local,trimmed)}else if("xmlns"===name){const trimmed=value.trim();this.topNS[""]=trimmed,nsPairCheck(this,"",trimmed)}}pushAttribPlain(name,value){var _a;const attr={name:name,value:value};this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr)}end(){var _a,_b;this.sawRoot||this.fail("document must contain a root element.");const{tags:tags}=this;for(;tags.length>0;){const tag=tags.pop();this.fail(`unclosed tag: ${tag.name}`)}0!==this.state&&13!==this.state&&this.fail("unexpected end.");const{text:text}=this;return 0!==text.length&&(null===(_a=this.textHandler)||void 0===_a||_a.call(this,text),this.text=""),this._closed=!0,null===(_b=this.endHandler)||void 0===_b||_b.call(this),this._init(),this}resolve(prefix){var _a,_b;let uri=this.topNS[prefix];if(void 0!==uri)return uri;const{tags:tags}=this;for(let index=tags.length-1;index>=0;index--)if(uri=tags[index].ns[prefix],void 0!==uri)return uri;return uri=this.ns[prefix],void 0!==uri?uri:null===(_b=(_a=this.opt).resolvePrefix)||void 0===_b?void 0:_b.call(_a,prefix)}qname(name){const colon=name.indexOf(":");if(-1===colon)return{prefix:"",local:name};const local=name.slice(colon+1),prefix=name.slice(0,colon);return(""===prefix||""===local||local.includes(":"))&&this.fail(`malformed name: ${name}.`),{prefix:prefix,local:local}}processAttribsNS(){var _a;const{attribList:attribList}=this,tag=this.tag;{const{prefix:prefix,local:local}=this.qname(tag.name);tag.prefix=prefix,tag.local=local;const uri=tag.uri=null!==(_a=this.resolve(prefix))&&void 0!==_a?_a:"";""!==prefix&&("xmlns"===prefix&&this.fail('tags may not have "xmlns" as prefix.'),""===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),tag.uri=prefix))}if(0===attribList.length)return;const{attributes:attributes}=tag,seen=new Set;for(const attr of attribList){const{name:name,prefix:prefix,local:local}=attr;let uri,eqname;""===prefix?(uri="xmlns"===name?XMLNS_NAMESPACE:"",eqname=name):(uri=this.resolve(prefix),void 0===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),uri=prefix),eqname=`{${uri}}${local}`),seen.has(eqname)&&this.fail(`duplicate attribute: ${eqname}.`),seen.add(eqname),attr.uri=uri,attributes[name]=attr}this.attribList=[]}processAttribsPlain(){const{attribList:attribList}=this,attributes=this.tag.attributes;for(const{name:name,value:value}of attribList)void 0!==attributes[name]&&this.fail(`duplicate attribute: ${name}.`),attributes[name]=value;this.attribList=[]}openTag(){var _a;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!1,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),tags.push(tag),this.state=13,this.name=""}openSelfClosingTag(){var _a,_b,_c;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!0,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),null===(_b=this.closeTagHandler)||void 0===_b||_b.call(this,tag);null===(this.tag=null!==(_c=tags[tags.length-1])&&void 0!==_c?_c:null)&&(this.closedRoot=!0),this.state=13,this.name=""}closeTag(){const{tags:tags,name:name}=this;if(this.state=13,this.name="",""===name)return this.fail("weird empty close tag."),void(this.text+="");const handler=this.closeTagHandler;let l=tags.length;for(;l-- >0;){const tag=this.tag=tags.pop();if(this.topNS=tag.ns,null==handler||handler(tag),tag.name===name)break;this.fail("unexpected close tag.")}0===l?this.closedRoot=!0:l<0&&(this.fail(`unmatched closing tag: ${name}.`),this.text+=``)}parseEntity(entity){if("#"!==entity[0]){const defined=this.ENTITIES[entity];return void 0!==defined?defined:(this.fail(this.isName(entity)?"undefined entity.":"disallowed character in entity name."),`&${entity};`)}let num=NaN;return"x"===entity[1]&&/^#x[0-9a-f]+$/i.test(entity)?num=parseInt(entity.slice(2),16):/^#[0-9]+$/.test(entity)&&(num=parseInt(entity.slice(1),10)),this.isChar(num)?String.fromCodePoint(num):(this.fail("malformed character entity."),`&${entity};`)}};const convertTransform=text=>{const values=text.split(/ +/).map((s=>parseFloat(s)));return index$c.fromValues(values[0],values[1],values[2],0,values[3],values[4],values[5],0,values[6],values[7],values[8],0,values[9],values[10],values[11],1)},parseModel$1=attributes=>{const obj={type:"model",unit:"millimeter"};return attributes.unit&&(obj.unit=attributes.unit),obj},parseMesh=attributes=>{const obj={type:"mesh",vertices:[],triangles:[],properties:[]};return obj},parseVertex=attributes=>{const obj={type:"vertex"};return obj.vertex=[parseFloat(attributes.x),parseFloat(attributes.y),parseFloat(attributes.z)],obj},parseTriangle=attributes=>{const obj={type:"triangle"};return obj.indices=[parseFloat(attributes.v1),parseFloat(attributes.v2),parseFloat(attributes.v3)],attributes.p1&&(obj.p1=parseFloat(attributes.p1)),attributes.p2&&(obj.p2=parseFloat(attributes.p2)),attributes.p3&&(obj.p3=parseFloat(attributes.p3)),attributes.pid&&(obj.pid=attributes.pid),obj},parseItem=attributes=>{const obj={type:"item",transform:index$c.create()};return obj.objectid=attributes.objectid,attributes.transform&&(obj.transform=convertTransform(attributes.transform)),obj},parseObject=attributes=>{const obj={type:"object",otype:"model"};return obj.id=attributes.id,attributes.type&&(obj.otype=attributes.type),attributes.partnumber&&(obj.partnumber=attributes.partnumber),attributes.name&&(obj.name=attributes.name),attributes.pid&&(obj.pid=attributes.pid),attributes.pindex&&(obj.pindex=parseFloat(attributes.pindex)),obj},parseComponents=attributes=>({type:"components"}),parseComponent=attributes=>{const obj={type:"component",transform:index$c.create()};return obj.objectid=attributes.objectid,attributes.transform&&(obj.transform=convertTransform(attributes.transform)),obj},parseBaseMaterials=attributes=>{const obj={type:"basematerials",bases:[]};return obj.id=attributes.id,obj},parseBase=attributes=>{const obj={type:"base"};obj.name=attributes.name;let color=hexToRgb(attributes.displaycolor);return 3===color.length&&(color=[color[0],color[1],color[2],1]),obj.displaycolor=color,obj},parseColorGroup=attributes=>{const obj={type:"colorgroup",colors:[]};return obj.id=attributes.id,obj},parseColor=attributes=>{const obj={type:"color"};let color=hexToRgb(attributes.color);return 3===color.length&&(color=[color[0],color[1],color[2],1]),obj.color=color,obj},parse=src=>{let items=[],materials=[],colorgroups=[],objects=[];return((src,storage)=>{let{items:items,materials:materials,colorgroups:colorgroups,objects:objects}=storage,objLast=null;const parser=new saxes.SaxesParser;parser.on("error",(e=>{console.log(e)})),parser.on("opentag",(node=>{const objMap={MODEL:parseModel$1,ITEM:parseItem,OBJECT:parseObject,MESH:parseMesh,VERTEX:parseVertex,TRIANGLE:parseTriangle,COMPONENTS:parseComponents,COMPONENT:parseComponent,BASEMATERIALS:parseBaseMaterials,BASE:parseBase,MCOLORGROUP:parseColorGroup,MCOLOR:parseColor,undefined:()=>console.log(`WARNING: unsupported 3MF element: ${node.name}`)},elementName=node.name.toUpperCase().replace(":",""),obj=objMap[elementName]?objMap[elementName](node.attributes):null;let object=null,material=null,colorgroup=null;if(obj){switch(obj.type){case"model":break;case"item":items.push(obj);break;case"object":objects.push(obj);break;case"mesh":object=objects.at(-1),object.mesh=obj;break;case"vertex":object=objects.at(-1),object.mesh.vertices.push(obj.vertex);break;case"triangle":object=objects.at(-1),object.mesh.triangles.push(obj.indices),object.mesh.properties.push(((object,triangle)=>{const property={};return object.pid&&(property.pid=object.pid),triangle.pid&&(property.pid=triangle.pid),"p1"in triangle?property.pindex=triangle.p1:"pindex"in object&&(property.pindex=object.pindex),property})(object,obj));break;case"components":object=objects.at(-1),object.components=[];break;case"component":object=objects.at(-1),object.components.push(obj);break;case"basematerials":materials.push(obj);break;case"base":material=materials.at(-1),material.bases.push(obj);break;case"colorgroup":colorgroups.push(obj);break;case"color":colorgroup=colorgroups.at(-1),colorgroup.colors.push(obj);break;default:console.log("WARNING: unknown object type",obj.type)}objLast=obj}})),parser.on("closetag",(node=>{})),parser.on("text",(value=>{null!==value&&(value=value.trim()).length>0&&objLast&&(objLast.value=value,objLast=null)})),parser.on("end",(()=>{})),parser.write(src).close()})(src,{items:items,materials:materials,colorgroups:colorgroups,objects:objects}),{items:items,materials:materials,colorgroups:colorgroups,objects:objects}},parseModel=(options,source)=>{const{objects:objects,materials:materials,colorgroups:colorgroups,items:items}=parse(source);if(0===objects.length)throw new Error("3MF parsing failed, no valid 3MF objects retrieved");const buildItems=[];return items.forEach((item=>{const components=getComponents(item,objects);for(let i=0;i{const object=objects.find((obj=>obj.id===component.objectid)),components=[];if(object.mesh){const cmp={otype:object.otype,oid:object.id,transform:component.transform};object.name&&(cmp.oname=object.name),object.partnumber&&(cmp.opartnumber=object.partnumber),components.push(cmp)}return object.components&&object.components.forEach((c=>{getComponents(c,objects).forEach((s=>{index$c.multiply(s.transform,c.transform,s.transform),components.push(s)}))})),components},getDisplayColor$1=(property,materials,colorgroups)=>{if("pid"in property&&"pindex"in property){const material=materials.find((m=>property.pid===m.id));if(material){return material.bases[property.pindex].displaycolor}const colorgroup=colorgroups.find((g=>property.pid===g.id));if(colorgroup){return colorgroup.colors[property.pindex].color}}return null},translateObject=(options,object,materials,colorgroups)=>{let code=`\n// Object ID: ${object.id}\n// Object Type: ${object.otype}`;if(object.name&&(code+=`\n// Object Name: ${object.name}`),object.mesh){let displaycolors="const displaycolors = null",shapecolor=((object,materials,colorgroups)=>{const displayColor=getDisplayColor$1(object,materials,colorgroups);return displayColor?`shape.color = [${displayColor}]`:""})(object,materials,colorgroups);const properties=((options,properties,materials,colorgroups)=>{const colors=[];for(let i=0;i {\n ${((options,vertices)=>{let code="const vertices = [\n";for(let i=0;i{let code="const triangles = [\n";for(let i=0;i{const{version:version,addMetaData:addMetaData,filename:filename}=options,translatedModels=models.map((source=>((options,source)=>{const{includedType:includedType}=options;let{buildItems:buildItems,objects:objects,materials:materials,colorgroups:colorgroups}=parseModel(0,source);"all"!==includedType&&(buildItems=buildItems.filter((item=>item.mesh.type===includedType)));const translatedObjects=objects.map(((object,index)=>translateObject(0,object,materials,colorgroups))),translatedItems=buildItems.map(((item,index)=>((options,item)=>{let code=`\n// Build Item ${item.sequence}\n// Object:\n// ID: ${item.oid}\n// Type: ${item.otype}`;return item.name&&(code+=`\n// Name: ${item.oname}`),code+=`\nconst createBuildItem${item.sequence} = () => {\n const object = objects["${item.oid}"]\n ${((options,transform)=>`const transform = [${transform}]`)(0,item.transform)}\n return transform(transform, object)\n}\n\nbuilditems.push(createBuildItem${item.sequence}())\n`,code})(0,item)));return translatedObjects.join("")+translatedItems.join("")})(options,source))),metacode=addMetaData?`\n//\n// Produced by JSCAD IO Library : 3MF Deserializer\n// Version: ${version}\n// Date: ${new Date}\n// Source: ${filename}\n//\n`:"";let bodycode="";for(let i=0;i {\n return builditems\n}\n"},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),getDisplayColor=(property,materials,colorgroups)=>{if("pid"in property&&"pindex"in property){const material=materials.find((m=>property.pid===m.id));if(material){return material.bases[property.pindex].displaycolor}const colorgroup=colorgroups.find((g=>property.pid===g.id));if(colorgroup){return colorgroup.colors[property.pindex].color}}return null},instantiateObject=(options,object,materials,colorgroups)=>{if(object.mesh){const mesh=object.mesh,displaycolors=((options,properties,materials,colorgroups)=>{const displaycolors=[];for(let i=0;i{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({points:mesh.vertices,faces:mesh.triangles,colors:displaycolors});shape.id=object.id,shape.type=object.otype,object.name&&(shape.name=object.name);const displayColor=getDisplayColor(object,materials,colorgroups);return!displaycolors&&displayColor&&(shape.color=displayColor),shape}return index$6.create()},instantiateModel=(options,model)=>{const{includedType:includedType}=options;let{buildItems:buildItems,objects:objects,materials:materials,colorgroups:colorgroups}=parseModel(0,model);"all"!==includedType&&(buildItems=buildItems.filter((item=>item.mesh.type===includedType)));const instantiatedObjects={};objects.forEach((object=>{const instantiatedObject=instantiateObject(0,object,materials,colorgroups);instantiatedObjects[object.id]=instantiatedObject}));const instantiatedItems=buildItems.map((item=>{const object=instantiatedObjects[item.oid];return((matrix,...objects)=>{if(0===(objects=flatten$1(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results})(item.transform,object)}));return instantiatedItems},deserialize=(options,input)=>{const defaults={output:"script",version:"3.0.0-alpha.0",addMetaData:!0,includedItems:"build",includedType:"all"};options=Object.assign({},defaults,options);let models=[];try{const decompressed=function(data,opts){for(var files={},e=data.length-22;101010256!=b4(data,e);--e)(!e||data.length-e>65558)&&err(13);var c=b2(data,e+8);if(!c)return{};var o=b4(data,e+16),z=4294967295==o;z&&(e=b4(data,e-12),101075792!=b4(data,e)&&err(13),c=b4(data,e+32),o=b4(data,e+48));for(var fltr=opts&&opts.filter,i=0;i{if(key.endsWith("3dmodel.model")){const contents=strFromU8(decompressed[key]);models.push(contents)}}))}catch(e){models=[input]}return"script"===options.output?translateModels(options,models):((options,models)=>{const shapeLists=models.map((model=>instantiateModel(options,model)));return flatten(shapeLists)})(options,models)},mimeType="model/3mf";export{deserialize,mimeType}; +Object.defineProperty(exports,"__esModule",{value:!0}),exports.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",exports.NC_NAME_CHAR="-"+exports.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",exports.NC_NAME_START_CHAR_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]$","u"),exports.NC_NAME_CHAR_RE=new RegExp("^["+exports.NC_NAME_CHAR+"]$","u"),exports.NC_NAME_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]["+exports.NC_NAME_CHAR+"]*$","u"),exports.isNCNameStartChar=isNCNameStartChar,exports.isNCNameChar=function(c){return isNCNameStartChar(c)||45===c||46===c||c>=48&&c<=57||183===c||c>=768&&c<=879||c>=8255&&c<=8256}}(ed3),Object.defineProperty(saxes,"__esModule",{value:!0}),saxes.SaxesParser=saxes.EVENTS=void 0;var isS=ed5$1.isS,isChar10=ed5$1.isChar,isNameStartChar=ed5$1.isNameStartChar,isNameChar=ed5$1.isNameChar,S_LIST=ed5$1.S_LIST,NAME_RE=ed5$1.NAME_RE,isChar11=ed2$1.isChar,isNCNameStartChar=ed3.isNCNameStartChar,isNCNameChar=ed3.isNCNameChar,NC_NAME_RE=ed3.NC_NAME_RE;const XML_NAMESPACE="http://www.w3.org/XML/1998/namespace",XMLNS_NAMESPACE="http://www.w3.org/2000/xmlns/",rootNS={__proto__:null,xml:XML_NAMESPACE,xmlns:XMLNS_NAMESPACE},XML_ENTITIES={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},isQuote=c=>34===c||39===c,QUOTES=[34,39],DOCTYPE_TERMINATOR=[...QUOTES,91,62],DTD_TERMINATOR=[...QUOTES,60,93],XML_DECL_NAME_TERMINATOR=[61,63,...S_LIST],ATTRIB_VALUE_UNQUOTED_TERMINATOR=[...S_LIST,62,38,60];function nsPairCheck(parser,prefix,uri){switch(prefix){case"xml":uri!==XML_NAMESPACE&&parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);break;case"xmlns":uri!==XMLNS_NAMESPACE&&parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`)}switch(uri){case XMLNS_NAMESPACE:parser.fail(""===prefix?`the default namespace may not be set to ${uri}.`:`may not assign a prefix (even "xmlns") to the URI ${XMLNS_NAMESPACE}.`);break;case XML_NAMESPACE:switch(prefix){case"xml":break;case"":parser.fail(`the default namespace may not be set to ${uri}.`);break;default:parser.fail("may not assign the xml namespace to another prefix.")}}}const isNCName=name=>NC_NAME_RE.test(name),isName=name=>NAME_RE.test(name);saxes.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];const EVENT_NAME_TO_HANDLER_NAME={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};saxes.SaxesParser=class{constructor(opt){this.opt=null!=opt?opt:{},this.fragmentOpt=!!this.opt.fragment;const xmlnsOpt=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=!1!==this.opt.position,this.fileName=this.opt.fileName,xmlnsOpt){this.nameStartCheck=isNCNameStartChar,this.nameCheck=isNCNameChar,this.isName=isNCName,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},rootNS);const additional=this.opt.additionalNamespaces;null!=additional&&(!function(parser,mapping){for(const local of Object.keys(mapping))nsPairCheck(parser,local,mapping[local])}(this,additional),Object.assign(this.ns,additional))}else this.nameStartCheck=isNameStartChar,this.nameCheck=isNameChar,this.isName=isName,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var _a;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=0,this.attribList=[];const{fragmentOpt:fragmentOpt}=this;this.state=fragmentOpt?13:0,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=fragmentOpt,this.xmlDeclPossible=!fragmentOpt,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:defaultXMLVersion}=this.opt;if(void 0===defaultXMLVersion){if(!0===this.opt.forceXMLVersion)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");defaultXMLVersion="1.0"}this.setXMLVersion(defaultXMLVersion),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(XML_ENTITIES),null===(_a=this.readyHandler)||void 0===_a||_a.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(name,handler){this[EVENT_NAME_TO_HANDLER_NAME[name]]=handler}off(name){this[EVENT_NAME_TO_HANDLER_NAME[name]]=void 0}makeError(message){var _a;let msg=null!==(_a=this.fileName)&&void 0!==_a?_a:"";return this.trackPosition&&(msg.length>0&&(msg+=":"),msg+=`${this.line}:${this.column}`),msg.length>0&&(msg+=": "),new Error(msg+message)}fail(message){const err=this.makeError(message),handler=this.errorHandler;if(void 0===handler)throw err;return handler(err),this}write(chunk){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let end=!1;null===chunk?(end=!0,chunk=""):"object"==typeof chunk&&(chunk=chunk.toString()),void 0!==this.carriedFromPrevious&&(chunk=`${this.carriedFromPrevious}${chunk}`,this.carriedFromPrevious=void 0);let limit=chunk.length;const lastCode=chunk.charCodeAt(limit-1);!end&&(13===lastCode||lastCode>=55296&&lastCode<=56319)&&(this.carriedFromPrevious=chunk[limit-1],limit--,chunk=chunk.slice(0,limit));const{stateTable:stateTable}=this;for(this.chunk=chunk,this.i=0;this.i=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>=32||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:return 10===chunk.charCodeAt(i+1)&&(this.i=i+2),this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCode11(){const{chunk:chunk,i:i}=this;if(this.prevI=i,this.i=i+1,i>=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>31&&code<127||code>159&&8232!==code||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:{const next=chunk.charCodeAt(i+1);10!==next&&133!==next||(this.i=i+2)}case 133:case 8232:return this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCodeNorm(){const c=this.getCode();return-2===c?10:c}unget(){this.i=this.prevI,this.column--}captureTo(chars){let{i:start}=this;const{chunk:chunk}=this;for(;;){const c=this.getCode(),isNLLike=-2===c,final=isNLLike?10:c;if(-1===final||chars.includes(final))return this.text+=chunk.slice(start,this.prevI),final;isNLLike&&(this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i)}}captureToChar(char){let{i:start}=this;const{chunk:chunk}=this;for(;;){let c=this.getCode();switch(c){case-2:this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i,c=10;break;case-1:return this.text+=chunk.slice(start),!1}if(c===char)return this.text+=chunk.slice(start,this.prevI),!0}}captureNameChars(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCode();if(-1===c)return this.name+=chunk.slice(start),-1;if(!isNameChar(c))return this.name+=chunk.slice(start,this.prevI),-2===c?10:c}}skipSpaces(){for(;;){const c=this.getCodeNorm();if(-1===c||!isS(c))return c}}setXMLVersion(version){this.currentXMLVersion=version,"1.0"===version?(this.isChar=isChar10,this.getCode=this.getCode10):(this.isChar=isChar11,this.getCode=this.getCode11)}sBegin(){65279===this.chunk.charCodeAt(0)&&(this.i++,this.column++),this.state=1}sBeginWhitespace(){const iBefore=this.i,c=this.skipSpaces();switch(this.prevI!==iBefore&&(this.xmlDeclPossible=!1),c){case 60:if(this.state=15,0!==this.text.length)throw new Error("no-empty text at start");break;case-1:break;default:this.unget(),this.state=13,this.xmlDeclPossible=!1}}sDoctype(){var _a;const c=this.captureTo(DOCTYPE_TERMINATOR);switch(c){case 62:null===(_a=this.doctypeHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13,this.doctype=!0;break;case-1:break;default:this.text+=String.fromCodePoint(c),91===c?this.state=4:isQuote(c)&&(this.state=3,this.q=c)}}sDoctypeQuote(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.q=null,this.state=2)}sDTD(){const c=this.captureTo(DTD_TERMINATOR);-1!==c&&(this.text+=String.fromCodePoint(c),93===c?this.state=2:60===c?this.state=6:isQuote(c)&&(this.state=5,this.q=c))}sDTDQuoted(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.state=4,this.q=null)}sDTDOpenWaka(){const c=this.getCodeNorm();switch(this.text+=String.fromCodePoint(c),c){case 33:this.state=7,this.openWakaBang="";break;case 63:this.state=11;break;default:this.state=4}}sDTDOpenWakaBang(){const char=String.fromCodePoint(this.getCodeNorm()),owb=this.openWakaBang+=char;this.text+=char,"-"!==owb&&(this.state="--"===owb?8:4,this.openWakaBang="")}sDTDComment(){this.captureToChar(45)&&(this.text+="-",this.state=9)}sDTDCommentEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),this.state=45===c?10:8}sDTDCommentEnded(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c?this.state=4:(this.fail("malformed comment."),this.state=8)}sDTDPI(){this.captureToChar(63)&&(this.text+="?",this.state=12)}sDTDPIEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c&&(this.state=4)}sText(){0!==this.tags.length?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:start}=this;const{chunk:chunk}=this;loop:for(;;)switch(this.getCode()){case-2:this.entity+=`${chunk.slice(start,this.prevI)}\n`,start=this.i;break;case 59:{const{entityReturnState:entityReturnState}=this,entity=this.entity+chunk.slice(start,this.prevI);let parsed;this.state=entityReturnState,""===entity?(this.fail("empty entity name."),parsed="&;"):(parsed=this.parseEntity(entity),this.entity=""),13===entityReturnState&&void 0===this.textHandler||(this.text+=parsed);break loop}case-1:this.entity+=chunk.slice(start);break loop}}sOpenWaka(){const c=this.getCode();if(isNameStartChar(c))this.state=34,this.unget(),this.xmlDeclPossible=!1;else switch(c){case 47:this.state=43,this.xmlDeclPossible=!1;break;case 33:this.state=16,this.openWakaBang="",this.xmlDeclPossible=!1;break;case 63:this.state=23;break;default:this.fail("disallowed character in tag name"),this.state=13,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=20,this.openWakaBang="";break;case"--":this.state=17,this.openWakaBang="";break;case"DOCTYPE":this.state=2,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(45)&&(this.state=18)}sCommentEnding(){var _a;const c=this.getCodeNorm();45===c?(this.state=19,null===(_a=this.commentHandler)||void 0===_a||_a.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(c)}`,this.state=17)}sCommentEnded(){const c=this.getCodeNorm();62!==c?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(c)}`,this.state=17):this.state=13}sCData(){this.captureToChar(93)&&(this.state=21)}sCDataEnding(){const c=this.getCodeNorm();93===c?this.state=22:(this.text+=`]${String.fromCodePoint(c)}`,this.state=20)}sCDataEnding2(){var _a;const c=this.getCodeNorm();switch(c){case 62:null===(_a=this.cdataHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13;break;case 93:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(c)}`,this.state=20}}sPIFirstChar(){const c=this.getCodeNorm();this.nameStartCheck(c)?(this.piTarget+=String.fromCodePoint(c),this.state=24):63===c||isS(c)?(this.fail("processing instruction without a target."),this.state=63===c?26:25):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c),this.state=24)}sPIRest(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCodeNorm();if(-1===c)return void(this.piTarget+=chunk.slice(start));if(!this.nameCheck(c)){this.piTarget+=chunk.slice(start,this.prevI);const isQuestion=63===c;isQuestion||isS(c)?"xml"===this.piTarget?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=isQuestion?33:27):this.state=isQuestion?26:25:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c));break}}}sPIBody(){if(0===this.text.length){const c=this.getCodeNorm();63===c?this.state=26:isS(c)||(this.text=String.fromCodePoint(c))}else this.captureToChar(63)&&(this.state=26)}sPIEnding(){var _a;const c=this.getCodeNorm();if(62===c){const{piTarget:piTarget}=this;"xml"===piTarget.toLowerCase()&&this.fail("the XML declaration must appear at the start of the document."),null===(_a=this.piHandler)||void 0===_a||_a.call(this,{target:piTarget,body:this.text}),this.piTarget=this.text="",this.state=13}else 63===c?this.text+="?":(this.text+=`?${String.fromCodePoint(c)}`,this.state=25);this.xmlDeclPossible=!1}sXMLDeclNameStart(){const c=this.skipSpaces();63!==c?-1!==c&&(this.state=28,this.name=String.fromCodePoint(c)):this.state=33}sXMLDeclName(){const c=this.captureTo(XML_DECL_NAME_TERMINATOR);if(63===c)return this.state=33,this.name+=this.text,this.text="",void this.fail("XML declaration is incomplete.");if(isS(c)||61===c){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=61===c?30:29}}sXMLDeclEq(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(61!==c&&this.fail("value required."),this.state=30)}sXMLDeclValueStart(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(isQuote(c)?this.q=c:(this.fail("value must be quoted."),this.q=32),this.state=31)}sXMLDeclValue(){const c=this.captureTo([this.q,63]);if(63===c)return this.state=33,this.text="",void this.fail("XML declaration is incomplete.");if(-1===c)return;const value=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];const version=value;this.xmlDecl.version=version,/^1\.[0-9]+$/.test(version)?this.opt.forceXMLVersion||this.setXMLVersion(version):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=value;break;case"standalone":"yes"!==value&&"no"!==value&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=value}this.name="",this.state=32}sXMLDeclSeparator(){const c=this.getCodeNorm();63!==c?(isS(c)||(this.fail("whitespace required."),this.unget()),this.state=27):this.state=33}sXMLDeclEnding(){var _a;62===this.getCodeNorm()?("xml"!==this.piTarget?this.fail("processing instructions are not allowed before root."):"version"!==this.name&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),null===(_a=this.xmldeclHandler)||void 0===_a||_a.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=13):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var _a;const c=this.captureNameChars();if(-1===c)return;const tag=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=tag.ns=Object.create(null)),null===(_a=this.openTagStartHandler)||void 0===_a||_a.call(this,tag),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),c){case 62:this.openTag();break;case 47:this.state=35;break;default:isS(c)||this.fail("disallowed character in tag name."),this.state=36}}sOpenTagSlash(){62===this.getCode()?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=36)}sAttrib(){const c=this.skipSpaces();-1!==c&&(isNameStartChar(c)?(this.unget(),this.state=37):62===c?this.openTag():47===c?this.state=35:this.fail("disallowed character in attribute name."))}sAttribName(){const c=this.captureNameChars();61===c?this.state=39:isS(c)?this.state=38:62===c?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):-1!==c&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){const c=this.skipSpaces();switch(c){case-1:return;case 61:this.state=39;break;default:this.fail("attribute without value."),this.text="",this.name="",62===c?this.openTag():isNameStartChar(c)?(this.unget(),this.state=37):(this.fail("disallowed character in attribute name."),this.state=36)}}sAttribValue(){const c=this.getCodeNorm();isQuote(c)?(this.q=c,this.state=40):isS(c)||(this.fail("unquoted attribute value."),this.state=42,this.unget())}sAttribValueQuoted(){const{q:q,chunk:chunk}=this;let{i:start}=this;for(;;)switch(this.getCode()){case q:return this.pushAttrib(this.name,this.text+chunk.slice(start,this.prevI)),this.name=this.text="",this.q=null,void(this.state=41);case 38:return this.text+=chunk.slice(start,this.prevI),this.state=14,void(this.entityReturnState=40);case 10:case-2:case 9:this.text+=`${chunk.slice(start,this.prevI)} `,start=this.i;break;case 60:return this.text+=chunk.slice(start,this.prevI),void this.fail("disallowed character.");case-1:return void(this.text+=chunk.slice(start))}}sAttribValueClosed(){const c=this.getCodeNorm();isS(c)?this.state=36:62===c?this.openTag():47===c?this.state=35:isNameStartChar(c)?(this.fail("no whitespace between attributes."),this.unget(),this.state=37):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){const c=this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);switch(c){case 38:this.state=14,this.entityReturnState=42;break;case 60:this.fail("disallowed character.");break;case-1:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",62===c?this.openTag():this.state=36}}sCloseTag(){const c=this.captureNameChars();62===c?this.closeTag():isS(c)?this.state=44:-1!==c&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case 62:this.closeTag();break;case-1:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:start,forbiddenState:forbiddenState}=this;const{chunk:chunk,textHandler:handler}=this;scanLoop:for(;;)switch(this.getCode()){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}forbiddenState=0;break scanLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),forbiddenState=0;break scanLoop;case 93:switch(forbiddenState){case 0:forbiddenState=1;break;case 1:forbiddenState=2;break;case 2:break;default:throw new Error("impossible state")}break;case 62:2===forbiddenState&&this.fail('the string "]]>" is disallowed in char data.'),forbiddenState=0;break;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i,forbiddenState=0;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break scanLoop;default:forbiddenState=0}this.forbiddenState=forbiddenState}handleTextOutsideRoot(){let{i:start}=this;const{chunk:chunk,textHandler:handler}=this;let nonSpace=!1;outRootLoop:for(;;){const code=this.getCode();switch(code){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}break outRootLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),nonSpace=!0;break outRootLoop;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break outRootLoop;default:isS(code)||(nonSpace=!0)}}nonSpace&&(this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(name,value){var _a;const{prefix:prefix,local:local}=this.qname(name),attr={name:name,prefix:prefix,local:local,value:value};if(this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr),"xmlns"===prefix){const trimmed=value.trim();"1.0"===this.currentXMLVersion&&""===trimmed&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[local]=trimmed,nsPairCheck(this,local,trimmed)}else if("xmlns"===name){const trimmed=value.trim();this.topNS[""]=trimmed,nsPairCheck(this,"",trimmed)}}pushAttribPlain(name,value){var _a;const attr={name:name,value:value};this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr)}end(){var _a,_b;this.sawRoot||this.fail("document must contain a root element.");const{tags:tags}=this;for(;tags.length>0;){const tag=tags.pop();this.fail(`unclosed tag: ${tag.name}`)}0!==this.state&&13!==this.state&&this.fail("unexpected end.");const{text:text}=this;return 0!==text.length&&(null===(_a=this.textHandler)||void 0===_a||_a.call(this,text),this.text=""),this._closed=!0,null===(_b=this.endHandler)||void 0===_b||_b.call(this),this._init(),this}resolve(prefix){var _a,_b;let uri=this.topNS[prefix];if(void 0!==uri)return uri;const{tags:tags}=this;for(let index=tags.length-1;index>=0;index--)if(uri=tags[index].ns[prefix],void 0!==uri)return uri;return uri=this.ns[prefix],void 0!==uri?uri:null===(_b=(_a=this.opt).resolvePrefix)||void 0===_b?void 0:_b.call(_a,prefix)}qname(name){const colon=name.indexOf(":");if(-1===colon)return{prefix:"",local:name};const local=name.slice(colon+1),prefix=name.slice(0,colon);return(""===prefix||""===local||local.includes(":"))&&this.fail(`malformed name: ${name}.`),{prefix:prefix,local:local}}processAttribsNS(){var _a;const{attribList:attribList}=this,tag=this.tag;{const{prefix:prefix,local:local}=this.qname(tag.name);tag.prefix=prefix,tag.local=local;const uri=tag.uri=null!==(_a=this.resolve(prefix))&&void 0!==_a?_a:"";""!==prefix&&("xmlns"===prefix&&this.fail('tags may not have "xmlns" as prefix.'),""===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),tag.uri=prefix))}if(0===attribList.length)return;const{attributes:attributes}=tag,seen=new Set;for(const attr of attribList){const{name:name,prefix:prefix,local:local}=attr;let uri,eqname;""===prefix?(uri="xmlns"===name?XMLNS_NAMESPACE:"",eqname=name):(uri=this.resolve(prefix),void 0===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),uri=prefix),eqname=`{${uri}}${local}`),seen.has(eqname)&&this.fail(`duplicate attribute: ${eqname}.`),seen.add(eqname),attr.uri=uri,attributes[name]=attr}this.attribList=[]}processAttribsPlain(){const{attribList:attribList}=this,attributes=this.tag.attributes;for(const{name:name,value:value}of attribList)void 0!==attributes[name]&&this.fail(`duplicate attribute: ${name}.`),attributes[name]=value;this.attribList=[]}openTag(){var _a;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!1,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),tags.push(tag),this.state=13,this.name=""}openSelfClosingTag(){var _a,_b,_c;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!0,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),null===(_b=this.closeTagHandler)||void 0===_b||_b.call(this,tag);null===(this.tag=null!==(_c=tags[tags.length-1])&&void 0!==_c?_c:null)&&(this.closedRoot=!0),this.state=13,this.name=""}closeTag(){const{tags:tags,name:name}=this;if(this.state=13,this.name="",""===name)return this.fail("weird empty close tag."),void(this.text+="");const handler=this.closeTagHandler;let l=tags.length;for(;l-- >0;){const tag=this.tag=tags.pop();if(this.topNS=tag.ns,null==handler||handler(tag),tag.name===name)break;this.fail("unexpected close tag.")}0===l?this.closedRoot=!0:l<0&&(this.fail(`unmatched closing tag: ${name}.`),this.text+=``)}parseEntity(entity){if("#"!==entity[0]){const defined=this.ENTITIES[entity];return void 0!==defined?defined:(this.fail(this.isName(entity)?"undefined entity.":"disallowed character in entity name."),`&${entity};`)}let num=NaN;return"x"===entity[1]&&/^#x[0-9a-f]+$/i.test(entity)?num=parseInt(entity.slice(2),16):/^#[0-9]+$/.test(entity)&&(num=parseInt(entity.slice(1),10)),this.isChar(num)?String.fromCodePoint(num):(this.fail("malformed character entity."),`&${entity};`)}};const convertTransform=text=>{const values=text.split(/ +/).map((s=>parseFloat(s)));return index$c.fromValues(values[0],values[1],values[2],0,values[3],values[4],values[5],0,values[6],values[7],values[8],0,values[9],values[10],values[11],1)},parseModel$1=attributes=>{const obj={type:"model",unit:"millimeter"};return attributes.unit&&(obj.unit=attributes.unit),obj},parseMesh=attributes=>{const obj={type:"mesh",vertices:[],triangles:[],properties:[]};return obj},parseVertex=attributes=>{const obj={type:"vertex"};return obj.vertex=[parseFloat(attributes.x),parseFloat(attributes.y),parseFloat(attributes.z)],obj},parseTriangle=attributes=>{const obj={type:"triangle"};return obj.indices=[parseFloat(attributes.v1),parseFloat(attributes.v2),parseFloat(attributes.v3)],attributes.p1&&(obj.p1=parseFloat(attributes.p1)),attributes.p2&&(obj.p2=parseFloat(attributes.p2)),attributes.p3&&(obj.p3=parseFloat(attributes.p3)),attributes.pid&&(obj.pid=attributes.pid),obj},parseItem=attributes=>{const obj={type:"item",transform:index$c.create()};return obj.objectid=attributes.objectid,attributes.transform&&(obj.transform=convertTransform(attributes.transform)),obj},parseObject=attributes=>{const obj={type:"object",otype:"model"};return obj.id=attributes.id,attributes.type&&(obj.otype=attributes.type),attributes.partnumber&&(obj.partnumber=attributes.partnumber),attributes.name&&(obj.name=attributes.name),attributes.pid&&(obj.pid=attributes.pid),attributes.pindex&&(obj.pindex=parseFloat(attributes.pindex)),obj},parseComponents=attributes=>({type:"components"}),parseComponent=attributes=>{const obj={type:"component",transform:index$c.create()};return obj.objectid=attributes.objectid,attributes.transform&&(obj.transform=convertTransform(attributes.transform)),obj},parseBaseMaterials=attributes=>{const obj={type:"basematerials",bases:[]};return obj.id=attributes.id,obj},parseBase=attributes=>{const obj={type:"base"};obj.name=attributes.name;let color=hexToRgb(attributes.displaycolor);return 3===color.length&&(color=[color[0],color[1],color[2],1]),obj.displaycolor=color,obj},parseColorGroup=attributes=>{const obj={type:"colorgroup",colors:[]};return obj.id=attributes.id,obj},parseColor=attributes=>{const obj={type:"color"};let color=hexToRgb(attributes.color);return 3===color.length&&(color=[color[0],color[1],color[2],1]),obj.color=color,obj},parse=src=>{const items=[],materials=[],colorgroups=[],objects=[];return((src,storage)=>{const{items:items,materials:materials,colorgroups:colorgroups,objects:objects}=storage;let objLast=null;const parser=new saxes.SaxesParser;parser.on("error",(e=>{console.log(e)})),parser.on("opentag",(node=>{const objMap={MODEL:parseModel$1,ITEM:parseItem,OBJECT:parseObject,MESH:parseMesh,VERTEX:parseVertex,TRIANGLE:parseTriangle,COMPONENTS:parseComponents,COMPONENT:parseComponent,BASEMATERIALS:parseBaseMaterials,BASE:parseBase,MCOLORGROUP:parseColorGroup,MCOLOR:parseColor,undefined:()=>console.log(`WARNING: unsupported 3MF element: ${node.name}`)},elementName=node.name.toUpperCase().replace(":",""),obj=objMap[elementName]?objMap[elementName](node.attributes):null;let object=null,material=null,colorgroup=null;if(obj){switch(obj.type){case"model":break;case"item":items.push(obj);break;case"object":objects.push(obj);break;case"mesh":object=objects.at(-1),object.mesh=obj;break;case"vertex":object=objects.at(-1),object.mesh.vertices.push(obj.vertex);break;case"triangle":object=objects.at(-1),object.mesh.triangles.push(obj.indices),object.mesh.properties.push(((object,triangle)=>{const property={};return object.pid&&(property.pid=object.pid),triangle.pid&&(property.pid=triangle.pid),"p1"in triangle?property.pindex=triangle.p1:"pindex"in object&&(property.pindex=object.pindex),property})(object,obj));break;case"components":object=objects.at(-1),object.components=[];break;case"component":object=objects.at(-1),object.components.push(obj);break;case"basematerials":materials.push(obj);break;case"base":material=materials.at(-1),material.bases.push(obj);break;case"colorgroup":colorgroups.push(obj);break;case"color":colorgroup=colorgroups.at(-1),colorgroup.colors.push(obj);break;default:console.log("WARNING: unknown object type",obj.type)}objLast=obj}})),parser.on("closetag",(node=>{})),parser.on("text",(value=>{null!==value&&(value=value.trim()).length>0&&objLast&&(objLast.value=value,objLast=null)})),parser.on("end",(()=>{})),parser.write(src).close()})(src,{items:items,materials:materials,colorgroups:colorgroups,objects:objects}),{items:items,materials:materials,colorgroups:colorgroups,objects:objects}},parseModel=(options,source)=>{const{objects:objects,materials:materials,colorgroups:colorgroups,items:items}=parse(source);if(0===objects.length)throw new Error("3MF parsing failed, no valid 3MF objects retrieved");const buildItems=[];return items.forEach((item=>{const components=getComponents(item,objects);for(let i=0;i{const object=objects.find((obj=>obj.id===component.objectid)),components=[];if(object.mesh){const cmp={otype:object.otype,oid:object.id,transform:component.transform};object.name&&(cmp.oname=object.name),object.partnumber&&(cmp.opartnumber=object.partnumber),components.push(cmp)}return object.components&&object.components.forEach((c=>{getComponents(c,objects).forEach((s=>{index$c.multiply(s.transform,c.transform,s.transform),components.push(s)}))})),components},getDisplayColor$1=(property,materials,colorgroups)=>{if("pid"in property&&"pindex"in property){const material=materials.find((m=>property.pid===m.id));if(material){return material.bases[property.pindex].displaycolor}const colorgroup=colorgroups.find((g=>property.pid===g.id));if(colorgroup){return colorgroup.colors[property.pindex].color}}return null},translateObject=(options,object,materials,colorgroups)=>{let code=`\n// Object ID: ${object.id}\n// Object Type: ${object.otype}`;if(object.name&&(code+=`\n// Object Name: ${object.name}`),object.mesh){let displaycolors="const displaycolors = null",shapecolor=((object,materials,colorgroups)=>{const displayColor=getDisplayColor$1(object,materials,colorgroups);return displayColor?`shape.color = [${displayColor}]`:""})(object,materials,colorgroups);const properties=((options,properties,materials,colorgroups)=>{const colors=[];for(let i=0;i {\n ${((options,vertices)=>{let code="const vertices = [\n";for(let i=0;i{let code="const triangles = [\n";for(let i=0;i{const{version:version,addMetaData:addMetaData,filename:filename}=options,translatedModels=models.map((source=>((options,source)=>{const{includedType:includedType}=options;let{buildItems:buildItems,objects:objects,materials:materials,colorgroups:colorgroups}=parseModel(0,source);"all"!==includedType&&(buildItems=buildItems.filter((item=>item.mesh.type===includedType)));const translatedObjects=objects.map(((object,index)=>translateObject(0,object,materials,colorgroups))),translatedItems=buildItems.map(((item,index)=>((options,item)=>{let code=`\n// Build Item ${item.sequence}\n// Object:\n// ID: ${item.oid}\n// Type: ${item.otype}`;return item.name&&(code+=`\n// Name: ${item.oname}`),code+=`\nconst createBuildItem${item.sequence} = () => {\n const object = objects["${item.oid}"]\n ${((options,transform)=>`const transform = [${transform}]`)(0,item.transform)}\n return transform(transform, object)\n}\n\nbuilditems.push(createBuildItem${item.sequence}())\n`,code})(0,item)));return translatedObjects.join("")+translatedItems.join("")})(options,source))),metacode=addMetaData?`\n//\n// Produced by JSCAD IO Library : 3MF Deserializer\n// Version: ${version}\n// Date: ${new Date}\n// Source: ${filename}\n//\n`:"";let bodycode="";for(let i=0;i {\n return builditems\n}\n"},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),getDisplayColor=(property,materials,colorgroups)=>{if("pid"in property&&"pindex"in property){const material=materials.find((m=>property.pid===m.id));if(material){return material.bases[property.pindex].displaycolor}const colorgroup=colorgroups.find((g=>property.pid===g.id));if(colorgroup){return colorgroup.colors[property.pindex].color}}return null},instantiateObject=(options,object,materials,colorgroups)=>{if(object.mesh){const mesh=object.mesh,displaycolors=((options,properties,materials,colorgroups)=>{const displaycolors=[];for(let i=0;i{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({points:mesh.vertices,faces:mesh.triangles,colors:displaycolors});shape.id=object.id,shape.type=object.otype,object.name&&(shape.name=object.name);const displayColor=getDisplayColor(object,materials,colorgroups);return!displaycolors&&displayColor&&(shape.color=displayColor),shape}return index$6.create()},instantiateModels=(options,models)=>{const shapeLists=models.map((model=>((options,model)=>{const{includedType:includedType}=options;let{buildItems:buildItems,objects:objects,materials:materials,colorgroups:colorgroups}=parseModel(0,model);"all"!==includedType&&(buildItems=buildItems.filter((item=>item.mesh.type===includedType)));const instantiatedObjects={};return objects.forEach((object=>{const instantiatedObject=instantiateObject(0,object,materials,colorgroups);instantiatedObjects[object.id]=instantiatedObject})),buildItems.map((item=>{const object=instantiatedObjects[item.oid];return transform(item.transform,object)}))})(options,model)));return flatten(shapeLists)},deserialize=(options,input)=>{const defaults={output:"script",version:"3.0.1-alpha.0",addMetaData:!0,includedItems:"build",includedType:"all"};options=Object.assign({},defaults,options);let models=[];try{const decompressed=function(data,opts){for(var files={},e=data.length-22;101010256!=b4(data,e);--e)(!e||data.length-e>65558)&&err(13);var c=b2(data,e+8);if(!c)return{};var o=b4(data,e+16),z=4294967295==o;z&&(e=b4(data,e-12),101075792!=b4(data,e)&&err(13),c=b4(data,e+32),o=b4(data,e+48));for(var fltr=opts&&opts.filter,i=0;i{if(key.endsWith("3dmodel.model")){const contents=strFromU8(decompressed[key]);models.push(contents)}}))}catch(e){models=[input]}return"script"===options.output?translateModels(options,models):instantiateModels(options,models)},mimeType="model/3mf";export{deserialize,mimeType}; diff --git a/packages/io/3mf-deserializer/dist/jscad-3mf-deserializer.min.js b/packages/io/3mf-deserializer/dist/jscad-3mf-deserializer.min.js index 0846a6d24..3cad7eee9 100644 --- a/packages/io/3mf-deserializer/dist/jscad-3mf-deserializer.min.js +++ b/packages/io/3mf-deserializer/dist/jscad-3mf-deserializer.min.js @@ -1,17 +1,17 @@ /** * 3MF Deserializer for JSCAD * @module @jscad/3mf-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ var global,factory;global=this,factory=function(exports){var u8=Uint8Array,u16=Uint16Array,u32=Uint32Array,fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb=function(eb,start){for(var b=new u16(31),i=0;i<31;++i)b[i]=start+=1<>>1|(21845&i)<<1;x=(61680&(x=(52428&x)>>>2|(13107&x)<<2))>>>4|(3855&x)<<4,rev[i]=((65280&x)>>>8|(255&x)<<8)>>>1}var hMap=function(cd,mb,r){for(var s=cd.length,i=0,l=new u16(mb);i>>rvb]=sv}else for(co=new u16(s),i=0;i>>15-cd[i]);return co},flt=new u8(288);for(i=0;i<144;++i)flt[i]=8;for(i=144;i<256;++i)flt[i]=9;for(i=256;i<280;++i)flt[i]=7;for(i=280;i<288;++i)flt[i]=8;var fdt=new u8(32);for(i=0;i<32;++i)fdt[i]=5;var flrm=hMap(flt,9,1),fdrm=hMap(fdt,5,1),max=function(a){for(var m=a[0],i=1;im&&(m=a[i]);return m},bits=function(d,p,m){var o=p/8|0;return(d[o]|d[o+1]<<8)>>(7&p)&m},bits16=function(d,p){var o=p/8|0;return(d[o]|d[o+1]<<8|d[o+2]<<16)>>(7&p)},slc=function(v,s,e){(null==s||s<0)&&(s=0),(null==e||e>v.length)&&(e=v.length);var n=new(2==v.BYTES_PER_ELEMENT?u16:4==v.BYTES_PER_ELEMENT?u32:u8)(e-s);return n.set(v.subarray(s,e)),n},ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);if(e.code=ind,Error.captureStackTrace&&Error.captureStackTrace(e,err),!nt)throw e;return e},inflt=function(dat,buf,st){var sl=dat.length;if(!sl||st&&st.f&&!st.l)return buf||new u8(0);var noBuf=!buf||st,noSt=!st||st.i;st||(st={}),buf||(buf=new u8(3*sl));var cbuf=function(l){var bl=buf.length;if(l>bl){var nbuf=new u8(Math.max(2*bl,l));nbuf.set(buf),buf=nbuf}},final=st.f||0,pos=st.p||0,bt=st.b||0,lm=st.l,dm=st.d,lbt=st.m,dbt=st.n,tbts=8*sl;do{if(!lm){final=bits(dat,pos,1);var type=bits(dat,pos+1,3);if(pos+=3,!type){var l=dat[(s=4+((pos+7)/8|0))-4]|dat[s-3]<<8,t=s+l;if(t>sl){noSt&&err(0);break}noBuf&&cbuf(bt+l),buf.set(dat.subarray(s,t),bt),st.b=bt+=l,st.p=pos=8*t,st.f=final;continue}if(1==type)lm=flrm,dm=fdrm,lbt=9,dbt=5;else if(2==type){var hLit=bits(dat,pos,31)+257,hcLen=bits(dat,pos+10,15)+4,tl=hLit+bits(dat,pos+5,31)+1;pos+=14;for(var ldt=new u8(tl),clt=new u8(19),i=0;i>>4)<16)ldt[i++]=s;else{var c=0,n=0;for(16==s?(n=3+bits(dat,pos,3),pos+=2,c=ldt[i-1]):17==s?(n=3+bits(dat,pos,7),pos+=3):18==s&&(n=11+bits(dat,pos,127),pos+=7);n--;)ldt[i++]=c}}var lt=ldt.subarray(0,hLit),dt=ldt.subarray(hLit);lbt=max(lt),dbt=max(dt),lm=hMap(lt,lbt,1),dm=hMap(dt,dbt,1)}else err(1);if(pos>tbts){noSt&&err(0);break}}noBuf&&cbuf(bt+131072);for(var lms=(1<>>4;if((pos+=15&c)>tbts){noSt&&err(0);break}if(c||err(2),sym<256)buf[bt++]=sym;else{if(256==sym){lpos=pos,lm=null;break}var add=sym-254;if(sym>264){var b=fleb[i=sym-257];add=bits(dat,pos,(1<>>4;if(d||err(3),pos+=15&d,dt=fd[dsym],dsym>3&&(b=fdeb[dsym],dt+=bits16(dat,pos)&(1<tbts){noSt&&err(0);break}noBuf&&cbuf(bt+131072);for(var end=bt+add;bt>>0},b8=function(d,b){return b4(d,b)+4294967296*b4(d,b+4)};function inflateSync(data,out){return inflt(data,out)}var td="undefined"!=typeof TextDecoder&&new TextDecoder;try{td.decode(et,{stream:!0})}catch(e){}function strFromU8(dat,latin1){if(latin1){for(var r="",i=0;i127)+(c>223)+(c>239);if(i+eb>d.length)return[r,slc(d,i-1)];eb?3==eb?(c=((15&c)<<18|(63&d[i++])<<12|(63&d[i++])<<6|63&d[i++])-65536,r+=String.fromCharCode(55296|c>>10,56320|1023&c)):r+=1&eb?String.fromCharCode((31&c)<<6|63&d[i++]):String.fromCharCode((15&c)<<12|(63&d[i++])<<6|63&d[i++]):r+=String.fromCharCode(c)}}(dat),out=_a[0];return _a[1].length&&err(8),out}var slzh=function(d,b){return b+30+b2(d,b+26)+b2(d,b+28)},zh=function(d,b,z){var fnl=b2(d,b+28),fn=strFromU8(d.subarray(b+46,b+46+fnl),!(2048&b2(d,b+8))),es=b+46+fnl,bs=b4(d,b+20),_a=z&&4294967295==bs?z64e(d,es):[bs,b4(d,b+24),b4(d,b+42)],sc=_a[0],su=_a[1],off=_a[2];return[b2(d,b+10),sc,su,fn,es+b2(d,b+30)+b2(d,b+32),off]},z64e=function(d,b){for(;1!=b2(d,b);b+=4+b2(d,b+2));return[b8(d,b+12),b8(d,b+4),b8(d,b+20)]}; /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const hexToRgb=notation=>{if((notation=notation.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const r=parseInt(notation.substring(0,2),16)/255,g=parseInt(notation.substring(2,4),16)/255,b=parseInt(notation.substring(4,6),16)/255;return notation.length>=8?[r,g,b,parseInt(notation.substring(6,8),16)/255]:[r,g,b]},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n)));var saxes={},ed5$1={};!function(exports){function isNameStartChar(c){return c>=65&&c<=90||c>=97&&c<=122||58===c||95===c||8204===c||8205===c||c>=192&&c<=214||c>=216&&c<=246||c>=248&&c<=767||c>=880&&c<=893||c>=895&&c<=8191||c>=8304&&c<=8591||c>=11264&&c<=12271||c>=12289&&c<=55295||c>=63744&&c<=64975||c>=65008&&c<=65533||c>=65536&&c<=983039} +const clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const hexToRgb=notation=>{if((notation=notation.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const r=parseInt(notation.substring(0,2),16)/255,g=parseInt(notation.substring(2,4),16)/255,b=parseInt(notation.substring(4,6),16)/255;return notation.length>=8?[r,g,b,parseInt(notation.substring(6,8),16)/255]:[r,g,b]},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),transform=(matrix,...objects)=>{const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?transform(matrix,...object):object));return 1===results.length?results[0]:results};var saxes={},ed5$1={};!function(exports){function isNameStartChar(c){return c>=65&&c<=90||c>=97&&c<=122||58===c||95===c||8204===c||8205===c||c>=192&&c<=214||c>=216&&c<=246||c>=248&&c<=767||c>=880&&c<=893||c>=895&&c<=8191||c>=8304&&c<=8591||c>=11264&&c<=12271||c>=12289&&c<=55295||c>=63744&&c<=64975||c>=65008&&c<=65533||c>=65536&&c<=983039} /** * Character classes and associated utilities for the 5th edition of XML 1.0. * @@ -35,4 +35,4 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.CHAR="-퟿- * @license MIT * @copyright Louis-Dominique Dubeau */ -Object.defineProperty(exports,"__esModule",{value:!0}),exports.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",exports.NC_NAME_CHAR="-"+exports.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",exports.NC_NAME_START_CHAR_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]$","u"),exports.NC_NAME_CHAR_RE=new RegExp("^["+exports.NC_NAME_CHAR+"]$","u"),exports.NC_NAME_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]["+exports.NC_NAME_CHAR+"]*$","u"),exports.isNCNameStartChar=isNCNameStartChar,exports.isNCNameChar=function(c){return isNCNameStartChar(c)||45===c||46===c||c>=48&&c<=57||183===c||c>=768&&c<=879||c>=8255&&c<=8256}}(ed3),Object.defineProperty(saxes,"__esModule",{value:!0}),saxes.SaxesParser=saxes.EVENTS=void 0;var isS=ed5$1.isS,isChar10=ed5$1.isChar,isNameStartChar=ed5$1.isNameStartChar,isNameChar=ed5$1.isNameChar,S_LIST=ed5$1.S_LIST,NAME_RE=ed5$1.NAME_RE,isChar11=ed2$1.isChar,isNCNameStartChar=ed3.isNCNameStartChar,isNCNameChar=ed3.isNCNameChar,NC_NAME_RE=ed3.NC_NAME_RE;const XML_NAMESPACE="http://www.w3.org/XML/1998/namespace",XMLNS_NAMESPACE="http://www.w3.org/2000/xmlns/",rootNS={__proto__:null,xml:XML_NAMESPACE,xmlns:XMLNS_NAMESPACE},XML_ENTITIES={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},isQuote=c=>34===c||39===c,QUOTES=[34,39],DOCTYPE_TERMINATOR=[...QUOTES,91,62],DTD_TERMINATOR=[...QUOTES,60,93],XML_DECL_NAME_TERMINATOR=[61,63,...S_LIST],ATTRIB_VALUE_UNQUOTED_TERMINATOR=[...S_LIST,62,38,60];function nsPairCheck(parser,prefix,uri){switch(prefix){case"xml":uri!==XML_NAMESPACE&&parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);break;case"xmlns":uri!==XMLNS_NAMESPACE&&parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`)}switch(uri){case XMLNS_NAMESPACE:parser.fail(""===prefix?`the default namespace may not be set to ${uri}.`:`may not assign a prefix (even "xmlns") to the URI ${XMLNS_NAMESPACE}.`);break;case XML_NAMESPACE:switch(prefix){case"xml":break;case"":parser.fail(`the default namespace may not be set to ${uri}.`);break;default:parser.fail("may not assign the xml namespace to another prefix.")}}}const isNCName=name=>NC_NAME_RE.test(name),isName=name=>NAME_RE.test(name);saxes.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];const EVENT_NAME_TO_HANDLER_NAME={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};saxes.SaxesParser=class{constructor(opt){this.opt=null!=opt?opt:{},this.fragmentOpt=!!this.opt.fragment;const xmlnsOpt=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=!1!==this.opt.position,this.fileName=this.opt.fileName,xmlnsOpt){this.nameStartCheck=isNCNameStartChar,this.nameCheck=isNCNameChar,this.isName=isNCName,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},rootNS);const additional=this.opt.additionalNamespaces;null!=additional&&(function(parser,mapping){for(const local of Object.keys(mapping))nsPairCheck(parser,local,mapping[local])}(this,additional),Object.assign(this.ns,additional))}else this.nameStartCheck=isNameStartChar,this.nameCheck=isNameChar,this.isName=isName,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var _a;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=0,this.attribList=[];const{fragmentOpt:fragmentOpt}=this;this.state=fragmentOpt?13:0,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=fragmentOpt,this.xmlDeclPossible=!fragmentOpt,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:defaultXMLVersion}=this.opt;if(void 0===defaultXMLVersion){if(!0===this.opt.forceXMLVersion)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");defaultXMLVersion="1.0"}this.setXMLVersion(defaultXMLVersion),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(XML_ENTITIES),null===(_a=this.readyHandler)||void 0===_a||_a.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(name,handler){this[EVENT_NAME_TO_HANDLER_NAME[name]]=handler}off(name){this[EVENT_NAME_TO_HANDLER_NAME[name]]=void 0}makeError(message){var _a;let msg=null!==(_a=this.fileName)&&void 0!==_a?_a:"";return this.trackPosition&&(msg.length>0&&(msg+=":"),msg+=`${this.line}:${this.column}`),msg.length>0&&(msg+=": "),new Error(msg+message)}fail(message){const err=this.makeError(message),handler=this.errorHandler;if(void 0===handler)throw err;return handler(err),this}write(chunk){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let end=!1;null===chunk?(end=!0,chunk=""):"object"==typeof chunk&&(chunk=chunk.toString()),void 0!==this.carriedFromPrevious&&(chunk=`${this.carriedFromPrevious}${chunk}`,this.carriedFromPrevious=void 0);let limit=chunk.length;const lastCode=chunk.charCodeAt(limit-1);!end&&(13===lastCode||lastCode>=55296&&lastCode<=56319)&&(this.carriedFromPrevious=chunk[limit-1],limit--,chunk=chunk.slice(0,limit));const{stateTable:stateTable}=this;for(this.chunk=chunk,this.i=0;this.i=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>=32||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:return 10===chunk.charCodeAt(i+1)&&(this.i=i+2),this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCode11(){const{chunk:chunk,i:i}=this;if(this.prevI=i,this.i=i+1,i>=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>31&&code<127||code>159&&8232!==code||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:{const next=chunk.charCodeAt(i+1);10!==next&&133!==next||(this.i=i+2)}case 133:case 8232:return this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCodeNorm(){const c=this.getCode();return-2===c?10:c}unget(){this.i=this.prevI,this.column--}captureTo(chars){let{i:start}=this;const{chunk:chunk}=this;for(;;){const c=this.getCode(),isNLLike=-2===c,final=isNLLike?10:c;if(-1===final||chars.includes(final))return this.text+=chunk.slice(start,this.prevI),final;isNLLike&&(this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i)}}captureToChar(char){let{i:start}=this;const{chunk:chunk}=this;for(;;){let c=this.getCode();switch(c){case-2:this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i,c=10;break;case-1:return this.text+=chunk.slice(start),!1}if(c===char)return this.text+=chunk.slice(start,this.prevI),!0}}captureNameChars(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCode();if(-1===c)return this.name+=chunk.slice(start),-1;if(!isNameChar(c))return this.name+=chunk.slice(start,this.prevI),-2===c?10:c}}skipSpaces(){for(;;){const c=this.getCodeNorm();if(-1===c||!isS(c))return c}}setXMLVersion(version){this.currentXMLVersion=version,"1.0"===version?(this.isChar=isChar10,this.getCode=this.getCode10):(this.isChar=isChar11,this.getCode=this.getCode11)}sBegin(){65279===this.chunk.charCodeAt(0)&&(this.i++,this.column++),this.state=1}sBeginWhitespace(){const iBefore=this.i,c=this.skipSpaces();switch(this.prevI!==iBefore&&(this.xmlDeclPossible=!1),c){case 60:if(this.state=15,0!==this.text.length)throw new Error("no-empty text at start");break;case-1:break;default:this.unget(),this.state=13,this.xmlDeclPossible=!1}}sDoctype(){var _a;const c=this.captureTo(DOCTYPE_TERMINATOR);switch(c){case 62:null===(_a=this.doctypeHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13,this.doctype=!0;break;case-1:break;default:this.text+=String.fromCodePoint(c),91===c?this.state=4:isQuote(c)&&(this.state=3,this.q=c)}}sDoctypeQuote(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.q=null,this.state=2)}sDTD(){const c=this.captureTo(DTD_TERMINATOR);-1!==c&&(this.text+=String.fromCodePoint(c),93===c?this.state=2:60===c?this.state=6:isQuote(c)&&(this.state=5,this.q=c))}sDTDQuoted(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.state=4,this.q=null)}sDTDOpenWaka(){const c=this.getCodeNorm();switch(this.text+=String.fromCodePoint(c),c){case 33:this.state=7,this.openWakaBang="";break;case 63:this.state=11;break;default:this.state=4}}sDTDOpenWakaBang(){const char=String.fromCodePoint(this.getCodeNorm()),owb=this.openWakaBang+=char;this.text+=char,"-"!==owb&&(this.state="--"===owb?8:4,this.openWakaBang="")}sDTDComment(){this.captureToChar(45)&&(this.text+="-",this.state=9)}sDTDCommentEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),this.state=45===c?10:8}sDTDCommentEnded(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c?this.state=4:(this.fail("malformed comment."),this.state=8)}sDTDPI(){this.captureToChar(63)&&(this.text+="?",this.state=12)}sDTDPIEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c&&(this.state=4)}sText(){0!==this.tags.length?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:start}=this;const{chunk:chunk}=this;loop:for(;;)switch(this.getCode()){case-2:this.entity+=`${chunk.slice(start,this.prevI)}\n`,start=this.i;break;case 59:{const{entityReturnState:entityReturnState}=this,entity=this.entity+chunk.slice(start,this.prevI);let parsed;this.state=entityReturnState,""===entity?(this.fail("empty entity name."),parsed="&;"):(parsed=this.parseEntity(entity),this.entity=""),13===entityReturnState&&void 0===this.textHandler||(this.text+=parsed);break loop}case-1:this.entity+=chunk.slice(start);break loop}}sOpenWaka(){const c=this.getCode();if(isNameStartChar(c))this.state=34,this.unget(),this.xmlDeclPossible=!1;else switch(c){case 47:this.state=43,this.xmlDeclPossible=!1;break;case 33:this.state=16,this.openWakaBang="",this.xmlDeclPossible=!1;break;case 63:this.state=23;break;default:this.fail("disallowed character in tag name"),this.state=13,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=20,this.openWakaBang="";break;case"--":this.state=17,this.openWakaBang="";break;case"DOCTYPE":this.state=2,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(45)&&(this.state=18)}sCommentEnding(){var _a;const c=this.getCodeNorm();45===c?(this.state=19,null===(_a=this.commentHandler)||void 0===_a||_a.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(c)}`,this.state=17)}sCommentEnded(){const c=this.getCodeNorm();62!==c?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(c)}`,this.state=17):this.state=13}sCData(){this.captureToChar(93)&&(this.state=21)}sCDataEnding(){const c=this.getCodeNorm();93===c?this.state=22:(this.text+=`]${String.fromCodePoint(c)}`,this.state=20)}sCDataEnding2(){var _a;const c=this.getCodeNorm();switch(c){case 62:null===(_a=this.cdataHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13;break;case 93:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(c)}`,this.state=20}}sPIFirstChar(){const c=this.getCodeNorm();this.nameStartCheck(c)?(this.piTarget+=String.fromCodePoint(c),this.state=24):63===c||isS(c)?(this.fail("processing instruction without a target."),this.state=63===c?26:25):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c),this.state=24)}sPIRest(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCodeNorm();if(-1===c)return void(this.piTarget+=chunk.slice(start));if(!this.nameCheck(c)){this.piTarget+=chunk.slice(start,this.prevI);const isQuestion=63===c;isQuestion||isS(c)?"xml"===this.piTarget?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=isQuestion?33:27):this.state=isQuestion?26:25:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c));break}}}sPIBody(){if(0===this.text.length){const c=this.getCodeNorm();63===c?this.state=26:isS(c)||(this.text=String.fromCodePoint(c))}else this.captureToChar(63)&&(this.state=26)}sPIEnding(){var _a;const c=this.getCodeNorm();if(62===c){const{piTarget:piTarget}=this;"xml"===piTarget.toLowerCase()&&this.fail("the XML declaration must appear at the start of the document."),null===(_a=this.piHandler)||void 0===_a||_a.call(this,{target:piTarget,body:this.text}),this.piTarget=this.text="",this.state=13}else 63===c?this.text+="?":(this.text+=`?${String.fromCodePoint(c)}`,this.state=25);this.xmlDeclPossible=!1}sXMLDeclNameStart(){const c=this.skipSpaces();63!==c?-1!==c&&(this.state=28,this.name=String.fromCodePoint(c)):this.state=33}sXMLDeclName(){const c=this.captureTo(XML_DECL_NAME_TERMINATOR);if(63===c)return this.state=33,this.name+=this.text,this.text="",void this.fail("XML declaration is incomplete.");if(isS(c)||61===c){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=61===c?30:29}}sXMLDeclEq(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(61!==c&&this.fail("value required."),this.state=30)}sXMLDeclValueStart(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(isQuote(c)?this.q=c:(this.fail("value must be quoted."),this.q=32),this.state=31)}sXMLDeclValue(){const c=this.captureTo([this.q,63]);if(63===c)return this.state=33,this.text="",void this.fail("XML declaration is incomplete.");if(-1===c)return;const value=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];const version=value;this.xmlDecl.version=version,/^1\.[0-9]+$/.test(version)?this.opt.forceXMLVersion||this.setXMLVersion(version):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=value;break;case"standalone":"yes"!==value&&"no"!==value&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=value}this.name="",this.state=32}sXMLDeclSeparator(){const c=this.getCodeNorm();63!==c?(isS(c)||(this.fail("whitespace required."),this.unget()),this.state=27):this.state=33}sXMLDeclEnding(){var _a;62===this.getCodeNorm()?("xml"!==this.piTarget?this.fail("processing instructions are not allowed before root."):"version"!==this.name&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),null===(_a=this.xmldeclHandler)||void 0===_a||_a.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=13):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var _a;const c=this.captureNameChars();if(-1===c)return;const tag=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=tag.ns=Object.create(null)),null===(_a=this.openTagStartHandler)||void 0===_a||_a.call(this,tag),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),c){case 62:this.openTag();break;case 47:this.state=35;break;default:isS(c)||this.fail("disallowed character in tag name."),this.state=36}}sOpenTagSlash(){62===this.getCode()?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=36)}sAttrib(){const c=this.skipSpaces();-1!==c&&(isNameStartChar(c)?(this.unget(),this.state=37):62===c?this.openTag():47===c?this.state=35:this.fail("disallowed character in attribute name."))}sAttribName(){const c=this.captureNameChars();61===c?this.state=39:isS(c)?this.state=38:62===c?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):-1!==c&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){const c=this.skipSpaces();switch(c){case-1:return;case 61:this.state=39;break;default:this.fail("attribute without value."),this.text="",this.name="",62===c?this.openTag():isNameStartChar(c)?(this.unget(),this.state=37):(this.fail("disallowed character in attribute name."),this.state=36)}}sAttribValue(){const c=this.getCodeNorm();isQuote(c)?(this.q=c,this.state=40):isS(c)||(this.fail("unquoted attribute value."),this.state=42,this.unget())}sAttribValueQuoted(){const{q:q,chunk:chunk}=this;let{i:start}=this;for(;;)switch(this.getCode()){case q:return this.pushAttrib(this.name,this.text+chunk.slice(start,this.prevI)),this.name=this.text="",this.q=null,void(this.state=41);case 38:return this.text+=chunk.slice(start,this.prevI),this.state=14,void(this.entityReturnState=40);case 10:case-2:case 9:this.text+=`${chunk.slice(start,this.prevI)} `,start=this.i;break;case 60:return this.text+=chunk.slice(start,this.prevI),void this.fail("disallowed character.");case-1:return void(this.text+=chunk.slice(start))}}sAttribValueClosed(){const c=this.getCodeNorm();isS(c)?this.state=36:62===c?this.openTag():47===c?this.state=35:isNameStartChar(c)?(this.fail("no whitespace between attributes."),this.unget(),this.state=37):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){const c=this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);switch(c){case 38:this.state=14,this.entityReturnState=42;break;case 60:this.fail("disallowed character.");break;case-1:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",62===c?this.openTag():this.state=36}}sCloseTag(){const c=this.captureNameChars();62===c?this.closeTag():isS(c)?this.state=44:-1!==c&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case 62:this.closeTag();break;case-1:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:start,forbiddenState:forbiddenState}=this;const{chunk:chunk,textHandler:handler}=this;scanLoop:for(;;)switch(this.getCode()){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}forbiddenState=0;break scanLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),forbiddenState=0;break scanLoop;case 93:switch(forbiddenState){case 0:forbiddenState=1;break;case 1:forbiddenState=2;break;case 2:break;default:throw new Error("impossible state")}break;case 62:2===forbiddenState&&this.fail('the string "]]>" is disallowed in char data.'),forbiddenState=0;break;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i,forbiddenState=0;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break scanLoop;default:forbiddenState=0}this.forbiddenState=forbiddenState}handleTextOutsideRoot(){let{i:start}=this;const{chunk:chunk,textHandler:handler}=this;let nonSpace=!1;outRootLoop:for(;;){const code=this.getCode();switch(code){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}break outRootLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),nonSpace=!0;break outRootLoop;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break outRootLoop;default:isS(code)||(nonSpace=!0)}}nonSpace&&(this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(name,value){var _a;const{prefix:prefix,local:local}=this.qname(name),attr={name:name,prefix:prefix,local:local,value:value};if(this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr),"xmlns"===prefix){const trimmed=value.trim();"1.0"===this.currentXMLVersion&&""===trimmed&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[local]=trimmed,nsPairCheck(this,local,trimmed)}else if("xmlns"===name){const trimmed=value.trim();this.topNS[""]=trimmed,nsPairCheck(this,"",trimmed)}}pushAttribPlain(name,value){var _a;const attr={name:name,value:value};this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr)}end(){var _a,_b;this.sawRoot||this.fail("document must contain a root element.");const{tags:tags}=this;for(;tags.length>0;){const tag=tags.pop();this.fail(`unclosed tag: ${tag.name}`)}0!==this.state&&13!==this.state&&this.fail("unexpected end.");const{text:text}=this;return 0!==text.length&&(null===(_a=this.textHandler)||void 0===_a||_a.call(this,text),this.text=""),this._closed=!0,null===(_b=this.endHandler)||void 0===_b||_b.call(this),this._init(),this}resolve(prefix){var _a,_b;let uri=this.topNS[prefix];if(void 0!==uri)return uri;const{tags:tags}=this;for(let index=tags.length-1;index>=0;index--)if(uri=tags[index].ns[prefix],void 0!==uri)return uri;return uri=this.ns[prefix],void 0!==uri?uri:null===(_b=(_a=this.opt).resolvePrefix)||void 0===_b?void 0:_b.call(_a,prefix)}qname(name){const colon=name.indexOf(":");if(-1===colon)return{prefix:"",local:name};const local=name.slice(colon+1),prefix=name.slice(0,colon);return(""===prefix||""===local||local.includes(":"))&&this.fail(`malformed name: ${name}.`),{prefix:prefix,local:local}}processAttribsNS(){var _a;const{attribList:attribList}=this,tag=this.tag;{const{prefix:prefix,local:local}=this.qname(tag.name);tag.prefix=prefix,tag.local=local;const uri=tag.uri=null!==(_a=this.resolve(prefix))&&void 0!==_a?_a:"";""!==prefix&&("xmlns"===prefix&&this.fail('tags may not have "xmlns" as prefix.'),""===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),tag.uri=prefix))}if(0===attribList.length)return;const{attributes:attributes}=tag,seen=new Set;for(const attr of attribList){const{name:name,prefix:prefix,local:local}=attr;let uri,eqname;""===prefix?(uri="xmlns"===name?XMLNS_NAMESPACE:"",eqname=name):(uri=this.resolve(prefix),void 0===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),uri=prefix),eqname=`{${uri}}${local}`),seen.has(eqname)&&this.fail(`duplicate attribute: ${eqname}.`),seen.add(eqname),attr.uri=uri,attributes[name]=attr}this.attribList=[]}processAttribsPlain(){const{attribList:attribList}=this,attributes=this.tag.attributes;for(const{name:name,value:value}of attribList)void 0!==attributes[name]&&this.fail(`duplicate attribute: ${name}.`),attributes[name]=value;this.attribList=[]}openTag(){var _a;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!1,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),tags.push(tag),this.state=13,this.name=""}openSelfClosingTag(){var _a,_b,_c;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!0,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),null===(_b=this.closeTagHandler)||void 0===_b||_b.call(this,tag),null===(this.tag=null!==(_c=tags[tags.length-1])&&void 0!==_c?_c:null)&&(this.closedRoot=!0),this.state=13,this.name=""}closeTag(){const{tags:tags,name:name}=this;if(this.state=13,this.name="",""===name)return this.fail("weird empty close tag."),void(this.text+="");const handler=this.closeTagHandler;let l=tags.length;for(;l-- >0;){const tag=this.tag=tags.pop();if(this.topNS=tag.ns,null==handler||handler(tag),tag.name===name)break;this.fail("unexpected close tag.")}0===l?this.closedRoot=!0:l<0&&(this.fail(`unmatched closing tag: ${name}.`),this.text+=``)}parseEntity(entity){if("#"!==entity[0]){const defined=this.ENTITIES[entity];return void 0!==defined?defined:(this.fail(this.isName(entity)?"undefined entity.":"disallowed character in entity name."),`&${entity};`)}let num=NaN;return"x"===entity[1]&&/^#x[0-9a-f]+$/i.test(entity)?num=parseInt(entity.slice(2),16):/^#[0-9]+$/.test(entity)&&(num=parseInt(entity.slice(1),10)),this.isChar(num)?String.fromCodePoint(num):(this.fail("malformed character entity."),`&${entity};`)}};const convertTransform=text=>{const values=text.split(/ +/).map((s=>parseFloat(s)));return index$c.fromValues(values[0],values[1],values[2],0,values[3],values[4],values[5],0,values[6],values[7],values[8],0,values[9],values[10],values[11],1)},parseModel$1=attributes=>{const obj={type:"model",unit:"millimeter"};return attributes.unit&&(obj.unit=attributes.unit),obj},parseMesh=attributes=>{const obj={type:"mesh",vertices:[],triangles:[],properties:[]};return obj},parseVertex=attributes=>{const obj={type:"vertex"};return obj.vertex=[parseFloat(attributes.x),parseFloat(attributes.y),parseFloat(attributes.z)],obj},parseTriangle=attributes=>{const obj={type:"triangle"};return obj.indices=[parseFloat(attributes.v1),parseFloat(attributes.v2),parseFloat(attributes.v3)],attributes.p1&&(obj.p1=parseFloat(attributes.p1)),attributes.p2&&(obj.p2=parseFloat(attributes.p2)),attributes.p3&&(obj.p3=parseFloat(attributes.p3)),attributes.pid&&(obj.pid=attributes.pid),obj},parseItem=attributes=>{const obj={type:"item",transform:index$c.create()};return obj.objectid=attributes.objectid,attributes.transform&&(obj.transform=convertTransform(attributes.transform)),obj},parseObject=attributes=>{const obj={type:"object",otype:"model"};return obj.id=attributes.id,attributes.type&&(obj.otype=attributes.type),attributes.partnumber&&(obj.partnumber=attributes.partnumber),attributes.name&&(obj.name=attributes.name),attributes.pid&&(obj.pid=attributes.pid),attributes.pindex&&(obj.pindex=parseFloat(attributes.pindex)),obj},parseComponents=attributes=>({type:"components"}),parseComponent=attributes=>{const obj={type:"component",transform:index$c.create()};return obj.objectid=attributes.objectid,attributes.transform&&(obj.transform=convertTransform(attributes.transform)),obj},parseBaseMaterials=attributes=>{const obj={type:"basematerials",bases:[]};return obj.id=attributes.id,obj},parseBase=attributes=>{const obj={type:"base"};obj.name=attributes.name;let color=hexToRgb(attributes.displaycolor);return 3===color.length&&(color=[color[0],color[1],color[2],1]),obj.displaycolor=color,obj},parseColorGroup=attributes=>{const obj={type:"colorgroup",colors:[]};return obj.id=attributes.id,obj},parseColor=attributes=>{const obj={type:"color"};let color=hexToRgb(attributes.color);return 3===color.length&&(color=[color[0],color[1],color[2],1]),obj.color=color,obj},parse=src=>{let items=[],materials=[],colorgroups=[],objects=[];return((src,storage)=>{let{items:items,materials:materials,colorgroups:colorgroups,objects:objects}=storage,objLast=null;const parser=new saxes.SaxesParser;parser.on("error",(e=>{console.log(e)})),parser.on("opentag",(node=>{const objMap={MODEL:parseModel$1,ITEM:parseItem,OBJECT:parseObject,MESH:parseMesh,VERTEX:parseVertex,TRIANGLE:parseTriangle,COMPONENTS:parseComponents,COMPONENT:parseComponent,BASEMATERIALS:parseBaseMaterials,BASE:parseBase,MCOLORGROUP:parseColorGroup,MCOLOR:parseColor,undefined:()=>console.log(`WARNING: unsupported 3MF element: ${node.name}`)},elementName=node.name.toUpperCase().replace(":",""),obj=objMap[elementName]?objMap[elementName](node.attributes):null;let object=null,material=null,colorgroup=null;if(obj){switch(obj.type){case"model":break;case"item":items.push(obj);break;case"object":objects.push(obj);break;case"mesh":object=objects.at(-1),object.mesh=obj;break;case"vertex":object=objects.at(-1),object.mesh.vertices.push(obj.vertex);break;case"triangle":object=objects.at(-1),object.mesh.triangles.push(obj.indices),object.mesh.properties.push(((object,triangle)=>{const property={};return object.pid&&(property.pid=object.pid),triangle.pid&&(property.pid=triangle.pid),"p1"in triangle?property.pindex=triangle.p1:"pindex"in object&&(property.pindex=object.pindex),property})(object,obj));break;case"components":object=objects.at(-1),object.components=[];break;case"component":object=objects.at(-1),object.components.push(obj);break;case"basematerials":materials.push(obj);break;case"base":material=materials.at(-1),material.bases.push(obj);break;case"colorgroup":colorgroups.push(obj);break;case"color":colorgroup=colorgroups.at(-1),colorgroup.colors.push(obj);break;default:console.log("WARNING: unknown object type",obj.type)}objLast=obj}})),parser.on("closetag",(node=>{})),parser.on("text",(value=>{null!==value&&(value=value.trim()).length>0&&objLast&&(objLast.value=value,objLast=null)})),parser.on("end",(()=>{})),parser.write(src).close()})(src,{items:items,materials:materials,colorgroups:colorgroups,objects:objects}),{items:items,materials:materials,colorgroups:colorgroups,objects:objects}},parseModel=(options,source)=>{const{objects:objects,materials:materials,colorgroups:colorgroups,items:items}=parse(source);if(0===objects.length)throw new Error("3MF parsing failed, no valid 3MF objects retrieved");const buildItems=[];return items.forEach((item=>{const components=getComponents(item,objects);for(let i=0;i{const object=objects.find((obj=>obj.id===component.objectid)),components=[];if(object.mesh){const cmp={otype:object.otype,oid:object.id,transform:component.transform};object.name&&(cmp.oname=object.name),object.partnumber&&(cmp.opartnumber=object.partnumber),components.push(cmp)}return object.components&&object.components.forEach((c=>{getComponents(c,objects).forEach((s=>{index$c.multiply(s.transform,c.transform,s.transform),components.push(s)}))})),components},getDisplayColor$1=(property,materials,colorgroups)=>{if("pid"in property&&"pindex"in property){const material=materials.find((m=>property.pid===m.id));if(material)return material.bases[property.pindex].displaycolor;const colorgroup=colorgroups.find((g=>property.pid===g.id));if(colorgroup)return colorgroup.colors[property.pindex].color}return null},translateObject=(options,object,materials,colorgroups)=>{let code=`\n// Object ID: ${object.id}\n// Object Type: ${object.otype}`;if(object.name&&(code+=`\n// Object Name: ${object.name}`),object.mesh){let displaycolors="const displaycolors = null",shapecolor=((object,materials,colorgroups)=>{const displayColor=getDisplayColor$1(object,materials,colorgroups);return displayColor?`shape.color = [${displayColor}]`:""})(object,materials,colorgroups);const properties=((options,properties,materials,colorgroups)=>{const colors=[];for(let i=0;i {\n ${((options,vertices)=>{let code="const vertices = [\n";for(let i=0;i{let code="const triangles = [\n";for(let i=0;i{const{version:version,addMetaData:addMetaData,filename:filename}=options,translatedModels=models.map((source=>((options,source)=>{const{includedType:includedType}=options;let{buildItems:buildItems,objects:objects,materials:materials,colorgroups:colorgroups}=parseModel(0,source);"all"!==includedType&&(buildItems=buildItems.filter((item=>item.mesh.type===includedType)));const translatedObjects=objects.map(((object,index)=>translateObject(0,object,materials,colorgroups))),translatedItems=buildItems.map(((item,index)=>((options,item)=>{let code=`\n// Build Item ${item.sequence}\n// Object:\n// ID: ${item.oid}\n// Type: ${item.otype}`;return item.name&&(code+=`\n// Name: ${item.oname}`),code+=`\nconst createBuildItem${item.sequence} = () => {\n const object = objects["${item.oid}"]\n ${((options,transform)=>`const transform = [${transform}]`)(0,item.transform)}\n return transform(transform, object)\n}\n\nbuilditems.push(createBuildItem${item.sequence}())\n`,code})(0,item)));return translatedObjects.join("")+translatedItems.join("")})(options,source))),metacode=addMetaData?`\n//\n// Produced by JSCAD IO Library : 3MF Deserializer\n// Version: ${version}\n// Date: ${new Date}\n// Source: ${filename}\n//\n`:"";let bodycode="";for(let i=0;i {\n return builditems\n}\n"},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),getDisplayColor=(property,materials,colorgroups)=>{if("pid"in property&&"pindex"in property){const material=materials.find((m=>property.pid===m.id));if(material)return material.bases[property.pindex].displaycolor;const colorgroup=colorgroups.find((g=>property.pid===g.id));if(colorgroup)return colorgroup.colors[property.pindex].color}return null},instantiateObject=(options,object,materials,colorgroups)=>{if(object.mesh){const mesh=object.mesh,displaycolors=((options,properties,materials,colorgroups)=>{const displaycolors=[];for(let i=0;i{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({points:mesh.vertices,faces:mesh.triangles,colors:displaycolors});shape.id=object.id,shape.type=object.otype,object.name&&(shape.name=object.name);const displayColor=getDisplayColor(object,materials,colorgroups);return!displaycolors&&displayColor&&(shape.color=displayColor),shape}return index$6.create()},instantiateModel=(options,model)=>{const{includedType:includedType}=options;let{buildItems:buildItems,objects:objects,materials:materials,colorgroups:colorgroups}=parseModel(0,model);"all"!==includedType&&(buildItems=buildItems.filter((item=>item.mesh.type===includedType)));const instantiatedObjects={};objects.forEach((object=>{const instantiatedObject=instantiateObject(0,object,materials,colorgroups);instantiatedObjects[object.id]=instantiatedObject}));const instantiatedItems=buildItems.map((item=>{const object=instantiatedObjects[item.oid];return((matrix,...objects)=>{if(0===(objects=flatten$1(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results})(item.transform,object)}));return instantiatedItems};exports.deserialize=(options,input)=>{const defaults={output:"script",version:"3.0.0-alpha.0",addMetaData:!0,includedItems:"build",includedType:"all"};options=Object.assign({},defaults,options);let models=[];try{const decompressed=function(data,opts){for(var files={},e=data.length-22;101010256!=b4(data,e);--e)(!e||data.length-e>65558)&&err(13);var c=b2(data,e+8);if(!c)return{};var o=b4(data,e+16),z=4294967295==o;z&&(e=b4(data,e-12),101075792!=b4(data,e)&&err(13),c=b4(data,e+32),o=b4(data,e+48));for(var fltr=opts&&opts.filter,i=0;i{if(key.endsWith("3dmodel.model")){const contents=strFromU8(decompressed[key]);models.push(contents)}}))}catch(e){models=[input]}return"script"===options.output?translateModels(options,models):((options,models)=>{const shapeLists=models.map((model=>instantiateModel(options,model)));return flatten(shapeLists)})(options,models)},exports.mimeType="model/3mf",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscad3MFDeserializer={}); +Object.defineProperty(exports,"__esModule",{value:!0}),exports.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",exports.NC_NAME_CHAR="-"+exports.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",exports.NC_NAME_START_CHAR_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]$","u"),exports.NC_NAME_CHAR_RE=new RegExp("^["+exports.NC_NAME_CHAR+"]$","u"),exports.NC_NAME_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]["+exports.NC_NAME_CHAR+"]*$","u"),exports.isNCNameStartChar=isNCNameStartChar,exports.isNCNameChar=function(c){return isNCNameStartChar(c)||45===c||46===c||c>=48&&c<=57||183===c||c>=768&&c<=879||c>=8255&&c<=8256}}(ed3),Object.defineProperty(saxes,"__esModule",{value:!0}),saxes.SaxesParser=saxes.EVENTS=void 0;var isS=ed5$1.isS,isChar10=ed5$1.isChar,isNameStartChar=ed5$1.isNameStartChar,isNameChar=ed5$1.isNameChar,S_LIST=ed5$1.S_LIST,NAME_RE=ed5$1.NAME_RE,isChar11=ed2$1.isChar,isNCNameStartChar=ed3.isNCNameStartChar,isNCNameChar=ed3.isNCNameChar,NC_NAME_RE=ed3.NC_NAME_RE;const XML_NAMESPACE="http://www.w3.org/XML/1998/namespace",XMLNS_NAMESPACE="http://www.w3.org/2000/xmlns/",rootNS={__proto__:null,xml:XML_NAMESPACE,xmlns:XMLNS_NAMESPACE},XML_ENTITIES={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},isQuote=c=>34===c||39===c,QUOTES=[34,39],DOCTYPE_TERMINATOR=[...QUOTES,91,62],DTD_TERMINATOR=[...QUOTES,60,93],XML_DECL_NAME_TERMINATOR=[61,63,...S_LIST],ATTRIB_VALUE_UNQUOTED_TERMINATOR=[...S_LIST,62,38,60];function nsPairCheck(parser,prefix,uri){switch(prefix){case"xml":uri!==XML_NAMESPACE&&parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);break;case"xmlns":uri!==XMLNS_NAMESPACE&&parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`)}switch(uri){case XMLNS_NAMESPACE:parser.fail(""===prefix?`the default namespace may not be set to ${uri}.`:`may not assign a prefix (even "xmlns") to the URI ${XMLNS_NAMESPACE}.`);break;case XML_NAMESPACE:switch(prefix){case"xml":break;case"":parser.fail(`the default namespace may not be set to ${uri}.`);break;default:parser.fail("may not assign the xml namespace to another prefix.")}}}const isNCName=name=>NC_NAME_RE.test(name),isName=name=>NAME_RE.test(name);saxes.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];const EVENT_NAME_TO_HANDLER_NAME={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};saxes.SaxesParser=class{constructor(opt){this.opt=null!=opt?opt:{},this.fragmentOpt=!!this.opt.fragment;const xmlnsOpt=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=!1!==this.opt.position,this.fileName=this.opt.fileName,xmlnsOpt){this.nameStartCheck=isNCNameStartChar,this.nameCheck=isNCNameChar,this.isName=isNCName,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},rootNS);const additional=this.opt.additionalNamespaces;null!=additional&&(function(parser,mapping){for(const local of Object.keys(mapping))nsPairCheck(parser,local,mapping[local])}(this,additional),Object.assign(this.ns,additional))}else this.nameStartCheck=isNameStartChar,this.nameCheck=isNameChar,this.isName=isName,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var _a;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=0,this.attribList=[];const{fragmentOpt:fragmentOpt}=this;this.state=fragmentOpt?13:0,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=fragmentOpt,this.xmlDeclPossible=!fragmentOpt,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:defaultXMLVersion}=this.opt;if(void 0===defaultXMLVersion){if(!0===this.opt.forceXMLVersion)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");defaultXMLVersion="1.0"}this.setXMLVersion(defaultXMLVersion),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(XML_ENTITIES),null===(_a=this.readyHandler)||void 0===_a||_a.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(name,handler){this[EVENT_NAME_TO_HANDLER_NAME[name]]=handler}off(name){this[EVENT_NAME_TO_HANDLER_NAME[name]]=void 0}makeError(message){var _a;let msg=null!==(_a=this.fileName)&&void 0!==_a?_a:"";return this.trackPosition&&(msg.length>0&&(msg+=":"),msg+=`${this.line}:${this.column}`),msg.length>0&&(msg+=": "),new Error(msg+message)}fail(message){const err=this.makeError(message),handler=this.errorHandler;if(void 0===handler)throw err;return handler(err),this}write(chunk){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let end=!1;null===chunk?(end=!0,chunk=""):"object"==typeof chunk&&(chunk=chunk.toString()),void 0!==this.carriedFromPrevious&&(chunk=`${this.carriedFromPrevious}${chunk}`,this.carriedFromPrevious=void 0);let limit=chunk.length;const lastCode=chunk.charCodeAt(limit-1);!end&&(13===lastCode||lastCode>=55296&&lastCode<=56319)&&(this.carriedFromPrevious=chunk[limit-1],limit--,chunk=chunk.slice(0,limit));const{stateTable:stateTable}=this;for(this.chunk=chunk,this.i=0;this.i=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>=32||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:return 10===chunk.charCodeAt(i+1)&&(this.i=i+2),this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCode11(){const{chunk:chunk,i:i}=this;if(this.prevI=i,this.i=i+1,i>=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>31&&code<127||code>159&&8232!==code||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:{const next=chunk.charCodeAt(i+1);10!==next&&133!==next||(this.i=i+2)}case 133:case 8232:return this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCodeNorm(){const c=this.getCode();return-2===c?10:c}unget(){this.i=this.prevI,this.column--}captureTo(chars){let{i:start}=this;const{chunk:chunk}=this;for(;;){const c=this.getCode(),isNLLike=-2===c,final=isNLLike?10:c;if(-1===final||chars.includes(final))return this.text+=chunk.slice(start,this.prevI),final;isNLLike&&(this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i)}}captureToChar(char){let{i:start}=this;const{chunk:chunk}=this;for(;;){let c=this.getCode();switch(c){case-2:this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i,c=10;break;case-1:return this.text+=chunk.slice(start),!1}if(c===char)return this.text+=chunk.slice(start,this.prevI),!0}}captureNameChars(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCode();if(-1===c)return this.name+=chunk.slice(start),-1;if(!isNameChar(c))return this.name+=chunk.slice(start,this.prevI),-2===c?10:c}}skipSpaces(){for(;;){const c=this.getCodeNorm();if(-1===c||!isS(c))return c}}setXMLVersion(version){this.currentXMLVersion=version,"1.0"===version?(this.isChar=isChar10,this.getCode=this.getCode10):(this.isChar=isChar11,this.getCode=this.getCode11)}sBegin(){65279===this.chunk.charCodeAt(0)&&(this.i++,this.column++),this.state=1}sBeginWhitespace(){const iBefore=this.i,c=this.skipSpaces();switch(this.prevI!==iBefore&&(this.xmlDeclPossible=!1),c){case 60:if(this.state=15,0!==this.text.length)throw new Error("no-empty text at start");break;case-1:break;default:this.unget(),this.state=13,this.xmlDeclPossible=!1}}sDoctype(){var _a;const c=this.captureTo(DOCTYPE_TERMINATOR);switch(c){case 62:null===(_a=this.doctypeHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13,this.doctype=!0;break;case-1:break;default:this.text+=String.fromCodePoint(c),91===c?this.state=4:isQuote(c)&&(this.state=3,this.q=c)}}sDoctypeQuote(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.q=null,this.state=2)}sDTD(){const c=this.captureTo(DTD_TERMINATOR);-1!==c&&(this.text+=String.fromCodePoint(c),93===c?this.state=2:60===c?this.state=6:isQuote(c)&&(this.state=5,this.q=c))}sDTDQuoted(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.state=4,this.q=null)}sDTDOpenWaka(){const c=this.getCodeNorm();switch(this.text+=String.fromCodePoint(c),c){case 33:this.state=7,this.openWakaBang="";break;case 63:this.state=11;break;default:this.state=4}}sDTDOpenWakaBang(){const char=String.fromCodePoint(this.getCodeNorm()),owb=this.openWakaBang+=char;this.text+=char,"-"!==owb&&(this.state="--"===owb?8:4,this.openWakaBang="")}sDTDComment(){this.captureToChar(45)&&(this.text+="-",this.state=9)}sDTDCommentEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),this.state=45===c?10:8}sDTDCommentEnded(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c?this.state=4:(this.fail("malformed comment."),this.state=8)}sDTDPI(){this.captureToChar(63)&&(this.text+="?",this.state=12)}sDTDPIEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c&&(this.state=4)}sText(){0!==this.tags.length?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:start}=this;const{chunk:chunk}=this;loop:for(;;)switch(this.getCode()){case-2:this.entity+=`${chunk.slice(start,this.prevI)}\n`,start=this.i;break;case 59:{const{entityReturnState:entityReturnState}=this,entity=this.entity+chunk.slice(start,this.prevI);let parsed;this.state=entityReturnState,""===entity?(this.fail("empty entity name."),parsed="&;"):(parsed=this.parseEntity(entity),this.entity=""),13===entityReturnState&&void 0===this.textHandler||(this.text+=parsed);break loop}case-1:this.entity+=chunk.slice(start);break loop}}sOpenWaka(){const c=this.getCode();if(isNameStartChar(c))this.state=34,this.unget(),this.xmlDeclPossible=!1;else switch(c){case 47:this.state=43,this.xmlDeclPossible=!1;break;case 33:this.state=16,this.openWakaBang="",this.xmlDeclPossible=!1;break;case 63:this.state=23;break;default:this.fail("disallowed character in tag name"),this.state=13,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=20,this.openWakaBang="";break;case"--":this.state=17,this.openWakaBang="";break;case"DOCTYPE":this.state=2,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(45)&&(this.state=18)}sCommentEnding(){var _a;const c=this.getCodeNorm();45===c?(this.state=19,null===(_a=this.commentHandler)||void 0===_a||_a.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(c)}`,this.state=17)}sCommentEnded(){const c=this.getCodeNorm();62!==c?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(c)}`,this.state=17):this.state=13}sCData(){this.captureToChar(93)&&(this.state=21)}sCDataEnding(){const c=this.getCodeNorm();93===c?this.state=22:(this.text+=`]${String.fromCodePoint(c)}`,this.state=20)}sCDataEnding2(){var _a;const c=this.getCodeNorm();switch(c){case 62:null===(_a=this.cdataHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13;break;case 93:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(c)}`,this.state=20}}sPIFirstChar(){const c=this.getCodeNorm();this.nameStartCheck(c)?(this.piTarget+=String.fromCodePoint(c),this.state=24):63===c||isS(c)?(this.fail("processing instruction without a target."),this.state=63===c?26:25):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c),this.state=24)}sPIRest(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCodeNorm();if(-1===c)return void(this.piTarget+=chunk.slice(start));if(!this.nameCheck(c)){this.piTarget+=chunk.slice(start,this.prevI);const isQuestion=63===c;isQuestion||isS(c)?"xml"===this.piTarget?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=isQuestion?33:27):this.state=isQuestion?26:25:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c));break}}}sPIBody(){if(0===this.text.length){const c=this.getCodeNorm();63===c?this.state=26:isS(c)||(this.text=String.fromCodePoint(c))}else this.captureToChar(63)&&(this.state=26)}sPIEnding(){var _a;const c=this.getCodeNorm();if(62===c){const{piTarget:piTarget}=this;"xml"===piTarget.toLowerCase()&&this.fail("the XML declaration must appear at the start of the document."),null===(_a=this.piHandler)||void 0===_a||_a.call(this,{target:piTarget,body:this.text}),this.piTarget=this.text="",this.state=13}else 63===c?this.text+="?":(this.text+=`?${String.fromCodePoint(c)}`,this.state=25);this.xmlDeclPossible=!1}sXMLDeclNameStart(){const c=this.skipSpaces();63!==c?-1!==c&&(this.state=28,this.name=String.fromCodePoint(c)):this.state=33}sXMLDeclName(){const c=this.captureTo(XML_DECL_NAME_TERMINATOR);if(63===c)return this.state=33,this.name+=this.text,this.text="",void this.fail("XML declaration is incomplete.");if(isS(c)||61===c){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=61===c?30:29}}sXMLDeclEq(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(61!==c&&this.fail("value required."),this.state=30)}sXMLDeclValueStart(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(isQuote(c)?this.q=c:(this.fail("value must be quoted."),this.q=32),this.state=31)}sXMLDeclValue(){const c=this.captureTo([this.q,63]);if(63===c)return this.state=33,this.text="",void this.fail("XML declaration is incomplete.");if(-1===c)return;const value=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];const version=value;this.xmlDecl.version=version,/^1\.[0-9]+$/.test(version)?this.opt.forceXMLVersion||this.setXMLVersion(version):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=value;break;case"standalone":"yes"!==value&&"no"!==value&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=value}this.name="",this.state=32}sXMLDeclSeparator(){const c=this.getCodeNorm();63!==c?(isS(c)||(this.fail("whitespace required."),this.unget()),this.state=27):this.state=33}sXMLDeclEnding(){var _a;62===this.getCodeNorm()?("xml"!==this.piTarget?this.fail("processing instructions are not allowed before root."):"version"!==this.name&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),null===(_a=this.xmldeclHandler)||void 0===_a||_a.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=13):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var _a;const c=this.captureNameChars();if(-1===c)return;const tag=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=tag.ns=Object.create(null)),null===(_a=this.openTagStartHandler)||void 0===_a||_a.call(this,tag),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),c){case 62:this.openTag();break;case 47:this.state=35;break;default:isS(c)||this.fail("disallowed character in tag name."),this.state=36}}sOpenTagSlash(){62===this.getCode()?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=36)}sAttrib(){const c=this.skipSpaces();-1!==c&&(isNameStartChar(c)?(this.unget(),this.state=37):62===c?this.openTag():47===c?this.state=35:this.fail("disallowed character in attribute name."))}sAttribName(){const c=this.captureNameChars();61===c?this.state=39:isS(c)?this.state=38:62===c?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):-1!==c&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){const c=this.skipSpaces();switch(c){case-1:return;case 61:this.state=39;break;default:this.fail("attribute without value."),this.text="",this.name="",62===c?this.openTag():isNameStartChar(c)?(this.unget(),this.state=37):(this.fail("disallowed character in attribute name."),this.state=36)}}sAttribValue(){const c=this.getCodeNorm();isQuote(c)?(this.q=c,this.state=40):isS(c)||(this.fail("unquoted attribute value."),this.state=42,this.unget())}sAttribValueQuoted(){const{q:q,chunk:chunk}=this;let{i:start}=this;for(;;)switch(this.getCode()){case q:return this.pushAttrib(this.name,this.text+chunk.slice(start,this.prevI)),this.name=this.text="",this.q=null,void(this.state=41);case 38:return this.text+=chunk.slice(start,this.prevI),this.state=14,void(this.entityReturnState=40);case 10:case-2:case 9:this.text+=`${chunk.slice(start,this.prevI)} `,start=this.i;break;case 60:return this.text+=chunk.slice(start,this.prevI),void this.fail("disallowed character.");case-1:return void(this.text+=chunk.slice(start))}}sAttribValueClosed(){const c=this.getCodeNorm();isS(c)?this.state=36:62===c?this.openTag():47===c?this.state=35:isNameStartChar(c)?(this.fail("no whitespace between attributes."),this.unget(),this.state=37):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){const c=this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);switch(c){case 38:this.state=14,this.entityReturnState=42;break;case 60:this.fail("disallowed character.");break;case-1:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",62===c?this.openTag():this.state=36}}sCloseTag(){const c=this.captureNameChars();62===c?this.closeTag():isS(c)?this.state=44:-1!==c&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case 62:this.closeTag();break;case-1:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:start,forbiddenState:forbiddenState}=this;const{chunk:chunk,textHandler:handler}=this;scanLoop:for(;;)switch(this.getCode()){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}forbiddenState=0;break scanLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),forbiddenState=0;break scanLoop;case 93:switch(forbiddenState){case 0:forbiddenState=1;break;case 1:forbiddenState=2;break;case 2:break;default:throw new Error("impossible state")}break;case 62:2===forbiddenState&&this.fail('the string "]]>" is disallowed in char data.'),forbiddenState=0;break;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i,forbiddenState=0;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break scanLoop;default:forbiddenState=0}this.forbiddenState=forbiddenState}handleTextOutsideRoot(){let{i:start}=this;const{chunk:chunk,textHandler:handler}=this;let nonSpace=!1;outRootLoop:for(;;){const code=this.getCode();switch(code){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}break outRootLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),nonSpace=!0;break outRootLoop;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break outRootLoop;default:isS(code)||(nonSpace=!0)}}nonSpace&&(this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(name,value){var _a;const{prefix:prefix,local:local}=this.qname(name),attr={name:name,prefix:prefix,local:local,value:value};if(this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr),"xmlns"===prefix){const trimmed=value.trim();"1.0"===this.currentXMLVersion&&""===trimmed&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[local]=trimmed,nsPairCheck(this,local,trimmed)}else if("xmlns"===name){const trimmed=value.trim();this.topNS[""]=trimmed,nsPairCheck(this,"",trimmed)}}pushAttribPlain(name,value){var _a;const attr={name:name,value:value};this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr)}end(){var _a,_b;this.sawRoot||this.fail("document must contain a root element.");const{tags:tags}=this;for(;tags.length>0;){const tag=tags.pop();this.fail(`unclosed tag: ${tag.name}`)}0!==this.state&&13!==this.state&&this.fail("unexpected end.");const{text:text}=this;return 0!==text.length&&(null===(_a=this.textHandler)||void 0===_a||_a.call(this,text),this.text=""),this._closed=!0,null===(_b=this.endHandler)||void 0===_b||_b.call(this),this._init(),this}resolve(prefix){var _a,_b;let uri=this.topNS[prefix];if(void 0!==uri)return uri;const{tags:tags}=this;for(let index=tags.length-1;index>=0;index--)if(uri=tags[index].ns[prefix],void 0!==uri)return uri;return uri=this.ns[prefix],void 0!==uri?uri:null===(_b=(_a=this.opt).resolvePrefix)||void 0===_b?void 0:_b.call(_a,prefix)}qname(name){const colon=name.indexOf(":");if(-1===colon)return{prefix:"",local:name};const local=name.slice(colon+1),prefix=name.slice(0,colon);return(""===prefix||""===local||local.includes(":"))&&this.fail(`malformed name: ${name}.`),{prefix:prefix,local:local}}processAttribsNS(){var _a;const{attribList:attribList}=this,tag=this.tag;{const{prefix:prefix,local:local}=this.qname(tag.name);tag.prefix=prefix,tag.local=local;const uri=tag.uri=null!==(_a=this.resolve(prefix))&&void 0!==_a?_a:"";""!==prefix&&("xmlns"===prefix&&this.fail('tags may not have "xmlns" as prefix.'),""===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),tag.uri=prefix))}if(0===attribList.length)return;const{attributes:attributes}=tag,seen=new Set;for(const attr of attribList){const{name:name,prefix:prefix,local:local}=attr;let uri,eqname;""===prefix?(uri="xmlns"===name?XMLNS_NAMESPACE:"",eqname=name):(uri=this.resolve(prefix),void 0===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),uri=prefix),eqname=`{${uri}}${local}`),seen.has(eqname)&&this.fail(`duplicate attribute: ${eqname}.`),seen.add(eqname),attr.uri=uri,attributes[name]=attr}this.attribList=[]}processAttribsPlain(){const{attribList:attribList}=this,attributes=this.tag.attributes;for(const{name:name,value:value}of attribList)void 0!==attributes[name]&&this.fail(`duplicate attribute: ${name}.`),attributes[name]=value;this.attribList=[]}openTag(){var _a;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!1,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),tags.push(tag),this.state=13,this.name=""}openSelfClosingTag(){var _a,_b,_c;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!0,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),null===(_b=this.closeTagHandler)||void 0===_b||_b.call(this,tag),null===(this.tag=null!==(_c=tags[tags.length-1])&&void 0!==_c?_c:null)&&(this.closedRoot=!0),this.state=13,this.name=""}closeTag(){const{tags:tags,name:name}=this;if(this.state=13,this.name="",""===name)return this.fail("weird empty close tag."),void(this.text+="");const handler=this.closeTagHandler;let l=tags.length;for(;l-- >0;){const tag=this.tag=tags.pop();if(this.topNS=tag.ns,null==handler||handler(tag),tag.name===name)break;this.fail("unexpected close tag.")}0===l?this.closedRoot=!0:l<0&&(this.fail(`unmatched closing tag: ${name}.`),this.text+=``)}parseEntity(entity){if("#"!==entity[0]){const defined=this.ENTITIES[entity];return void 0!==defined?defined:(this.fail(this.isName(entity)?"undefined entity.":"disallowed character in entity name."),`&${entity};`)}let num=NaN;return"x"===entity[1]&&/^#x[0-9a-f]+$/i.test(entity)?num=parseInt(entity.slice(2),16):/^#[0-9]+$/.test(entity)&&(num=parseInt(entity.slice(1),10)),this.isChar(num)?String.fromCodePoint(num):(this.fail("malformed character entity."),`&${entity};`)}};const convertTransform=text=>{const values=text.split(/ +/).map((s=>parseFloat(s)));return index$c.fromValues(values[0],values[1],values[2],0,values[3],values[4],values[5],0,values[6],values[7],values[8],0,values[9],values[10],values[11],1)},parseModel$1=attributes=>{const obj={type:"model",unit:"millimeter"};return attributes.unit&&(obj.unit=attributes.unit),obj},parseMesh=attributes=>{const obj={type:"mesh",vertices:[],triangles:[],properties:[]};return obj},parseVertex=attributes=>{const obj={type:"vertex"};return obj.vertex=[parseFloat(attributes.x),parseFloat(attributes.y),parseFloat(attributes.z)],obj},parseTriangle=attributes=>{const obj={type:"triangle"};return obj.indices=[parseFloat(attributes.v1),parseFloat(attributes.v2),parseFloat(attributes.v3)],attributes.p1&&(obj.p1=parseFloat(attributes.p1)),attributes.p2&&(obj.p2=parseFloat(attributes.p2)),attributes.p3&&(obj.p3=parseFloat(attributes.p3)),attributes.pid&&(obj.pid=attributes.pid),obj},parseItem=attributes=>{const obj={type:"item",transform:index$c.create()};return obj.objectid=attributes.objectid,attributes.transform&&(obj.transform=convertTransform(attributes.transform)),obj},parseObject=attributes=>{const obj={type:"object",otype:"model"};return obj.id=attributes.id,attributes.type&&(obj.otype=attributes.type),attributes.partnumber&&(obj.partnumber=attributes.partnumber),attributes.name&&(obj.name=attributes.name),attributes.pid&&(obj.pid=attributes.pid),attributes.pindex&&(obj.pindex=parseFloat(attributes.pindex)),obj},parseComponents=attributes=>({type:"components"}),parseComponent=attributes=>{const obj={type:"component",transform:index$c.create()};return obj.objectid=attributes.objectid,attributes.transform&&(obj.transform=convertTransform(attributes.transform)),obj},parseBaseMaterials=attributes=>{const obj={type:"basematerials",bases:[]};return obj.id=attributes.id,obj},parseBase=attributes=>{const obj={type:"base"};obj.name=attributes.name;let color=hexToRgb(attributes.displaycolor);return 3===color.length&&(color=[color[0],color[1],color[2],1]),obj.displaycolor=color,obj},parseColorGroup=attributes=>{const obj={type:"colorgroup",colors:[]};return obj.id=attributes.id,obj},parseColor=attributes=>{const obj={type:"color"};let color=hexToRgb(attributes.color);return 3===color.length&&(color=[color[0],color[1],color[2],1]),obj.color=color,obj},parse=src=>{const items=[],materials=[],colorgroups=[],objects=[];return((src,storage)=>{const{items:items,materials:materials,colorgroups:colorgroups,objects:objects}=storage;let objLast=null;const parser=new saxes.SaxesParser;parser.on("error",(e=>{console.log(e)})),parser.on("opentag",(node=>{const objMap={MODEL:parseModel$1,ITEM:parseItem,OBJECT:parseObject,MESH:parseMesh,VERTEX:parseVertex,TRIANGLE:parseTriangle,COMPONENTS:parseComponents,COMPONENT:parseComponent,BASEMATERIALS:parseBaseMaterials,BASE:parseBase,MCOLORGROUP:parseColorGroup,MCOLOR:parseColor,undefined:()=>console.log(`WARNING: unsupported 3MF element: ${node.name}`)},elementName=node.name.toUpperCase().replace(":",""),obj=objMap[elementName]?objMap[elementName](node.attributes):null;let object=null,material=null,colorgroup=null;if(obj){switch(obj.type){case"model":break;case"item":items.push(obj);break;case"object":objects.push(obj);break;case"mesh":object=objects.at(-1),object.mesh=obj;break;case"vertex":object=objects.at(-1),object.mesh.vertices.push(obj.vertex);break;case"triangle":object=objects.at(-1),object.mesh.triangles.push(obj.indices),object.mesh.properties.push(((object,triangle)=>{const property={};return object.pid&&(property.pid=object.pid),triangle.pid&&(property.pid=triangle.pid),"p1"in triangle?property.pindex=triangle.p1:"pindex"in object&&(property.pindex=object.pindex),property})(object,obj));break;case"components":object=objects.at(-1),object.components=[];break;case"component":object=objects.at(-1),object.components.push(obj);break;case"basematerials":materials.push(obj);break;case"base":material=materials.at(-1),material.bases.push(obj);break;case"colorgroup":colorgroups.push(obj);break;case"color":colorgroup=colorgroups.at(-1),colorgroup.colors.push(obj);break;default:console.log("WARNING: unknown object type",obj.type)}objLast=obj}})),parser.on("closetag",(node=>{})),parser.on("text",(value=>{null!==value&&(value=value.trim()).length>0&&objLast&&(objLast.value=value,objLast=null)})),parser.on("end",(()=>{})),parser.write(src).close()})(src,{items:items,materials:materials,colorgroups:colorgroups,objects:objects}),{items:items,materials:materials,colorgroups:colorgroups,objects:objects}},parseModel=(options,source)=>{const{objects:objects,materials:materials,colorgroups:colorgroups,items:items}=parse(source);if(0===objects.length)throw new Error("3MF parsing failed, no valid 3MF objects retrieved");const buildItems=[];return items.forEach((item=>{const components=getComponents(item,objects);for(let i=0;i{const object=objects.find((obj=>obj.id===component.objectid)),components=[];if(object.mesh){const cmp={otype:object.otype,oid:object.id,transform:component.transform};object.name&&(cmp.oname=object.name),object.partnumber&&(cmp.opartnumber=object.partnumber),components.push(cmp)}return object.components&&object.components.forEach((c=>{getComponents(c,objects).forEach((s=>{index$c.multiply(s.transform,c.transform,s.transform),components.push(s)}))})),components},getDisplayColor$1=(property,materials,colorgroups)=>{if("pid"in property&&"pindex"in property){const material=materials.find((m=>property.pid===m.id));if(material)return material.bases[property.pindex].displaycolor;const colorgroup=colorgroups.find((g=>property.pid===g.id));if(colorgroup)return colorgroup.colors[property.pindex].color}return null},translateObject=(options,object,materials,colorgroups)=>{let code=`\n// Object ID: ${object.id}\n// Object Type: ${object.otype}`;if(object.name&&(code+=`\n// Object Name: ${object.name}`),object.mesh){let displaycolors="const displaycolors = null",shapecolor=((object,materials,colorgroups)=>{const displayColor=getDisplayColor$1(object,materials,colorgroups);return displayColor?`shape.color = [${displayColor}]`:""})(object,materials,colorgroups);const properties=((options,properties,materials,colorgroups)=>{const colors=[];for(let i=0;i {\n ${((options,vertices)=>{let code="const vertices = [\n";for(let i=0;i{let code="const triangles = [\n";for(let i=0;i{const{version:version,addMetaData:addMetaData,filename:filename}=options,translatedModels=models.map((source=>((options,source)=>{const{includedType:includedType}=options;let{buildItems:buildItems,objects:objects,materials:materials,colorgroups:colorgroups}=parseModel(0,source);"all"!==includedType&&(buildItems=buildItems.filter((item=>item.mesh.type===includedType)));const translatedObjects=objects.map(((object,index)=>translateObject(0,object,materials,colorgroups))),translatedItems=buildItems.map(((item,index)=>((options,item)=>{let code=`\n// Build Item ${item.sequence}\n// Object:\n// ID: ${item.oid}\n// Type: ${item.otype}`;return item.name&&(code+=`\n// Name: ${item.oname}`),code+=`\nconst createBuildItem${item.sequence} = () => {\n const object = objects["${item.oid}"]\n ${((options,transform)=>`const transform = [${transform}]`)(0,item.transform)}\n return transform(transform, object)\n}\n\nbuilditems.push(createBuildItem${item.sequence}())\n`,code})(0,item)));return translatedObjects.join("")+translatedItems.join("")})(options,source))),metacode=addMetaData?`\n//\n// Produced by JSCAD IO Library : 3MF Deserializer\n// Version: ${version}\n// Date: ${new Date}\n// Source: ${filename}\n//\n`:"";let bodycode="";for(let i=0;i {\n return builditems\n}\n"},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),getDisplayColor=(property,materials,colorgroups)=>{if("pid"in property&&"pindex"in property){const material=materials.find((m=>property.pid===m.id));if(material)return material.bases[property.pindex].displaycolor;const colorgroup=colorgroups.find((g=>property.pid===g.id));if(colorgroup)return colorgroup.colors[property.pindex].color}return null},instantiateObject=(options,object,materials,colorgroups)=>{if(object.mesh){const mesh=object.mesh,displaycolors=((options,properties,materials,colorgroups)=>{const displaycolors=[];for(let i=0;i{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({points:mesh.vertices,faces:mesh.triangles,colors:displaycolors});shape.id=object.id,shape.type=object.otype,object.name&&(shape.name=object.name);const displayColor=getDisplayColor(object,materials,colorgroups);return!displaycolors&&displayColor&&(shape.color=displayColor),shape}return index$6.create()},instantiateModels=(options,models)=>{const shapeLists=models.map((model=>((options,model)=>{const{includedType:includedType}=options;let{buildItems:buildItems,objects:objects,materials:materials,colorgroups:colorgroups}=parseModel(0,model);"all"!==includedType&&(buildItems=buildItems.filter((item=>item.mesh.type===includedType)));const instantiatedObjects={};return objects.forEach((object=>{const instantiatedObject=instantiateObject(0,object,materials,colorgroups);instantiatedObjects[object.id]=instantiatedObject})),buildItems.map((item=>{const object=instantiatedObjects[item.oid];return transform(item.transform,object)}))})(options,model)));return flatten(shapeLists)};exports.deserialize=(options,input)=>{const defaults={output:"script",version:"3.0.1-alpha.0",addMetaData:!0,includedItems:"build",includedType:"all"};options=Object.assign({},defaults,options);let models=[];try{const decompressed=function(data,opts){for(var files={},e=data.length-22;101010256!=b4(data,e);--e)(!e||data.length-e>65558)&&err(13);var c=b2(data,e+8);if(!c)return{};var o=b4(data,e+16),z=4294967295==o;z&&(e=b4(data,e-12),101075792!=b4(data,e)&&err(13),c=b4(data,e+32),o=b4(data,e+48));for(var fltr=opts&&opts.filter,i=0;i{if(key.endsWith("3dmodel.model")){const contents=strFromU8(decompressed[key]);models.push(contents)}}))}catch(e){models=[input]}return"script"===options.output?translateModels(options,models):instantiateModels(options,models)},exports.mimeType="model/3mf",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscad3MFDeserializer={}); diff --git a/packages/io/3mf-deserializer/package.json b/packages/io/3mf-deserializer/package.json index 6afde4c72..772183e1f 100644 --- a/packages/io/3mf-deserializer/package.json +++ b/packages/io/3mf-deserializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/3mf-deserializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "3MF Deserializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org/", @@ -32,8 +32,8 @@ "access": "public" }, "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0", + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", "fflate": "^0.7.3", "saxes": "^6.0.0" }, diff --git a/packages/io/3mf-serializer/CHANGELOG.md b/packages/io/3mf-serializer/CHANGELOG.md index 1ed12e719..5a78e2d4d 100644 --- a/packages/io/3mf-serializer/CHANGELOG.md +++ b/packages/io/3mf-serializer/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/3mf-serializer@2.1.6...@jscad/3mf-serializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/3mf-serializer@2.1.6...@jscad/3mf-serializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/3mf-serializer/dist/jscad-3mf-serializer.es.js b/packages/io/3mf-serializer/dist/jscad-3mf-serializer.es.js index da603e4fa..d00896cb8 100644 --- a/packages/io/3mf-serializer/dist/jscad-3mf-serializer.es.js +++ b/packages/io/3mf-serializer/dist/jscad-3mf-serializer.es.js @@ -1,7 +1,7 @@ /** * 3MF serializer for JSCAD project * @module @jscad/3mf-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -var u8=Uint8Array,u16=Uint16Array,u32=Uint32Array,fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb=function(eb,start){for(var b=new u16(31),i=0;i<31;++i)b[i]=start+=1<>>1|(21845&i)<<1;x=(61680&(x=(52428&x)>>>2|(13107&x)<<2))>>>4|(3855&x)<<4,rev[i]=((65280&x)>>>8|(255&x)<<8)>>>1}var hMap=function(cd,mb,r){for(var s=cd.length,i=0,l=new u16(mb);i>>rvb]=sv}else for(co=new u16(s),i=0;i>>15-cd[i]);return co},flt=new u8(288);for(i=0;i<144;++i)flt[i]=8;for(i=144;i<256;++i)flt[i]=9;for(i=256;i<280;++i)flt[i]=7;for(i=280;i<288;++i)flt[i]=8;var fdt=new u8(32);for(i=0;i<32;++i)fdt[i]=5;var flm=hMap(flt,9,0),fdm=hMap(fdt,5,0),shft=function(p){return(p+7)/8|0},slc=function(v,s,e){(null==s||s<0)&&(s=0),(null==e||e>v.length)&&(e=v.length);var n=new(2==v.BYTES_PER_ELEMENT?u16:4==v.BYTES_PER_ELEMENT?u32:u8)(e-s);return n.set(v.subarray(s,e)),n},ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);if(e.code=ind,Error.captureStackTrace&&Error.captureStackTrace(e,err),!nt)throw e;return e},wbits=function(d,p,v){v<<=7&p;var o=p/8|0;d[o]|=v,d[o+1]|=v>>>8},wbits16=function(d,p,v){v<<=7&p;var o=p/8|0;d[o]|=v,d[o+1]|=v>>>8,d[o+2]|=v>>>16},hTree=function(d,mb){for(var t=[],i=0;imaxSym&&(maxSym=t2[i].s);var tr=new u16(maxSym+1),mbt=ln(t[i1-1],tr,0);if(mbt>mb){i=0;var dt=0,lft=mbt-mb,cst=1<mb))break;dt+=cst-(1<>>=lft;dt>0;){var i2_2=t2[i].s;tr[i2_2]=0&&dt;--i){var i2_3=t2[i].s;tr[i2_3]==mb&&(--tr[i2_3],++dt)}mbt=mb}return[new u8(tr),mbt]},ln=function(n,l,d){return-1==n.s?Math.max(ln(n.l,l,d+1),ln(n.r,l,d+1)):l[n.s]=d},lc=function(c){for(var s=c.length;s&&!c[--s];);for(var cl=new u16(++s),cli=0,cln=c[0],cls=1,w=function(v){cl[cli++]=v},i=1;i<=s;++i)if(c[i]==cln&&i!=s)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w(32754);cls>2&&(w(cls>10?cls-11<<5|28690:cls-3<<5|12305),cls=0)}else if(cls>3){for(w(cln),--cls;cls>6;cls-=6)w(8304);cls>2&&(w(cls-3<<5|8208),cls=0)}for(;cls--;)w(cln);cls=1,cln=c[i]}return[cl.subarray(0,cli),s]},clen=function(cf,cl){for(var l=0,i=0;i>>8,out[o+2]=255^out[o],out[o+3]=255^out[o+1];for(var i=0;i4&&!lct[clim[nlcc-1]];--nlcc);var lm,ll,dm,dl,flen=bl+5<<3,ftlen=clen(lf,flt)+clen(df,fdt)+eb,dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+(2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18]);if(flen<=ftlen&&flen<=dtlen)return wfblk(out,p,dat.subarray(bs,bs+bl));if(wbits(out,p,1+(dtlen15&&(wbits(out,p,clct[i]>>>5&127),p+=clct[i]>>>12)}}}else lm=flm,ll=flt,dm=fdm,dl=fdt;for(i=0;i255){len=syms[i]>>>18&31;wbits16(out,p,lm[len+257]),p+=ll[len+257],len>7&&(wbits(out,p,syms[i]>>>23&31),p+=fleb[len]);var dst=31&syms[i];wbits16(out,p,dm[dst]),p+=dl[dst],dst>3&&(wbits16(out,p,syms[i]>>>5&8191),p+=fdeb[dst])}else wbits16(out,p,lm[syms[i]]),p+=ll[syms[i]];return wbits16(out,p,lm[256]),p+ll[256]},deo=new u32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),et=new u8(0),crct=function(){for(var t=new Int32Array(256),i=0;i<256;++i){for(var c=i,k=9;--k;)c=(1&c&&-306674912)^c>>>1;t[i]=c}return t}(),crc=function(){var c=-1;return{p:function(d){for(var cr=c,i=0;i>>8;c=cr},d:function(){return~c}}},dopt=function(dat,opt,pre,post,st){return function(dat,lvl,plvl,pre,post,lst){var s=dat.length,o=new u8(pre+s+5*(1+Math.ceil(s/7e3))+post),w=o.subarray(pre,o.length-post),pos=0;if(!lvl||s<8)for(var i=0;i<=s;i+=65535){var e=i+65535;e>=s&&(w[pos>>3]=lst),pos=wfblk(w,pos+1,dat.subarray(i,e))}else{for(var opt=deo[lvl-1],n=opt>>>13,c=8191&opt,msk_1=(1<7e3||li>24576)&&rem>423){pos=wblk(dat,w,0,syms,lf,df,eb,li,bs,i-bs,pos),li=lc_1=eb=0,bs=i;for(var j=0;j<286;++j)lf[j]=0;for(j=0;j<30;++j)df[j]=0}var l=2,d=0,ch_1=c,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i-dif))for(var maxn=Math.min(n,rem)-1,maxd=Math.min(32767,i),ml=Math.min(258,rem);dif<=maxd&&--ch_1&&imod!=pimod;){if(dat[i+l]==dat[i+l-dif]){for(var nl=0;nll){if(l=nl,d=dif,nl>maxn)break;var mmd=Math.min(dif,nl-2),md=0;for(j=0;jmd&&(md=cd,pimod=ti)}}}dif+=(imod=pimod)-(pimod=prev[imod])+32768&32767}if(d){syms[li++]=268435456|revfl[l]<<18|revfd[d];var lin=31&revfl[l],din=31&revfd[d];eb+=fleb[lin]+fdeb[din],++lf[257+lin],++df[din],wi=i+l,++lc_1}else syms[li++]=dat[i],++lf[dat[i]]}}pos=wblk(dat,w,lst,syms,lf,df,eb,li,bs,i-bs,pos),!lst&&7&pos&&(pos=wfblk(w,pos+1,et))}return slc(o,0,pre+shft(pos)+post)}(dat,null==opt.level?6:opt.level,null==opt.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(dat.length)))):12+opt.mem,pre,post,!st)},mrg=function(a,b){var o={};for(var k in a)o[k]=a[k];for(var k in b)o[k]=b[k];return o},wbytes=function(d,b,v){for(;v;++b)d[b]=v,v>>>=8};function deflateSync(data,opts){return dopt(data,opts||{},0,0)}var fltn=function(d,p,t,o){for(var k in d){var val=d[k],n=p+k,op=o;Array.isArray(val)&&(op=mrg(o,val[1]),val=val[0]),val instanceof u8?t[n]=[val,op]:(t[n+="/"]=[new u8(0),op],fltn(val,n,t,o))}},te="undefined"!=typeof TextEncoder&&new TextEncoder,td="undefined"!=typeof TextDecoder&&new TextDecoder;try{td.decode(et,{stream:!0}),1}catch(e){}function strToU8(str,latin1){if(latin1){for(var ar_1=new u8(str.length),i=0;i>1)),ai=0,w=function(v){ar[ai++]=v};for(i=0;iar.length){var n=new u8(ai+8+(l-i<<1));n.set(ar),ar=n}var c=str.charCodeAt(i);c<128||latin1?w(c):c<2048?(w(192|c>>6),w(128|63&c)):c>55295&&c<57344?(w(240|(c=65536+(1047552&c)|1023&str.charCodeAt(++i))>>18),w(128|c>>12&63),w(128|c>>6&63),w(128|63&c)):(w(224|c>>12),w(128|c>>6&63),w(128|63&c))}return slc(ar,0,ai)}var exfl=function(ex){var le=0;if(ex)for(var k in ex){var l=ex[k].length;l>65535&&err(9),le+=l+4}return le},wzh=function(d,b,f,fn,u,c,ce,co){var fl=fn.length,ex=f.extra,col=co&&co.length,exl=exfl(ex);wbytes(d,b,null!=ce?33639248:67324752),b+=4,null!=ce&&(d[b++]=20,d[b++]=f.os),d[b]=20,b+=2,d[b++]=f.flag<<1|(null==c&&8),d[b++]=u&&8,d[b++]=255&f.compression,d[b++]=f.compression>>8;var dt=new Date(null==f.mtime?Date.now():f.mtime),y=dt.getFullYear()-1980;if((y<0||y>119)&&err(10),wbytes(d,b,y<<25|dt.getMonth()+1<<21|dt.getDate()<<16|dt.getHours()<<11|dt.getMinutes()<<5|dt.getSeconds()>>>1),b+=4,null!=c&&(wbytes(d,b,f.crc),wbytes(d,b+4,c),wbytes(d,b+8,f.size)),wbytes(d,b+12,fl),wbytes(d,b+14,exl),b+=16,null!=ce&&(wbytes(d,b,col),wbytes(d,b+6,f.attrs),wbytes(d,b+10,ce),b+=14),d.set(fn,b),b+=fl,exl)for(var k in ex){var exf=ex[k],l=exf.length;wbytes(d,b,+k),wbytes(d,b+2,l),d.set(exf,b+4),b+=4+l}return col&&(d.set(co,b),b+=col),b};function zipSync(data,opts){opts||(opts={});var r={},files=[];fltn(data,"",r,opts);var o=0,tot=0;for(var fn in r){var _a=r[fn],file=_a[0],p=_a[1],compression=0==p.level?0:8,s=(f=strToU8(fn)).length,com=p.comment,m=com&&strToU8(com),ms=m&&m.length,exl=exfl(p.extra);s>65535&&err(11);var d=compression?deflateSync(file,p):file,l=d.length,c=crc();c.p(file),files.push(mrg(p,{size:file.length,crc:c.d(),c:d,f:f,m:m,u:s!=fn.length||m&&com.length!=ms,o:o,compression:compression})),o+=30+s+exl+l,tot+=76+2*(s+exl)+(ms||0)+l}for(var out=new u8(tot+22),oe=o,cdl=tot-o,i=0;i{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;const isEmpty=a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}));return isEmpty?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const rgbToHex=(...values)=>{if((values=flatten$1(values)).length<3)throw new Error("values must contain R, G and B values");const r=255*values[0],g=255*values[1],b=255*values[2];let s=`#${Number(16777216+65536*r+256*g+b).toString(16).substring(1,7)}`;return values.length>3&&(s+=Number(255*values[3]).toString(16)),s},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),mimeType="model/3mf",serialize=(options,...objects)=>{options=Object.assign({},{unit:"millimeter",metadata:!0,defaultcolor:[1,160/255,0,1],compress:!0},options);const objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to 3MF");var array;objects.length!==objects3d.length&&console.warn("some objects could not be serialized to 3MF"),array=((options,...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results})({snap:!0,triangulate:!0},objects3d),objects=Array.isArray(array)?array:null==array?[]:[array];const body=["model",{unit:options.unit,"xml:lang":"und"},["metadata",{name:"Application"},"JSCAD"]];options.metadata&&body.push(["metadata",{name:"CreationDate"},(new Date).toISOString()]),body.push(translateResources(objects,options)),body.push(translateBuild(objects));const xml=`\n${stringify(body,2)}`;if(options.compress){return[zipSync({"3D":{"3dmodel.model":strToU8(xml)},_rels:{".rels":strToU8(rels)},"[Content_Types].xml":strToU8(contenttype)},{comment:"created by JSCAD"}).buffer]}return[xml]},contenttype='\n\n \n \n \n \n',rels='\n\n \n \n',translateResources=(objects,options)=>{let resources=["resources",{},translateMaterials(objects,options)];return resources=resources.concat(translateObjects(objects,options)),resources},translateMaterials=(objects,options)=>{let basematerials=["basematerials",{id:"0"}];const materials=[];return objects.forEach(((object,i)=>{let srgb=rgbToHex(options.defaultcolor).toUpperCase();object.color&&(srgb=rgbToHex(object.color).toUpperCase()),materials.push(["base",{name:`mat${i}`,displaycolor:srgb}])})),basematerials=basematerials.concat(materials),basematerials},translateObjects=(objects,options)=>{const contents=[];return objects.forEach(((object,i)=>{if(index$6.isA(object)){index$6.toPolygons(object).length>0&&(options.id=i,contents.push(convertToObject(object,options)))}})),contents},translateBuild=(objects,options)=>{let build=["build",{}];const items=[];return objects.forEach(((object,i)=>{items.push(["item",{objectid:`${i+1}`}])})),build=build.concat(items),build},convertToObject=(object,options)=>{const name=object.name?object.name:`Part ${options.id}`;return["object",{id:`${options.id+1}`,type:"model",pid:"0",pindex:`${options.id}`,name:name},convertToMesh(object)]},convertToMesh=(object,options)=>["mesh",{},convertToVertices(object),convertToVolumes(object)],convertToVertices=(object,options)=>{const vertices=[];return index$6.toPolygons(object).forEach((polygon=>{for(let i=0;i["vertex",{x:vertex[0],y:vertex[1],z:vertex[2]}],convertToVolumes=(object,options)=>{let n=0;const polygons=index$6.toPolygons(object);let contents=["triangles",{}];return polygons.forEach((polygon=>{if(polygon.vertices.length<3)return;const triangles=convertToTriangles(polygon,n);contents=contents.concat(triangles),n+=polygon.vertices.length})),contents},convertToTriangles=(polygon,index)=>{const contents=[];for(let i=0;i>>1|(21845&i)<<1;x=(61680&(x=(52428&x)>>>2|(13107&x)<<2))>>>4|(3855&x)<<4,rev[i]=((65280&x)>>>8|(255&x)<<8)>>>1}var hMap=function(cd,mb,r){for(var s=cd.length,i=0,l=new u16(mb);i>>rvb]=sv}else for(co=new u16(s),i=0;i>>15-cd[i]);return co},flt=new u8(288);for(i=0;i<144;++i)flt[i]=8;for(i=144;i<256;++i)flt[i]=9;for(i=256;i<280;++i)flt[i]=7;for(i=280;i<288;++i)flt[i]=8;var fdt=new u8(32);for(i=0;i<32;++i)fdt[i]=5;var flm=hMap(flt,9,0),fdm=hMap(fdt,5,0),shft=function(p){return(p+7)/8|0},slc=function(v,s,e){(null==s||s<0)&&(s=0),(null==e||e>v.length)&&(e=v.length);var n=new(2==v.BYTES_PER_ELEMENT?u16:4==v.BYTES_PER_ELEMENT?u32:u8)(e-s);return n.set(v.subarray(s,e)),n},ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);if(e.code=ind,Error.captureStackTrace&&Error.captureStackTrace(e,err),!nt)throw e;return e},wbits=function(d,p,v){v<<=7&p;var o=p/8|0;d[o]|=v,d[o+1]|=v>>>8},wbits16=function(d,p,v){v<<=7&p;var o=p/8|0;d[o]|=v,d[o+1]|=v>>>8,d[o+2]|=v>>>16},hTree=function(d,mb){for(var t=[],i=0;imaxSym&&(maxSym=t2[i].s);var tr=new u16(maxSym+1),mbt=ln(t[i1-1],tr,0);if(mbt>mb){i=0;var dt=0,lft=mbt-mb,cst=1<mb))break;dt+=cst-(1<>>=lft;dt>0;){var i2_2=t2[i].s;tr[i2_2]=0&&dt;--i){var i2_3=t2[i].s;tr[i2_3]==mb&&(--tr[i2_3],++dt)}mbt=mb}return[new u8(tr),mbt]},ln=function(n,l,d){return-1==n.s?Math.max(ln(n.l,l,d+1),ln(n.r,l,d+1)):l[n.s]=d},lc=function(c){for(var s=c.length;s&&!c[--s];);for(var cl=new u16(++s),cli=0,cln=c[0],cls=1,w=function(v){cl[cli++]=v},i=1;i<=s;++i)if(c[i]==cln&&i!=s)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w(32754);cls>2&&(w(cls>10?cls-11<<5|28690:cls-3<<5|12305),cls=0)}else if(cls>3){for(w(cln),--cls;cls>6;cls-=6)w(8304);cls>2&&(w(cls-3<<5|8208),cls=0)}for(;cls--;)w(cln);cls=1,cln=c[i]}return[cl.subarray(0,cli),s]},clen=function(cf,cl){for(var l=0,i=0;i>>8,out[o+2]=255^out[o],out[o+3]=255^out[o+1];for(var i=0;i4&&!lct[clim[nlcc-1]];--nlcc);var lm,ll,dm,dl,flen=bl+5<<3,ftlen=clen(lf,flt)+clen(df,fdt)+eb,dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+(2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18]);if(flen<=ftlen&&flen<=dtlen)return wfblk(out,p,dat.subarray(bs,bs+bl));if(wbits(out,p,1+(dtlen15&&(wbits(out,p,clct[i]>>>5&127),p+=clct[i]>>>12)}}}else lm=flm,ll=flt,dm=fdm,dl=fdt;for(i=0;i255){len=syms[i]>>>18&31;wbits16(out,p,lm[len+257]),p+=ll[len+257],len>7&&(wbits(out,p,syms[i]>>>23&31),p+=fleb[len]);var dst=31&syms[i];wbits16(out,p,dm[dst]),p+=dl[dst],dst>3&&(wbits16(out,p,syms[i]>>>5&8191),p+=fdeb[dst])}else wbits16(out,p,lm[syms[i]]),p+=ll[syms[i]];return wbits16(out,p,lm[256]),p+ll[256]},deo=new u32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),et=new u8(0),crct=function(){for(var t=new Int32Array(256),i=0;i<256;++i){for(var c=i,k=9;--k;)c=(1&c&&-306674912)^c>>>1;t[i]=c}return t}(),crc=function(){var c=-1;return{p:function(d){for(var cr=c,i=0;i>>8;c=cr},d:function(){return~c}}},dopt=function(dat,opt,pre,post,st){return function(dat,lvl,plvl,pre,post,lst){var s=dat.length,o=new u8(pre+s+5*(1+Math.ceil(s/7e3))+post),w=o.subarray(pre,o.length-post),pos=0;if(!lvl||s<8)for(var i=0;i<=s;i+=65535){var e=i+65535;e>=s&&(w[pos>>3]=lst),pos=wfblk(w,pos+1,dat.subarray(i,e))}else{for(var opt=deo[lvl-1],n=opt>>>13,c=8191&opt,msk_1=(1<7e3||li>24576)&&rem>423){pos=wblk(dat,w,0,syms,lf,df,eb,li,bs,i-bs,pos),li=lc_1=eb=0,bs=i;for(var j=0;j<286;++j)lf[j]=0;for(j=0;j<30;++j)df[j]=0}var l=2,d=0,ch_1=c,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i-dif))for(var maxn=Math.min(n,rem)-1,maxd=Math.min(32767,i),ml=Math.min(258,rem);dif<=maxd&&--ch_1&&imod!=pimod;){if(dat[i+l]==dat[i+l-dif]){for(var nl=0;nll){if(l=nl,d=dif,nl>maxn)break;var mmd=Math.min(dif,nl-2),md=0;for(j=0;jmd&&(md=cd,pimod=ti)}}}dif+=(imod=pimod)-(pimod=prev[imod])+32768&32767}if(d){syms[li++]=268435456|revfl[l]<<18|revfd[d];var lin=31&revfl[l],din=31&revfd[d];eb+=fleb[lin]+fdeb[din],++lf[257+lin],++df[din],wi=i+l,++lc_1}else syms[li++]=dat[i],++lf[dat[i]]}}pos=wblk(dat,w,lst,syms,lf,df,eb,li,bs,i-bs,pos),!lst&&7&pos&&(pos=wfblk(w,pos+1,et))}return slc(o,0,pre+shft(pos)+post)}(dat,null==opt.level?6:opt.level,null==opt.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(dat.length)))):12+opt.mem,pre,post,!st)},mrg=function(a,b){var o={};for(var k in a)o[k]=a[k];for(var k in b)o[k]=b[k];return o},wbytes=function(d,b,v){for(;v;++b)d[b]=v,v>>>=8};function deflateSync(data,opts){return dopt(data,opts||{},0,0)}var fltn=function(d,p,t,o){for(var k in d){var val=d[k],n=p+k,op=o;Array.isArray(val)&&(op=mrg(o,val[1]),val=val[0]),val instanceof u8?t[n]=[val,op]:(t[n+="/"]=[new u8(0),op],fltn(val,n,t,o))}},te="undefined"!=typeof TextEncoder&&new TextEncoder,td="undefined"!=typeof TextDecoder&&new TextDecoder;try{td.decode(et,{stream:!0}),1}catch(e){}function strToU8(str,latin1){if(latin1){for(var ar_1=new u8(str.length),i=0;i>1)),ai=0,w=function(v){ar[ai++]=v};for(i=0;iar.length){var n=new u8(ai+8+(l-i<<1));n.set(ar),ar=n}var c=str.charCodeAt(i);c<128||latin1?w(c):c<2048?(w(192|c>>6),w(128|63&c)):c>55295&&c<57344?(w(240|(c=65536+(1047552&c)|1023&str.charCodeAt(++i))>>18),w(128|c>>12&63),w(128|c>>6&63),w(128|63&c)):(w(224|c>>12),w(128|c>>6&63),w(128|63&c))}return slc(ar,0,ai)}var exfl=function(ex){var le=0;if(ex)for(var k in ex){var l=ex[k].length;l>65535&&err(9),le+=l+4}return le},wzh=function(d,b,f,fn,u,c,ce,co){var fl=fn.length,ex=f.extra,col=co&&co.length,exl=exfl(ex);wbytes(d,b,null!=ce?33639248:67324752),b+=4,null!=ce&&(d[b++]=20,d[b++]=f.os),d[b]=20,b+=2,d[b++]=f.flag<<1|(null==c&&8),d[b++]=u&&8,d[b++]=255&f.compression,d[b++]=f.compression>>8;var dt=new Date(null==f.mtime?Date.now():f.mtime),y=dt.getFullYear()-1980;if((y<0||y>119)&&err(10),wbytes(d,b,y<<25|dt.getMonth()+1<<21|dt.getDate()<<16|dt.getHours()<<11|dt.getMinutes()<<5|dt.getSeconds()>>>1),b+=4,null!=c&&(wbytes(d,b,f.crc),wbytes(d,b+4,c),wbytes(d,b+8,f.size)),wbytes(d,b+12,fl),wbytes(d,b+14,exl),b+=16,null!=ce&&(wbytes(d,b,col),wbytes(d,b+6,f.attrs),wbytes(d,b+10,ce),b+=14),d.set(fn,b),b+=fl,exl)for(var k in ex){var exf=ex[k],l=exf.length;wbytes(d,b,+k),wbytes(d,b+2,l),d.set(exf,b+4),b+=4+l}return col&&(d.set(co,b),b+=col),b};function zipSync(data,opts){opts||(opts={});var r={},files=[];fltn(data,"",r,opts);var o=0,tot=0;for(var fn in r){var _a=r[fn],file=_a[0],p=_a[1],compression=0==p.level?0:8,s=(f=strToU8(fn)).length,com=p.comment,m=com&&strToU8(com),ms=m&&m.length,exl=exfl(p.extra);s>65535&&err(11);var d=compression?deflateSync(file,p):file,l=d.length,c=crc();c.p(file),files.push(mrg(p,{size:file.length,crc:c.d(),c:d,f:f,m:m,u:s!=fn.length||m&&com.length!=ms,o:o,compression:compression})),o+=30+s+exl+l,tot+=76+2*(s+exl)+(ms||0)+l}for(var out=new u8(tot+22),oe=o,cdl=tot-o,i=0;i{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;const isEmpty=a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}));return isEmpty?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),rgbToHex=(...values)=>{if((values=flatten$1(values)).length<3)throw new Error("values must contain R, G and B values");const r=255*values[0],g=255*values[1],b=255*values[2];let s=`#${Number(16777216+65536*r+256*g+b).toString(16).substring(1,7)}`;return values.length>3&&(s+=Number(255*values[3]).toString(16)),s},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),mimeType="model/3mf",serialize=(options,...objects)=>{options=Object.assign({},{unit:"millimeter",metadata:!0,defaultcolor:[1,160/255,0,1],compress:!0},options);const objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to 3MF");var array;objects.length!==objects3d.length&&console.warn("some objects could not be serialized to 3MF"),array=generalize({snap:!0,triangulate:!0},objects3d),objects=Array.isArray(array)?array:null==array?[]:[array];const body=["model",{unit:options.unit,"xml:lang":"und"},["metadata",{name:"Application"},"JSCAD"]];options.metadata&&body.push(["metadata",{name:"CreationDate"},(new Date).toISOString()]),body.push(translateResources(objects,options)),body.push(translateBuild(objects));const xml=`\n${stringify(body,2)}`;if(options.compress){return[zipSync({"3D":{"3dmodel.model":strToU8(xml)},_rels:{".rels":strToU8(rels)},"[Content_Types].xml":strToU8(contenttype)},{comment:"created by JSCAD"}).buffer]}return[xml]},contenttype='\n\n \n \n \n \n',rels='\n\n \n \n',translateResources=(objects,options)=>{let resources=["resources",{},translateMaterials(objects,options)];return resources=resources.concat(translateObjects(objects,options)),resources},translateMaterials=(objects,options)=>{let basematerials=["basematerials",{id:"0"}];const materials=[];return objects.forEach(((object,i)=>{let srgb=rgbToHex(options.defaultcolor).toUpperCase();object.color&&(srgb=rgbToHex(object.color).toUpperCase()),materials.push(["base",{name:`mat${i}`,displaycolor:srgb}])})),basematerials=basematerials.concat(materials),basematerials},translateObjects=(objects,options)=>{const contents=[];return objects.forEach(((object,i)=>{if(index$6.isA(object)){index$6.toPolygons(object).length>0&&(options.id=i,contents.push(convertToObject(object,options)))}})),contents},translateBuild=(objects,options)=>{let build=["build",{}];const items=[];return objects.forEach(((object,i)=>{items.push(["item",{objectid:`${i+1}`}])})),build=build.concat(items),build},convertToObject=(object,options)=>{const name=object.name?object.name:`Part ${options.id}`;return["object",{id:`${options.id+1}`,type:"model",pid:"0",pindex:`${options.id}`,name:name},convertToMesh(object)]},convertToMesh=(object,options)=>["mesh",{},convertToVertices(object),convertToVolumes(object)],convertToVertices=(object,options)=>{const vertices=[];return index$6.toPolygons(object).forEach((polygon=>{for(let i=0;i["vertex",{x:vertex[0],y:vertex[1],z:vertex[2]}],convertToVolumes=(object,options)=>{let n=0;const polygons=index$6.toPolygons(object);let contents=["triangles",{}];return polygons.forEach((polygon=>{if(polygon.vertices.length<3)return;const triangles=convertToTriangles(polygon,n);contents=contents.concat(triangles),n+=polygon.vertices.length})),contents},convertToTriangles=(polygon,index)=>{const contents=[];for(let i=0;i>>1|(21845&i)<<1;x=(61680&(x=(52428&x)>>>2|(13107&x)<<2))>>>4|(3855&x)<<4,rev[i]=((65280&x)>>>8|(255&x)<<8)>>>1}var hMap=function(cd,mb,r){for(var s=cd.length,i=0,l=new u16(mb);i>>rvb]=sv}else for(co=new u16(s),i=0;i>>15-cd[i]);return co},flt=new u8(288);for(i=0;i<144;++i)flt[i]=8;for(i=144;i<256;++i)flt[i]=9;for(i=256;i<280;++i)flt[i]=7;for(i=280;i<288;++i)flt[i]=8;var fdt=new u8(32);for(i=0;i<32;++i)fdt[i]=5;var flm=hMap(flt,9,0),fdm=hMap(fdt,5,0),shft=function(p){return(p+7)/8|0},slc=function(v,s,e){(null==s||s<0)&&(s=0),(null==e||e>v.length)&&(e=v.length);var n=new(2==v.BYTES_PER_ELEMENT?u16:4==v.BYTES_PER_ELEMENT?u32:u8)(e-s);return n.set(v.subarray(s,e)),n},ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);if(e.code=ind,Error.captureStackTrace&&Error.captureStackTrace(e,err),!nt)throw e;return e},wbits=function(d,p,v){v<<=7&p;var o=p/8|0;d[o]|=v,d[o+1]|=v>>>8},wbits16=function(d,p,v){v<<=7&p;var o=p/8|0;d[o]|=v,d[o+1]|=v>>>8,d[o+2]|=v>>>16},hTree=function(d,mb){for(var t=[],i=0;imaxSym&&(maxSym=t2[i].s);var tr=new u16(maxSym+1),mbt=ln(t[i1-1],tr,0);if(mbt>mb){i=0;var dt=0,lft=mbt-mb,cst=1<mb))break;dt+=cst-(1<>>=lft;dt>0;){var i2_2=t2[i].s;tr[i2_2]=0&&dt;--i){var i2_3=t2[i].s;tr[i2_3]==mb&&(--tr[i2_3],++dt)}mbt=mb}return[new u8(tr),mbt]},ln=function(n,l,d){return-1==n.s?Math.max(ln(n.l,l,d+1),ln(n.r,l,d+1)):l[n.s]=d},lc=function(c){for(var s=c.length;s&&!c[--s];);for(var cl=new u16(++s),cli=0,cln=c[0],cls=1,w=function(v){cl[cli++]=v},i=1;i<=s;++i)if(c[i]==cln&&i!=s)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w(32754);cls>2&&(w(cls>10?cls-11<<5|28690:cls-3<<5|12305),cls=0)}else if(cls>3){for(w(cln),--cls;cls>6;cls-=6)w(8304);cls>2&&(w(cls-3<<5|8208),cls=0)}for(;cls--;)w(cln);cls=1,cln=c[i]}return[cl.subarray(0,cli),s]},clen=function(cf,cl){for(var l=0,i=0;i>>8,out[o+2]=255^out[o],out[o+3]=255^out[o+1];for(var i=0;i4&&!lct[clim[nlcc-1]];--nlcc);var lm,ll,dm,dl,flen=bl+5<<3,ftlen=clen(lf,flt)+clen(df,fdt)+eb,dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+(2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18]);if(flen<=ftlen&&flen<=dtlen)return wfblk(out,p,dat.subarray(bs,bs+bl));if(wbits(out,p,1+(dtlen15&&(wbits(out,p,clct[i]>>>5&127),p+=clct[i]>>>12)}}}else lm=flm,ll=flt,dm=fdm,dl=fdt;for(i=0;i255){len=syms[i]>>>18&31,wbits16(out,p,lm[len+257]),p+=ll[len+257],len>7&&(wbits(out,p,syms[i]>>>23&31),p+=fleb[len]);var dst=31&syms[i];wbits16(out,p,dm[dst]),p+=dl[dst],dst>3&&(wbits16(out,p,syms[i]>>>5&8191),p+=fdeb[dst])}else wbits16(out,p,lm[syms[i]]),p+=ll[syms[i]];return wbits16(out,p,lm[256]),p+ll[256]},deo=new u32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),et=new u8(0),crct=function(){for(var t=new Int32Array(256),i=0;i<256;++i){for(var c=i,k=9;--k;)c=(1&c&&-306674912)^c>>>1;t[i]=c}return t}(),crc=function(){var c=-1;return{p:function(d){for(var cr=c,i=0;i>>8;c=cr},d:function(){return~c}}},dopt=function(dat,opt,pre,post,st){return function(dat,lvl,plvl,pre,post,lst){var s=dat.length,o=new u8(pre+s+5*(1+Math.ceil(s/7e3))+post),w=o.subarray(pre,o.length-post),pos=0;if(!lvl||s<8)for(var i=0;i<=s;i+=65535){var e=i+65535;e>=s&&(w[pos>>3]=lst),pos=wfblk(w,pos+1,dat.subarray(i,e))}else{for(var opt=deo[lvl-1],n=opt>>>13,c=8191&opt,msk_1=(1<7e3||li>24576)&&rem>423){pos=wblk(dat,w,0,syms,lf,df,eb,li,bs,i-bs,pos),li=lc_1=eb=0,bs=i;for(var j=0;j<286;++j)lf[j]=0;for(j=0;j<30;++j)df[j]=0}var l=2,d=0,ch_1=c,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i-dif))for(var maxn=Math.min(n,rem)-1,maxd=Math.min(32767,i),ml=Math.min(258,rem);dif<=maxd&&--ch_1&&imod!=pimod;){if(dat[i+l]==dat[i+l-dif]){for(var nl=0;nll){if(l=nl,d=dif,nl>maxn)break;var mmd=Math.min(dif,nl-2),md=0;for(j=0;jmd&&(md=cd,pimod=ti)}}}dif+=(imod=pimod)-(pimod=prev[imod])+32768&32767}if(d){syms[li++]=268435456|revfl[l]<<18|revfd[d];var lin=31&revfl[l],din=31&revfd[d];eb+=fleb[lin]+fdeb[din],++lf[257+lin],++df[din],wi=i+l,++lc_1}else syms[li++]=dat[i],++lf[dat[i]]}}pos=wblk(dat,w,lst,syms,lf,df,eb,li,bs,i-bs,pos),!lst&&7&pos&&(pos=wfblk(w,pos+1,et))}return slc(o,0,pre+shft(pos)+post)}(dat,null==opt.level?6:opt.level,null==opt.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(dat.length)))):12+opt.mem,pre,post,!st)},mrg=function(a,b){var o={};for(var k in a)o[k]=a[k];for(var k in b)o[k]=b[k];return o},wbytes=function(d,b,v){for(;v;++b)d[b]=v,v>>>=8};function deflateSync(data,opts){return dopt(data,opts||{},0,0)}var fltn=function(d,p,t,o){for(var k in d){var val=d[k],n=p+k,op=o;Array.isArray(val)&&(op=mrg(o,val[1]),val=val[0]),val instanceof u8?t[n]=[val,op]:(t[n+="/"]=[new u8(0),op],fltn(val,n,t,o))}},te="undefined"!=typeof TextEncoder&&new TextEncoder,td="undefined"!=typeof TextDecoder&&new TextDecoder;try{td.decode(et,{stream:!0})}catch(e){}function strToU8(str,latin1){if(latin1){for(var ar_1=new u8(str.length),i=0;i>1)),ai=0,w=function(v){ar[ai++]=v};for(i=0;iar.length){var n=new u8(ai+8+(l-i<<1));n.set(ar),ar=n}var c=str.charCodeAt(i);c<128||latin1?w(c):c<2048?(w(192|c>>6),w(128|63&c)):c>55295&&c<57344?(w(240|(c=65536+(1047552&c)|1023&str.charCodeAt(++i))>>18),w(128|c>>12&63),w(128|c>>6&63),w(128|63&c)):(w(224|c>>12),w(128|c>>6&63),w(128|63&c))}return slc(ar,0,ai)}var exfl=function(ex){var le=0;if(ex)for(var k in ex){var l=ex[k].length;l>65535&&err(9),le+=l+4}return le},wzh=function(d,b,f,fn,u,c,ce,co){var fl=fn.length,ex=f.extra,col=co&&co.length,exl=exfl(ex);wbytes(d,b,null!=ce?33639248:67324752),b+=4,null!=ce&&(d[b++]=20,d[b++]=f.os),d[b]=20,b+=2,d[b++]=f.flag<<1|(null==c&&8),d[b++]=u&&8,d[b++]=255&f.compression,d[b++]=f.compression>>8;var dt=new Date(null==f.mtime?Date.now():f.mtime),y=dt.getFullYear()-1980;if((y<0||y>119)&&err(10),wbytes(d,b,y<<25|dt.getMonth()+1<<21|dt.getDate()<<16|dt.getHours()<<11|dt.getMinutes()<<5|dt.getSeconds()>>>1),b+=4,null!=c&&(wbytes(d,b,f.crc),wbytes(d,b+4,c),wbytes(d,b+8,f.size)),wbytes(d,b+12,fl),wbytes(d,b+14,exl),b+=16,null!=ce&&(wbytes(d,b,col),wbytes(d,b+6,f.attrs),wbytes(d,b+10,ce),b+=14),d.set(fn,b),b+=fl,exl)for(var k in ex){var exf=ex[k],l=exf.length;wbytes(d,b,+k),wbytes(d,b+2,l),d.set(exf,b+4),b+=4+l}return col&&(d.set(co,b),b+=col),b};function zipSync(data,opts){opts||(opts={});var r={},files=[];fltn(data,"",r,opts);var o=0,tot=0;for(var fn in r){var _a=r[fn],file=_a[0],p=_a[1],compression=0==p.level?0:8,s=(f=strToU8(fn)).length,com=p.comment,m=com&&strToU8(com),ms=m&&m.length,exl=exfl(p.extra);s>65535&&err(11);var d=compression?deflateSync(file,p):file,l=d.length,c=crc();c.p(file),files.push(mrg(p,{size:file.length,crc:c.d(),c:d,f:f,m:m,u:s!=fn.length||m&&com.length!=ms,o:o,compression:compression})),o+=30+s+exl+l,tot+=76+2*(s+exl)+(ms||0)+l}for(var out=new u8(tot+22),oe=o,cdl=tot-o,i=0;i{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;const isEmpty=a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}));return isEmpty?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const rgbToHex=(...values)=>{if((values=flatten$1(values)).length<3)throw new Error("values must contain R, G and B values");const r=255*values[0],g=255*values[1],b=255*values[2];let s=`#${Number(16777216+65536*r+256*g+b).toString(16).substring(1,7)}`;return values.length>3&&(s+=Number(255*values[3]).toString(16)),s},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),contenttype='\n\n \n \n \n \n',rels='\n\n \n \n',translateResources=(objects,options)=>{let resources=["resources",{},translateMaterials(objects,options)];return resources=resources.concat(translateObjects(objects,options)),resources},translateMaterials=(objects,options)=>{let basematerials=["basematerials",{id:"0"}];const materials=[];return objects.forEach(((object,i)=>{let srgb=rgbToHex(options.defaultcolor).toUpperCase();object.color&&(srgb=rgbToHex(object.color).toUpperCase()),materials.push(["base",{name:`mat${i}`,displaycolor:srgb}])})),basematerials=basematerials.concat(materials),basematerials},translateObjects=(objects,options)=>{const contents=[];return objects.forEach(((object,i)=>{index$6.isA(object)&&index$6.toPolygons(object).length>0&&(options.id=i,contents.push(convertToObject(object,options)))})),contents},translateBuild=(objects,options)=>{let build=["build",{}];const items=[];return objects.forEach(((object,i)=>{items.push(["item",{objectid:`${i+1}`}])})),build=build.concat(items),build},convertToObject=(object,options)=>{const name=object.name?object.name:`Part ${options.id}`;return["object",{id:`${options.id+1}`,type:"model",pid:"0",pindex:`${options.id}`,name:name},convertToMesh(object)]},convertToMesh=(object,options)=>["mesh",{},convertToVertices(object),convertToVolumes(object)],convertToVertices=(object,options)=>{const vertices=[];return index$6.toPolygons(object).forEach((polygon=>{for(let i=0;i["vertex",{x:vertex[0],y:vertex[1],z:vertex[2]}],convertToVolumes=(object,options)=>{let n=0;const polygons=index$6.toPolygons(object);let contents=["triangles",{}];return polygons.forEach((polygon=>{if(polygon.vertices.length<3)return;const triangles=convertToTriangles(polygon,n);contents=contents.concat(triangles),n+=polygon.vertices.length})),contents},convertToTriangles=(polygon,index)=>{const contents=[];for(let i=0;i{options=Object.assign({},{unit:"millimeter",metadata:!0,defaultcolor:[1,160/255,0,1],compress:!0},options);const objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to 3MF");var array;objects.length!==objects3d.length&&console.warn("some objects could not be serialized to 3MF"),array=((options,...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results})({snap:!0,triangulate:!0},objects3d),objects=Array.isArray(array)?array:null==array?[]:[array];const body=["model",{unit:options.unit,"xml:lang":"und"},["metadata",{name:"Application"},"JSCAD"]];options.metadata&&body.push(["metadata",{name:"CreationDate"},(new Date).toISOString()]),body.push(translateResources(objects,options)),body.push(translateBuild(objects));const xml=`\n${stringify(body,2)}`;return options.compress?[zipSync({"3D":{"3dmodel.model":strToU8(xml)},_rels:{".rels":strToU8(rels)},"[Content_Types].xml":strToU8(contenttype)},{comment:"created by JSCAD"}).buffer]:[xml]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscad3mfSerializer={}); +var global,factory;global=this,factory=function(exports){var u8=Uint8Array,u16=Uint16Array,u32=Uint32Array,fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb=function(eb,start){for(var b=new u16(31),i=0;i<31;++i)b[i]=start+=1<>>1|(21845&i)<<1;x=(61680&(x=(52428&x)>>>2|(13107&x)<<2))>>>4|(3855&x)<<4,rev[i]=((65280&x)>>>8|(255&x)<<8)>>>1}var hMap=function(cd,mb,r){for(var s=cd.length,i=0,l=new u16(mb);i>>rvb]=sv}else for(co=new u16(s),i=0;i>>15-cd[i]);return co},flt=new u8(288);for(i=0;i<144;++i)flt[i]=8;for(i=144;i<256;++i)flt[i]=9;for(i=256;i<280;++i)flt[i]=7;for(i=280;i<288;++i)flt[i]=8;var fdt=new u8(32);for(i=0;i<32;++i)fdt[i]=5;var flm=hMap(flt,9,0),fdm=hMap(fdt,5,0),shft=function(p){return(p+7)/8|0},slc=function(v,s,e){(null==s||s<0)&&(s=0),(null==e||e>v.length)&&(e=v.length);var n=new(2==v.BYTES_PER_ELEMENT?u16:4==v.BYTES_PER_ELEMENT?u32:u8)(e-s);return n.set(v.subarray(s,e)),n},ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);if(e.code=ind,Error.captureStackTrace&&Error.captureStackTrace(e,err),!nt)throw e;return e},wbits=function(d,p,v){v<<=7&p;var o=p/8|0;d[o]|=v,d[o+1]|=v>>>8},wbits16=function(d,p,v){v<<=7&p;var o=p/8|0;d[o]|=v,d[o+1]|=v>>>8,d[o+2]|=v>>>16},hTree=function(d,mb){for(var t=[],i=0;imaxSym&&(maxSym=t2[i].s);var tr=new u16(maxSym+1),mbt=ln(t[i1-1],tr,0);if(mbt>mb){i=0;var dt=0,lft=mbt-mb,cst=1<mb))break;dt+=cst-(1<>>=lft;dt>0;){var i2_2=t2[i].s;tr[i2_2]=0&&dt;--i){var i2_3=t2[i].s;tr[i2_3]==mb&&(--tr[i2_3],++dt)}mbt=mb}return[new u8(tr),mbt]},ln=function(n,l,d){return-1==n.s?Math.max(ln(n.l,l,d+1),ln(n.r,l,d+1)):l[n.s]=d},lc=function(c){for(var s=c.length;s&&!c[--s];);for(var cl=new u16(++s),cli=0,cln=c[0],cls=1,w=function(v){cl[cli++]=v},i=1;i<=s;++i)if(c[i]==cln&&i!=s)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w(32754);cls>2&&(w(cls>10?cls-11<<5|28690:cls-3<<5|12305),cls=0)}else if(cls>3){for(w(cln),--cls;cls>6;cls-=6)w(8304);cls>2&&(w(cls-3<<5|8208),cls=0)}for(;cls--;)w(cln);cls=1,cln=c[i]}return[cl.subarray(0,cli),s]},clen=function(cf,cl){for(var l=0,i=0;i>>8,out[o+2]=255^out[o],out[o+3]=255^out[o+1];for(var i=0;i4&&!lct[clim[nlcc-1]];--nlcc);var lm,ll,dm,dl,flen=bl+5<<3,ftlen=clen(lf,flt)+clen(df,fdt)+eb,dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+(2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18]);if(flen<=ftlen&&flen<=dtlen)return wfblk(out,p,dat.subarray(bs,bs+bl));if(wbits(out,p,1+(dtlen15&&(wbits(out,p,clct[i]>>>5&127),p+=clct[i]>>>12)}}}else lm=flm,ll=flt,dm=fdm,dl=fdt;for(i=0;i255){len=syms[i]>>>18&31,wbits16(out,p,lm[len+257]),p+=ll[len+257],len>7&&(wbits(out,p,syms[i]>>>23&31),p+=fleb[len]);var dst=31&syms[i];wbits16(out,p,dm[dst]),p+=dl[dst],dst>3&&(wbits16(out,p,syms[i]>>>5&8191),p+=fdeb[dst])}else wbits16(out,p,lm[syms[i]]),p+=ll[syms[i]];return wbits16(out,p,lm[256]),p+ll[256]},deo=new u32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),et=new u8(0),crct=function(){for(var t=new Int32Array(256),i=0;i<256;++i){for(var c=i,k=9;--k;)c=(1&c&&-306674912)^c>>>1;t[i]=c}return t}(),crc=function(){var c=-1;return{p:function(d){for(var cr=c,i=0;i>>8;c=cr},d:function(){return~c}}},dopt=function(dat,opt,pre,post,st){return function(dat,lvl,plvl,pre,post,lst){var s=dat.length,o=new u8(pre+s+5*(1+Math.ceil(s/7e3))+post),w=o.subarray(pre,o.length-post),pos=0;if(!lvl||s<8)for(var i=0;i<=s;i+=65535){var e=i+65535;e>=s&&(w[pos>>3]=lst),pos=wfblk(w,pos+1,dat.subarray(i,e))}else{for(var opt=deo[lvl-1],n=opt>>>13,c=8191&opt,msk_1=(1<7e3||li>24576)&&rem>423){pos=wblk(dat,w,0,syms,lf,df,eb,li,bs,i-bs,pos),li=lc_1=eb=0,bs=i;for(var j=0;j<286;++j)lf[j]=0;for(j=0;j<30;++j)df[j]=0}var l=2,d=0,ch_1=c,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i-dif))for(var maxn=Math.min(n,rem)-1,maxd=Math.min(32767,i),ml=Math.min(258,rem);dif<=maxd&&--ch_1&&imod!=pimod;){if(dat[i+l]==dat[i+l-dif]){for(var nl=0;nll){if(l=nl,d=dif,nl>maxn)break;var mmd=Math.min(dif,nl-2),md=0;for(j=0;jmd&&(md=cd,pimod=ti)}}}dif+=(imod=pimod)-(pimod=prev[imod])+32768&32767}if(d){syms[li++]=268435456|revfl[l]<<18|revfd[d];var lin=31&revfl[l],din=31&revfd[d];eb+=fleb[lin]+fdeb[din],++lf[257+lin],++df[din],wi=i+l,++lc_1}else syms[li++]=dat[i],++lf[dat[i]]}}pos=wblk(dat,w,lst,syms,lf,df,eb,li,bs,i-bs,pos),!lst&&7&pos&&(pos=wfblk(w,pos+1,et))}return slc(o,0,pre+shft(pos)+post)}(dat,null==opt.level?6:opt.level,null==opt.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(dat.length)))):12+opt.mem,pre,post,!st)},mrg=function(a,b){var o={};for(var k in a)o[k]=a[k];for(var k in b)o[k]=b[k];return o},wbytes=function(d,b,v){for(;v;++b)d[b]=v,v>>>=8};function deflateSync(data,opts){return dopt(data,opts||{},0,0)}var fltn=function(d,p,t,o){for(var k in d){var val=d[k],n=p+k,op=o;Array.isArray(val)&&(op=mrg(o,val[1]),val=val[0]),val instanceof u8?t[n]=[val,op]:(t[n+="/"]=[new u8(0),op],fltn(val,n,t,o))}},te="undefined"!=typeof TextEncoder&&new TextEncoder,td="undefined"!=typeof TextDecoder&&new TextDecoder;try{td.decode(et,{stream:!0})}catch(e){}function strToU8(str,latin1){if(latin1){for(var ar_1=new u8(str.length),i=0;i>1)),ai=0,w=function(v){ar[ai++]=v};for(i=0;iar.length){var n=new u8(ai+8+(l-i<<1));n.set(ar),ar=n}var c=str.charCodeAt(i);c<128||latin1?w(c):c<2048?(w(192|c>>6),w(128|63&c)):c>55295&&c<57344?(w(240|(c=65536+(1047552&c)|1023&str.charCodeAt(++i))>>18),w(128|c>>12&63),w(128|c>>6&63),w(128|63&c)):(w(224|c>>12),w(128|c>>6&63),w(128|63&c))}return slc(ar,0,ai)}var exfl=function(ex){var le=0;if(ex)for(var k in ex){var l=ex[k].length;l>65535&&err(9),le+=l+4}return le},wzh=function(d,b,f,fn,u,c,ce,co){var fl=fn.length,ex=f.extra,col=co&&co.length,exl=exfl(ex);wbytes(d,b,null!=ce?33639248:67324752),b+=4,null!=ce&&(d[b++]=20,d[b++]=f.os),d[b]=20,b+=2,d[b++]=f.flag<<1|(null==c&&8),d[b++]=u&&8,d[b++]=255&f.compression,d[b++]=f.compression>>8;var dt=new Date(null==f.mtime?Date.now():f.mtime),y=dt.getFullYear()-1980;if((y<0||y>119)&&err(10),wbytes(d,b,y<<25|dt.getMonth()+1<<21|dt.getDate()<<16|dt.getHours()<<11|dt.getMinutes()<<5|dt.getSeconds()>>>1),b+=4,null!=c&&(wbytes(d,b,f.crc),wbytes(d,b+4,c),wbytes(d,b+8,f.size)),wbytes(d,b+12,fl),wbytes(d,b+14,exl),b+=16,null!=ce&&(wbytes(d,b,col),wbytes(d,b+6,f.attrs),wbytes(d,b+10,ce),b+=14),d.set(fn,b),b+=fl,exl)for(var k in ex){var exf=ex[k],l=exf.length;wbytes(d,b,+k),wbytes(d,b+2,l),d.set(exf,b+4),b+=4+l}return col&&(d.set(co,b),b+=col),b};function zipSync(data,opts){opts||(opts={});var r={},files=[];fltn(data,"",r,opts);var o=0,tot=0;for(var fn in r){var _a=r[fn],file=_a[0],p=_a[1],compression=0==p.level?0:8,s=(f=strToU8(fn)).length,com=p.comment,m=com&&strToU8(com),ms=m&&m.length,exl=exfl(p.extra);s>65535&&err(11);var d=compression?deflateSync(file,p):file,l=d.length,c=crc();c.p(file),files.push(mrg(p,{size:file.length,crc:c.d(),c:d,f:f,m:m,u:s!=fn.length||m&&com.length!=ms,o:o,compression:compression})),o+=30+s+exl+l,tot+=76+2*(s+exl)+(ms||0)+l}for(var out=new u8(tot+22),oe=o,cdl=tot-o,i=0;i{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;const isEmpty=a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}));return isEmpty?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),rgbToHex=(...values)=>{if((values=flatten$1(values)).length<3)throw new Error("values must contain R, G and B values");const r=255*values[0],g=255*values[1],b=255*values[2];let s=`#${Number(16777216+65536*r+256*g+b).toString(16).substring(1,7)}`;return values.length>3&&(s+=Number(255*values[3]).toString(16)),s},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),contenttype='\n\n \n \n \n \n',rels='\n\n \n \n',translateResources=(objects,options)=>{let resources=["resources",{},translateMaterials(objects,options)];return resources=resources.concat(translateObjects(objects,options)),resources},translateMaterials=(objects,options)=>{let basematerials=["basematerials",{id:"0"}];const materials=[];return objects.forEach(((object,i)=>{let srgb=rgbToHex(options.defaultcolor).toUpperCase();object.color&&(srgb=rgbToHex(object.color).toUpperCase()),materials.push(["base",{name:`mat${i}`,displaycolor:srgb}])})),basematerials=basematerials.concat(materials),basematerials},translateObjects=(objects,options)=>{const contents=[];return objects.forEach(((object,i)=>{index$6.isA(object)&&index$6.toPolygons(object).length>0&&(options.id=i,contents.push(convertToObject(object,options)))})),contents},translateBuild=(objects,options)=>{let build=["build",{}];const items=[];return objects.forEach(((object,i)=>{items.push(["item",{objectid:`${i+1}`}])})),build=build.concat(items),build},convertToObject=(object,options)=>{const name=object.name?object.name:`Part ${options.id}`;return["object",{id:`${options.id+1}`,type:"model",pid:"0",pindex:`${options.id}`,name:name},convertToMesh(object)]},convertToMesh=(object,options)=>["mesh",{},convertToVertices(object),convertToVolumes(object)],convertToVertices=(object,options)=>{const vertices=[];return index$6.toPolygons(object).forEach((polygon=>{for(let i=0;i["vertex",{x:vertex[0],y:vertex[1],z:vertex[2]}],convertToVolumes=(object,options)=>{let n=0;const polygons=index$6.toPolygons(object);let contents=["triangles",{}];return polygons.forEach((polygon=>{if(polygon.vertices.length<3)return;const triangles=convertToTriangles(polygon,n);contents=contents.concat(triangles),n+=polygon.vertices.length})),contents},convertToTriangles=(polygon,index)=>{const contents=[];for(let i=0;i{options=Object.assign({},{unit:"millimeter",metadata:!0,defaultcolor:[1,160/255,0,1],compress:!0},options);const objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to 3MF");var array;objects.length!==objects3d.length&&console.warn("some objects could not be serialized to 3MF"),array=generalize({snap:!0,triangulate:!0},objects3d),objects=Array.isArray(array)?array:null==array?[]:[array];const body=["model",{unit:options.unit,"xml:lang":"und"},["metadata",{name:"Application"},"JSCAD"]];options.metadata&&body.push(["metadata",{name:"CreationDate"},(new Date).toISOString()]),body.push(translateResources(objects,options)),body.push(translateBuild(objects));const xml=`\n${stringify(body,2)}`;return options.compress?[zipSync({"3D":{"3dmodel.model":strToU8(xml)},_rels:{".rels":strToU8(rels)},"[Content_Types].xml":strToU8(contenttype)},{comment:"created by JSCAD"}).buffer]:[xml]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscad3mfSerializer={}); diff --git a/packages/io/3mf-serializer/package.json b/packages/io/3mf-serializer/package.json index 7aaa69bc3..5720cca60 100644 --- a/packages/io/3mf-serializer/package.json +++ b/packages/io/3mf-serializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/3mf-serializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "3MF serializer for JSCAD project", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -32,9 +32,9 @@ "access": "public" }, "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/io-utils": "workspace:^3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0", + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/io-utils": "workspace:^3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", "fflate": "^0.7.3", "onml": "^1.2.0" }, diff --git a/packages/io/dxf-deserializer/CHANGELOG.md b/packages/io/dxf-deserializer/CHANGELOG.md index 08f846522..f23f1ec09 100644 --- a/packages/io/dxf-deserializer/CHANGELOG.md +++ b/packages/io/dxf-deserializer/CHANGELOG.md @@ -3,6 +3,18 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/dxf-deserializer@2.3.19...@jscad/dxf-deserializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** renamed poly3 toVertices and fromVerticesAndPlane ([58621b9](https://github.com/jscad/OpenJSCAD.org/commit/58621b9d23d8e0905eff23faf8e9dddb2c4023fb)) +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) +* **regl-renderer:** added rollup configuration to create ES6 bundle, adjusted imports and exports ([#1259](https://github.com/jscad/OpenJSCAD.org/issues/1259)) ([47a66bc](https://github.com/jscad/OpenJSCAD.org/commit/47a66bc07a137a748ce8571ea5d043ebaab9418d)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/dxf-deserializer@2.3.19...@jscad/dxf-deserializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/dxf-deserializer/dist/jscad-dxf-deserializer.es.js b/packages/io/dxf-deserializer/dist/jscad-dxf-deserializer.es.js index 05236c703..221e95935 100644 --- a/packages/io/dxf-deserializer/dist/jscad-dxf-deserializer.es.js +++ b/packages/io/dxf-deserializer/dist/jscad-dxf-deserializer.es.js @@ -1,7 +1,7 @@ /** * DXF Deserializer for JSCAD * @module @jscad/dxf-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const dxfMap=new Map([[0,"etyp"],[1,"text"],[2,"name"],[3,"nam1"],[5,"hdle"],[6,"ltyp"],[7,"lsty"],[8,"lnam"],[9,"vari"],[10,"pptx"],[11,"sptx"],[12,"tptx"],[13,"fptx"],[20,"ppty"],[21,"spty"],[22,"tpty"],[23,"fpty"],[30,"pptz"],[31,"sptz"],[32,"tptz"],[33,"fptz"],[38,"elev"],[39,"lthk"],[40,"swid"],[41,"ewid"],[42,"bulg"],[43,"cwid"],[48,"lscl"],[50,"ang0"],[51,"ang1"],[60,"visb"],[62,"cnmb"],[67,"spac"],[70,"lflg"],[71,"fvia"],[72,"fvib"],[73,"fvic"],[74,"fvid"],[75,"cflg"],[90,"vlen"],[91,"slen"],[92,"plen"],[93,"flen"],[94,"elen"],[95,"clen"],[100,"sbnm"],[210,"etrx"],[220,"etry"],[230,"etrz"]]),getTLA=group=>dxfMap.get(group),colorIndex=[[0,0,0,255],[255,0,0,255],[255,255,0,255],[0,255,0,255],[0,255,255,255],[0,0,255,255],[255,0,255,255],[255,255,255,255],[128,128,128,255],[192,192,192,255],[255,0,0,255],[255,127,127,255],[165,0,0,255],[165,82,82,255],[127,0,0,255],[127,63,63,255],[76,0,0,255],[76,38,38,255],[38,0,0,255],[38,19,19,255],[255,63,0,255],[255,159,127,255],[165,41,0,255],[165,103,82,255],[127,31,0,255],[127,79,63,255],[76,19,0,255],[76,47,38,255],[38,9,0,255],[38,28,19,255],[255,127,0,255],[255,191,127,255],[165,82,0,255],[165,124,82,255],[127,63,0,255],[127,95,63,255],[76,38,0,255],[76,57,38,255],[38,19,0,255],[38,28,19,255],[255,191,0,255],[255,223,127,255],[165,124,0,255],[165,145,82,255],[127,95,0,255],[127,111,63,255],[76,57,0,255],[76,66,38,255],[38,28,0,255],[38,33,19,255],[255,255,0,255],[255,255,127,255],[165,165,0,255],[165,165,82,255],[127,127,0,255],[127,127,63,255],[76,76,0,255],[76,76,38,255],[38,38,0,255],[38,38,19,255],[191,255,0,255],[223,255,127,255],[124,165,0,255],[145,165,82,255],[95,127,0,255],[111,127,63,255],[57,76,0,255],[66,76,38,255],[28,38,0,255],[33,38,19,255],[127,255,0,255],[191,255,127,255],[82,165,0,255],[124,165,82,255],[63,127,0,255],[95,127,63,255],[38,76,0,255],[57,76,38,255],[19,38,0,255],[28,38,19,255],[63,255,0,255],[159,255,127,255],[41,165,0,255],[103,165,82,255],[31,127,0,255],[79,127,63,255],[19,76,0,255],[47,76,38,255],[9,38,0,255],[23,38,19,255],[0,255,0,255],[125,255,127,255],[0,165,0,255],[82,165,82,255],[0,127,0,255],[63,127,63,255],[0,76,0,255],[38,76,38,255],[0,38,0,255],[19,38,19,255],[0,255,63,255],[127,255,159,255],[0,165,41,255],[82,165,103,255],[0,127,31,255],[63,127,79,255],[0,76,19,255],[38,76,47,255],[0,38,9,255],[19,88,23,255],[0,255,127,255],[127,255,191,255],[0,165,82,255],[82,165,124,255],[0,127,63,255],[63,127,95,255],[0,76,38,255],[38,76,57,255],[0,38,19,255],[19,88,28,255],[0,255,191,255],[127,255,223,255],[0,165,124,255],[82,165,145,255],[0,127,95,255],[63,127,111,255],[0,76,57,255],[38,76,66,255],[0,38,28,255],[19,88,88,255],[0,255,255,255],[127,255,255,255],[0,165,165,255],[82,165,165,255],[0,127,127,255],[63,127,127,255],[0,76,76,255],[38,76,76,255],[0,38,38,255],[19,88,88,255],[0,191,255,255],[127,223,255,255],[0,124,165,255],[82,145,165,255],[0,95,127,255],[63,111,217,255],[0,57,76,255],[38,66,126,255],[0,28,38,255],[19,88,88,255],[0,127,255,255],[127,191,255,255],[0,82,165,255],[82,124,165,255],[0,63,127,255],[63,95,127,255],[0,38,76,255],[38,57,126,255],[0,19,38,255],[19,28,88,255],[0,63,255,255],[127,159,255,255],[0,41,165,255],[82,103,165,255],[0,31,127,255],[63,79,127,255],[0,19,76,255],[38,47,126,255],[0,9,38,255],[19,23,88,255],[0,0,255,255],[127,127,255,255],[0,0,165,255],[82,82,165,255],[0,0,127,255],[63,63,127,255],[0,0,76,255],[38,38,126,255],[0,0,38,255],[19,19,88,255],[63,0,255,255],[159,127,255,255],[41,0,165,255],[103,82,165,255],[31,0,127,255],[79,63,127,255],[19,0,76,255],[47,38,126,255],[9,0,38,255],[23,19,88,255],[127,0,255,255],[191,127,255,255],[165,0,82,255],[124,82,165,255],[63,0,127,255],[95,63,127,255],[38,0,76,255],[57,38,126,255],[19,0,38,255],[28,19,88,255],[191,0,255,255],[223,127,255,255],[124,0,165,255],[142,82,165,255],[95,0,127,255],[111,63,127,255],[57,0,76,255],[66,38,76,255],[28,0,38,255],[88,19,88,255],[255,0,255,255],[255,127,255,255],[165,0,165,255],[165,82,165,255],[127,0,127,255],[127,63,127,255],[76,0,76,255],[76,38,76,255],[38,0,38,255],[88,19,88,255],[255,0,191,255],[255,127,223,255],[165,0,124,255],[165,82,145,255],[127,0,95,255],[127,63,111,255],[76,0,57,255],[76,38,66,255],[38,0,28,255],[88,19,88,255],[255,0,127,255],[255,127,191,255],[165,0,82,255],[165,82,124,255],[127,0,63,255],[127,63,95,255],[76,0,38,255],[76,38,57,255],[38,0,19,255],[88,19,28,255],[255,0,63,255],[255,127,159,255],[165,0,41,255],[165,82,103,255],[127,0,31,255],[127,63,79,255],[76,0,19,255],[76,38,47,255],[38,0,9,255],[88,19,23,255],[0,0,0,255],[101,101,101,255],[102,102,102,255],[153,153,153,255],[204,204,204,255],[255,255,255,255]];class DxfReader{constructor(options){this.options=Object.assign({},{strict:!1,track:!0},options),this.trackPosition=this.options.track,this.trackPosition&&(this.line=0,this.column=0,this.c=0)}on(state,callback){return this["on"+state]=callback,this}absorb(group,callback){return void 0===this.absorbers&&(this.absorbers=new Map),this.absorbers.set(group,callback),this}write(data){return parse(this,data),this}close(){return this.isclosed=!0,this}}const emiterror=(reader,er)=>(reader.trackPosition&&(er+=`\nLine: ${reader.line}\nColumn: ${reader.column}\nChar: ${reader.c}`),er=new Error(er),reader.error=er,emitstate(reader,"onerror",er)),emitend=reader=>emitstate(reader,"onend",reader.data),emitstate=(reader,state,data)=>{const onhandler=state.toString();return reader[onhandler]&&reader[onhandler](reader,data),reader},parse=(reader,data)=>{if(reader.error)throw reader.error;if(reader.isclosed)return emiterror(reader,"Cannot write after close");if((reader=>{emitstate(reader,"onstart",reader.data)})(reader),null===data)return emitend(reader);reader.group=null,reader.value=null,reader.error=null,reader.position=0,reader.line=0,reader.column=0;let i=0,c="",l="";for(;null===reader.error&&(c=charAt(data,i++),c);)reader.trackPosition&&(reader.position++,"\n"===c?(reader.line++,reader.column=0):reader.column++),"\n"===c?(parseLine(reader,l),l=""):l+=c;return emitend(reader),reader},parseLine=(reader,line)=>{line=line.trim(),null===reader.group?(setDxfGroup(reader,line),reader.value=null):setDxfValue(reader,line),null!==reader.group&&null!==reader.value&&(((reader,group,value)=>{if(void 0!==reader.absorbers){const absorber=reader.absorbers.get(group);void 0!==absorber&&absorber(reader,group,value)}})(reader,reader.group,reader.value),reader.group=null,reader.value=null)},setDxfGroup=(reader,line)=>{const code=parseInt(line);isNaN(code)?(emiterror(reader,"Invalid group (int)"),reader.group=null):reader.group=code},setDxfValue=(reader,line)=>{reader.options.strict,reader.value=line},charAt=(data,i)=>data&&data.length>i?data.charAt(i):"",clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS$1=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};var index$b=Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(value=radius,constant=0,!(Number.isFinite(value)&&value>constant))throw new Error("radius must be greater than zero");var value,constant;if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS$1*EPS$1)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps)),point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})},line=points=>{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},findLayer=(obj,layers)=>{const lname=obj.lnam||"0";for(const layer of layers)if(layer.name===lname)return layer;return null},getColorNumber=(obj,layers)=>{let cn=obj.cnmb||-1;if(256===cn){cn=-1;const layer=findLayer(obj,layers);null!==layer&&(cn=layer.cnmb||-1)}return cn},getColor=(index,colorindex)=>{if(index<1)return null;index=((num,mod)=>{const remain=num%mod;return Math.floor(remain>=0?remain:remain+mod)})(index,colorindex.length);const color=colorindex[index];return[color[0]/255,color[1]/255,color[2]/255,color[3]/255]},instantiatePolygon=(obj,layers,options)=>{const vertices=[];if(vertices.push(index$d.fromValues(obj.pptx,obj.ppty,obj.pptz)),vertices.push(index$d.fromValues(obj.sptx,obj.spty,obj.sptz)),vertices.push(index$d.fromValues(obj.tptx,obj.tpty,obj.tptz)),obj.fptx){let pushit=!1;obj.tptx!==obj.fptx&&(pushit=!0),obj.tpty!==obj.fpty&&(pushit=!0),obj.tptz!==obj.fptz&&(pushit=!0),pushit&&vertices.push(index$d.fromValues(obj.fptx,obj.fpty,obj.fptz))}const cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygon=index$7.create(vertices);return color&&(polygon.color=color),polygon},instantiateLine=(obj,layers,options)=>{if(obj.pptz===obj.sptz&&0===obj.pptz){const p1=index$b.fromValues(obj.pptx,obj.ppty),p2=index$b.fromValues(obj.sptx,obj.spty);return line([p1,p2])}const p1=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),p2=index$d.fromValues(obj.sptx,obj.spty,obj.sptz);return line([p1,p2])},instantiateVector=obj=>{const d3line=parseInt("00000000000100000",2),d3mesh=parseInt("00000000001000000",2),d3face=parseInt("00000000010000000",2),flags=obj.lflg,vtype={};return(flags&d3line)===d3line||(flags&d3mesh)===d3mesh?vtype.vec=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz):(flags&d3face)===d3face?(vtype.vec=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),vtype.fvia=obj.fvia,vtype.fvib=obj.fvib,vtype.fvic=obj.fvic,vtype.fvid=obj.fvid):(vtype.vec=index$b.fromValues(obj.pptx,obj.ppty),vtype.bulg=obj.bulg),vtype},addSection=(path,x1,y1,bulg)=>{if(0===bulg)path=index$5.appendPoints([[x1,y1]],path);else{const points=index$5.toPoints(path),prev=points[points.length-1],curr=index$b.fromValues(x1,y1),r=index$b.distance(prev,curr)*((1+Math.pow(bulg,2))/(4*bulg)),clockwise=bulg<0,large=!1,d=4*Math.atan(bulg),res=16;path=index$5.appendArc({endpoint:[x1,y1],radius:[r,r],xaxisrotation:d,clockwise:clockwise,large:large,segments:res},path)}return path},instantiatePath2D=(obj,layers,options)=>{const closed=parseInt("00000000000000001",2),vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,bulgs=obj.bulgs,flags=obj.lflg;let path=index$5.create();const isclosed=(flags&closed)===closed;return vlen!==pptxs.length||vlen!==pptys.length||vlen!==bulgs.length||(pptxs.forEach(((item,index,array)=>{let bulg=0;index>0&&(bulg=bulgs[index-1]),path=addSection(path,pptxs[index],pptys[index],bulg)})),isclosed&&!path.isClosed&&(path=addSection(path,pptxs[0],pptys[0],bulgs[vlen-1]),path=index$5.close(path))),path},instantiateArc=(obj,layers,options)=>{obj.lthk;const pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid;let ang0=obj.ang0;ang0*=.017453292519943295;let ang1=obj.ang1;ang1*=.017453292519943295;return arc({center:[pptx,ppty],radius:swid,startAngle:ang0,endAngle:ang1,segments:16})},instantiateCircle=(obj,layers,options)=>{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===lthk){const cag=circle({center:[pptx,ppty],radius:swid,segments:16});return color&&(cag.color=color),cag}const csg=circle({center:[pptx,ppty],radius:swid,segments:16}).extrude({offset:[0,0,lthk]});return color&&(csg.color=color),csg},instantiateEllipse=(obj,layers,options)=>{const pptx=obj.pptx,ppty=obj.ppty,pptz=obj.pptz,sptx=obj.sptx,spty=obj.spty,sptz=obj.sptz,swid=obj.swid;if(0===pptz&&0===sptz){const center=index$b.fromValues(0,0),mjaxis=index$b.fromValues(sptx,spty),rx=index$b.distance(center,mjaxis),ry=rx*swid;let angle=180*Math.atan2(spty,sptx)/Math.PI;angle<1e-5&&(angle=0),angle*=.017453292519943295;const cag=ellipse({center:[0,0],radius:[rx,ry],segments:16}),matrix=index$c.fromZRotation(index$c.create(),angle);return index$c.multiply(matrix,matrix,index$c.fromTranslation(index$c.create(),[pptx,ppty,0])),index$a.transform(matrix,cag)}},instantiateMesh=(obj,layers,options)=>{const vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,pptzs=obj.pptzs,flen=obj.flen,fvals=obj.fvals,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygons=[];if(vlen===pptxs.length&&vlen===pptys.length&&vlen===pptzs.length&&flen===fvals.length){const faces=(fvals=>{const faces=[];let vi=0;for(;vi0;)face.push(fvals[vi++]),fi--;faces.push(face)}return faces})(fvals),points=((pptxs,pptys,pptzs)=>{const points=[];let vi=0;for(;vi{const closedM=parseInt("00000000000000001",2),d3line=parseInt("00000000000001000",2),d3mesh=parseInt("00000000000010000",2),closedN=parseInt("00000000000100000",2),d3face=parseInt("00000000001000000",2),flags=obj.lflg;let ptype=null;return(flags&d3line)===d3line?ptype=null:(flags&d3mesh)===d3mesh||(flags&d3face)===d3face?(ptype=index$6.create(),ptype.closedM=(flags&closedM)===closedM,ptype.closedN=(flags&closedN)===closedN):(ptype=index$5.create(),ptype.closedM=(flags&closedM)===closedM),"cnmb"in obj&&(ptype.cnmb=obj.cnmb),ptype},completeCurrent=(objects,baseobj,polygons,vectors,options)=>{if(index$5.isA(baseobj)){const points=vectors.map((vector=>vector.vec));objects.push(index$5.fromPoints({closed:baseobj.closed},points))}return index$6.isA(baseobj)&&objects.push(index$6.create(polygons)),null},translateVector2D=vector=>`${vector[0]},${vector[1]}`,translateVector3D=vector=>`${vector[0]},${vector[1]},${vector[2]}`,translatePolygon=polygon=>{const vertices=index$7.toVertices(polygon);let script="createPolygon([";return vertices.forEach((vertice=>{script+=`[${translateVector3D(vertice)}],`})),script+=`],${translateColor(polygon)})`,script},translateColor=polygon=>{let script="null";if("color"in polygon){const rgb=polygon.color;script=`[${rgb[0]},${rgb[1]},${rgb[2]},${rgb[3]}]`}return script},translateLine=(obj,layers,options)=>{const name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);let script="";if(!obj.pptz||obj.pptz===obj.sptz&&0===obj.pptz){const p1=index$b.fromValues(obj.pptx,obj.ppty),p2=index$b.fromValues(obj.sptx,obj.spty);script=` let ${name} = line([[${translateVector2D(p1)}],[${translateVector2D(p2)}]])\n`}else{const p1=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),p2=index$d.fromValues(obj.sptx,obj.spty,obj.sptz);script=` let ${name} = line([[${translateVector3D(p1)}],[${translateVector3D(p2)}]])\n`}color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateSection=(name,x1,y1,bulg,px,py)=>{if(0===bulg)return`path2.appendPoints([[${x1},${y1}]], ${name})\n`;const prev=index$b.fromValues(px,py),curr=index$b.fromValues(x1,y1),r=index$b.distance(prev,curr)*((1+Math.pow(bulg,2))/(4*bulg)),clockwise=bulg<0;return`path2.appendArc({endpoint: [${x1},${y1}],radius: [${r},${r}],xaxisrotation: ${4*Math.atan(bulg)},clockwise: ${clockwise},large: false,segments: 16}, ${name})\n`},translatePath2D=(obj,layers,options)=>{const closed=parseInt("00000000000000001",2),vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,bulgs=obj.bulgs,flags=obj.lflg,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);let script=` let ${name} = path2.create()\n`;const isclosed=(flags&closed)===closed;if(vlen===pptxs.length&&vlen===pptys.length&&vlen===bulgs.length){script+=` ${name} = path2.appendPoints([[${pptxs[0]}, ${pptys[0]}]], ${name})\n`;for(let i=0;i{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid;let ang0=obj.ang0,ang1=obj.ang1;const name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);ang0*=.017453292519943295,ang1*=.017453292519943295;if(0===lthk){let script=` let ${name} = arc({center: [${pptx}, ${ppty}], radius: ${swid}, startAngle: ${ang0}, endAngle: ${ang1}, segements: 16})\n`;return color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,void addToLayer(obj,layers)}let script=` let ${name} = arc({center: [${pptx}, ${ppty}], radius: ${swid}, startAngle: ${ang0}, endAngle: ${ang1}, segements: 16})\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateCircle=(obj,layers,options)=>{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===lthk){let script=` let ${name} = circle({center: [${pptx}, ${ppty}], radius: ${swid}, segments: 16})\n`;return color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,void addToLayer(obj,layers)}let script=` let ${name} = circle({center: [${pptx}, ${ppty}], radius: ${swid}, segments: 16}).extrude({offset: [0,0,${lthk}]}))\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateEllipse=(obj,layers,options)=>{const pptx=obj.pptx,ppty=obj.ppty,pptz=obj.pptz,sptx=obj.sptx,spty=obj.spty,sptz=obj.sptz,swid=obj.swid,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===pptz&&0===sptz){const center=index$b.fromValues(0,0),mjaxis=index$b.fromValues(sptx,spty),rx=index$b.distance(center,mjaxis);let script=` let ${name} = ellipse({center: [0, 0, 0], radius: [${rx}, ${rx*swid}], segments: 16})\n let ${name}matrix = mat4.multiply(mat4.create(), mat4.fromTranslation(mat4.create(), [${pptx}, ${ppty}, 0]), mat4.fromZRotation(mat4.create(), ${Math.atan2(spty,sptx)}))\n ${name} = geom2.transform(${name}matrix, ${name})\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)}},translateMesh=(obj,layers,options)=>{const vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,pptzs=obj.pptzs,flen=obj.flen,fvals=obj.fvals,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygons=[];if(vlen===pptxs.length&&vlen===pptys.length&&vlen===pptzs.length)if(flen===fvals.length){const faces=(fvals=>{const faces=[];let vi=0;for(;vi0;)face.push(fvals[vi++]),fi--;faces.push(face)}return faces})(fvals),points=((pptxs,pptys,pptzs)=>{const points=[];let vi=0;for(;vi{let layer=findLayer(obj,layers);null===layer&&(layer=(layers=>{for(const layer of layers)if("0"===layer.name)return layer;const layer={type:"layer",lnam:"layer0",name:"0",lscl:1,visb:0,spac:0,objects:[]};return layers.push(layer),layer})(layers)),"objects"in layer||(layer.objects=[]),layer.objects.push(obj)},getPolyType=obj=>{const closedM=parseInt("00000000000000001",2),d3line=parseInt("00000000000001000",2),d3mesh=parseInt("00000000000010000",2),closedN=parseInt("00000000000100000",2),d3face=parseInt("00000000001000000",2),flags=obj.lflg;let ptype=null;if((flags&d3line)===d3line){ptype={type:"3dline",isclosed:(flags&closedM)===closedM}}else if((flags&d3mesh)===d3mesh)ptype={type:"3dpolymesh"},ptype.fvia=obj.fvia,ptype.fvib=obj.fvib,ptype.closedM=(flags&closedM)===closedM,ptype.closedN=(flags&closedN)===closedN;else if((flags&d3face)===d3face)ptype={type:"3dpolyfaces"},ptype.fvia=obj.fvia,ptype.fvib=obj.fvib;else{ptype={type:"2dline",isclosed:(flags&closedM)===closedM}}return"cnmb"in obj&&(ptype.cnmb=obj.cnmb),"lnam"in obj&&(ptype.lnam=obj.lnam),ptype},translateCurrent=(obj,layers,parts,options)=>{if(null===obj)return null;const type=obj.type,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if("2dline"===type)return((obj,layers,parts,options)=>{obj.vlen=parts.length,obj.pptxs=[],obj.pptys=[],obj.bulgs=[];for(const part of parts)obj.pptxs.push(part.vec[0]),obj.pptys.push(part.vec[1]),obj.bulgs.push(part.bulg);return obj.isclosed?obj.lflg=parseInt("00000000000000001",2):obj.lflg=0,translatePath2D(obj,layers,options),null})(obj,layers,parts,options);if("3dline"===type)return null;if("3dpolymesh"===type){const facets=((meshM,meshN,parts,color,options)=>{const getVector=(x,y)=>parts[(x-1)*meshN+(y-1)].vec,facets=[];if(meshM*meshN!==parts.length)return facets;if(meshM<2|meshN<2)return facets;let i=1;for(;i{const faces=[];if(meshM+meshN!==parts.length)return faces;let i=meshM;for(;i0&&(part=parts[indexes[0]-1],vertices.push(part.vec),indexes[1]>0&&(part=parts[indexes[1]-1],vertices.push(part.vec),indexes[2]>0&&(part=parts[indexes[2]-1],vertices.push(part.vec),indexes[3]>0&&(part=parts[indexes[3]-1],vertices.push(part.vec))))),vertices.length>2){1===options.dxf.angdir&&(vertices=vertices.reverse());const polygon=index$7.create(vertices);faces.push(polygon)}i++}return faces})(obj.fvia,obj.fvib,parts,0,options);parts=faces}const name=obj.name;let script=` const ${name}_polygons = [\n`;for(const polygon of parts)script+=" "+translatePolygon(polygon)+",\n";return script+=` ]\n let ${name} = geom3.create(${name}_polygons)\n`,color&&(script+=` ${name}.color = [${color}]\n`),obj.script=script,addToLayer(obj,layers),null},saveVariable=(obj,options)=>{if("$ANGDIR"===(obj.name||"Unknown"))"lflg"in obj&&(options.dxf.angdir=obj.lflg)},handleError=(reader,error)=>{if(!0===reader.options.strict)throw error;console.log(`error: line ${error.line}, column ${error.column}, bad character [${error.c}]`)},handleStart=(reader,data)=>{},handleEnd=(reader,data)=>{},handleEntity=(reader,group,value)=>{let obj=null;switch(value){case"LAYER":obj={type:"layer"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(67)]=0,reader.objstack.push(obj);break;case"LINE":obj={type:"line"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=0,reader.objstack.push(obj);break;case"LWPOLYLINE":obj={type:"lwpolyline"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(38)]=0,obj[getTLA(39)]=0,obj[getTLA(43)]=0,obj[getTLA(70)]=0,obj[getTLA(90)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"MESH":obj={type:"mesh"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(91)]=0,obj[getTLA(92)]=0,obj[getTLA(93)]=0,obj[getTLA(94)]=0,obj[getTLA(95)]=0,obj.state=0,reader.objstack.push(obj);break;case"POLYLINE":obj={type:"polyline"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(10)]=0,obj[getTLA(20)]=0,obj[getTLA(30)]=0,obj[getTLA(39)]=0,obj[getTLA(40)]=0,obj[getTLA(41)]=0,obj[getTLA(70)]=0,obj[getTLA(71)]=0,obj[getTLA(72)]=0,obj[getTLA(73)]=0,obj[getTLA(74)]=0,obj[getTLA(75)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"ARC":obj={type:"arc"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(39)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"CIRCLE":obj={type:"circle"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(39)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"ELLIPSE":obj={type:"ellipse"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"VERTEX":obj={type:"vertex"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(10)]=0,obj[getTLA(20)]=0,obj[getTLA(30)]=0,obj[getTLA(40)]=0,obj[getTLA(41)]=0,obj[getTLA(42)]=0,obj[getTLA(70)]=0,obj[getTLA(71)]=0,obj[getTLA(72)]=0,obj[getTLA(73)]=0,obj[getTLA(74)]=0,reader.objstack.push(obj);break;case"3DFACE":obj={type:"3dface"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(70)]=0,reader.objstack.push(obj);break;case"SEQEND":obj={type:"seqend"},reader.objstack.push(obj);break;default:obj={},reader.objstack.push(obj)}},handleVariable=(reader,group,value)=>{const obj={type:"variable",name:value};reader.objstack.push(obj)},handleInt=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleDouble=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleXcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("lwpolyline"===obj.type?(void 0===obj.pptxs&&(obj.pptxs=[],obj.bulgs=[]),obj.pptxs.push(parseFloat(value)),obj.bulgs.push(0)):"mesh"===obj.type?(void 0===obj.pptxs&&(obj.pptxs=[]),obj.pptxs.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleYcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("lwpolyline"===obj.type||"mesh"===obj.type?(void 0===obj.pptys&&(obj.pptys=[]),obj.pptys.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleZcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("mesh"===obj.type?(void 0===obj.pptzs&&(obj.pptzs=[]),obj.pptzs.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleBulge=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("lwpolyline"===obj.type){const bulgs=obj.bulgs;if(void 0!==bulgs){obj.pptxs.length===bulgs.length&&(bulgs[bulgs.length-1]=parseFloat(value))}}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleLen=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("mesh"===obj.type){const state=obj.state;switch(group){case 91:obj[getTLA(group)]=parseFloat(value),obj.state=1;break;case 92:1===state?(obj.vlen=parseFloat(value),obj.state=2):(obj.plen=parseFloat(value),obj.state=6);break;case 93:obj[getTLA(group)]=parseFloat(value),obj.state=3;break;case 94:obj[getTLA(group)]=parseFloat(value),obj.state=4;break;case 95:obj[getTLA(group)]=parseFloat(value),obj.state=5;break;default:obj.state=7}}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleValue=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("mesh"===obj.type){switch(obj.state){case 3:void 0===obj.fvals&&(obj.fvals=[]),obj.fvals.push(parseFloat(value));break;case 4:void 0===obj.evals&&(obj.evals=[]),obj.evals.push(parseFloat(value))}}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleString=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=value),reader.objstack.push(obj)},handleName=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&void 0===obj[getTLA(group)]&&(obj[getTLA(group)]=value),reader.objstack.push(obj)},createReader=(src,options)=>{const dxfreader=new DxfReader(options);return dxfreader.on("error",handleError),dxfreader.on("start",handleStart),dxfreader.on("end",handleEnd),dxfreader.absorb(0,handleEntity),dxfreader.absorb(1,handleString),dxfreader.absorb(2,handleName),dxfreader.absorb(3,handleName),dxfreader.absorb(6,handleString),dxfreader.absorb(7,handleString),dxfreader.absorb(8,handleString),dxfreader.absorb(9,handleVariable),dxfreader.absorb(10,handleXcoord),dxfreader.absorb(11,handleDouble),dxfreader.absorb(12,handleDouble),dxfreader.absorb(13,handleDouble),dxfreader.absorb(20,handleYcoord),dxfreader.absorb(21,handleDouble),dxfreader.absorb(22,handleDouble),dxfreader.absorb(23,handleDouble),dxfreader.absorb(30,handleZcoord),dxfreader.absorb(31,handleDouble),dxfreader.absorb(32,handleDouble),dxfreader.absorb(33,handleDouble),dxfreader.absorb(39,handleDouble),dxfreader.absorb(40,handleDouble),dxfreader.absorb(41,handleDouble),dxfreader.absorb(42,handleBulge),dxfreader.absorb(50,handleDouble),dxfreader.absorb(51,handleDouble),dxfreader.absorb(62,handleInt),dxfreader.absorb(70,handleInt),dxfreader.absorb(71,handleInt),dxfreader.absorb(72,handleInt),dxfreader.absorb(73,handleInt),dxfreader.absorb(74,handleInt),dxfreader.absorb(75,handleInt),dxfreader.absorb(90,handleValue),dxfreader.absorb(91,handleLen),dxfreader.absorb(92,handleLen),dxfreader.absorb(93,handleLen),dxfreader.absorb(94,handleLen),dxfreader.absorb(95,handleLen),dxfreader.absorb(210,handleInt),dxfreader.absorb(220,handleInt),dxfreader.absorb(230,handleInt),dxfreader.objstack=[],dxfreader.objstack.push({type:"dxf"}),dxfreader.write(src),dxfreader.close(),dxfreader},instantiate=(src,options)=>{const objs=((reader,options)=>{const layers=[];let current=null;const polygons=[],objects=[],vectors=[];let p=null;for(const obj of reader.objstack)if(p=null,"type"in obj){switch(obj.type){case"dxf":break;case"layer":current=completeCurrent(objects,current,polygons,vectors),layers.push(obj);break;case"variable":case"seqend":current=completeCurrent(objects,current,polygons,vectors);break;case"3dface":p=instantiatePolygon(obj,layers,options),null===current&&(current=index$6.create());break;case"mesh":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateMesh(obj,layers,options));break;case"arc":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateArc(obj));break;case"circle":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateCircle(obj,layers,options));break;case"ellipse":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateEllipse(obj));break;case"line":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateLine(obj));break;case"polyline":current=completeCurrent(objects,current,polygons,vectors),null===current&&(current=getPolyType$1(obj));break;case"vertex":p=instantiateVector(obj);break;case"lwpolyline":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiatePath2D(obj))}index$7.isA(p)&&polygons.push(p),p&&"vec"in p&&3===p.vec.length&&vectors.push(p),p&&"vec"in p&&2===p.vec.length&&vectors.push(p)}return current=completeCurrent(objects,current,polygons,vectors),objects})(createReader(src,options),options);return objs},translate=(src,options)=>{const reader=createReader(src,options);let code=`// Produced by JSCAD IO Library : DXF Deserializer (${options.version})\n\n`;return code+=((reader,options)=>{const layers=[];let current=null,parts=[],numobjs=0,p=null;for(const obj of reader.objstack)if(p=null,"type"in obj){if("name"in obj){let name=obj.name;name=name.replace(/ /g,"_"),name=name.replace(/-/g,"_"),name=name.replace(/\./g,"_"),obj.name=name}else obj.name="jscad"+numobjs,numobjs+=1;switch(obj.type){case"dxf":break;case"layer":current=translateCurrent(current,layers,parts,options),parts=[],obj.objects=[],obj.lnam="layer"+layers.length,layers.push(obj);break;case"variable":current=translateCurrent(current,layers,parts,options),parts=[],saveVariable(obj,options);break;case"3dface":p=instantiatePolygon(obj,layers,options),null===current&&(current={type:"3dfaces"},current.name="jscad"+numobjs,numobjs+=1);break;case"mesh":current=translateCurrent(current,layers,parts,options),parts=[],translateMesh(obj,layers,options);break;case"arc":current=translateCurrent(current,layers,parts,options),parts=[],translateArc(obj,layers,options);break;case"circle":current=translateCurrent(current,layers,parts,options),parts=[],translateCircle(obj,layers,options);break;case"ellipse":current=translateCurrent(current,layers,parts,options),parts=[],translateEllipse(obj,layers,options);break;case"line":current=translateCurrent(current,layers,parts,options),parts=[],translateLine(obj,layers,options);break;case"polyline":current=translateCurrent(current,layers,parts,options),parts=[],null===current&&(current=getPolyType(obj),current.name="jscad"+numobjs,numobjs+=1);break;case"vertex":p=instantiateVector(obj);break;case"seqend":current=translateCurrent(current,layers,parts,options),parts=[];break;case"lwpolyline":current=translateCurrent(current,layers,parts,options),parts=[],translatePath2D(obj,layers,options)}index$7.isA(p)&&parts.push(p),p&&"vec"in p&&3===p.vec.length&&parts.push(p),p&&"vec"in p&&2===p.vec.length&&parts.push(p)}current=translateCurrent(current,layers,parts,options);let script="import * from '@jscad/modeling'\n\nexport const main = () => {\n let layers = []\n return layers.concat(";return layers.forEach((layer=>{const name=layer.lnam||"Unknown";script+=`${name}(),`})),script+="[])\n}\n",script+="\nconst createPolygon = (listofpoints, color) => {\n let polygon = poly3.create(listofpoints)\n return colorize(color, polygon)\n}\n",layers.forEach((layer=>{script+=(layer=>{let script=`const ${layer.lnam||"Unknown"} = () => {\n`;for(const object of layer.objects)script+=object.script;script+=" return [";for(const object of layer.objects)script+=object.name+",";return script+="]\n}\n",script})(layer)})),script})(reader,options),code},deserialize=(options,src)=>{const defaults={filename:"dxf",version:"3.0.0-alpha.0",output:"script",strict:!0,colorindex:colorIndex,dxf:{angdir:0,insunits:4,pfacevmax:4}};return"script"===(options=Object.assign({},defaults,options)).output?translate(src,options):instantiate(src,options)},mimeType="image/vnd.dxf";export{deserialize,mimeType}; +const dxfMap=new Map([[0,"etyp"],[1,"text"],[2,"name"],[3,"nam1"],[5,"hdle"],[6,"ltyp"],[7,"lsty"],[8,"lnam"],[9,"vari"],[10,"pptx"],[11,"sptx"],[12,"tptx"],[13,"fptx"],[20,"ppty"],[21,"spty"],[22,"tpty"],[23,"fpty"],[30,"pptz"],[31,"sptz"],[32,"tptz"],[33,"fptz"],[38,"elev"],[39,"lthk"],[40,"swid"],[41,"ewid"],[42,"bulg"],[43,"cwid"],[48,"lscl"],[50,"ang0"],[51,"ang1"],[60,"visb"],[62,"cnmb"],[67,"spac"],[70,"lflg"],[71,"fvia"],[72,"fvib"],[73,"fvic"],[74,"fvid"],[75,"cflg"],[90,"vlen"],[91,"slen"],[92,"plen"],[93,"flen"],[94,"elen"],[95,"clen"],[100,"sbnm"],[210,"etrx"],[220,"etry"],[230,"etrz"]]),getTLA=group=>dxfMap.get(group),colorIndex=[[0,0,0,255],[255,0,0,255],[255,255,0,255],[0,255,0,255],[0,255,255,255],[0,0,255,255],[255,0,255,255],[255,255,255,255],[128,128,128,255],[192,192,192,255],[255,0,0,255],[255,127,127,255],[165,0,0,255],[165,82,82,255],[127,0,0,255],[127,63,63,255],[76,0,0,255],[76,38,38,255],[38,0,0,255],[38,19,19,255],[255,63,0,255],[255,159,127,255],[165,41,0,255],[165,103,82,255],[127,31,0,255],[127,79,63,255],[76,19,0,255],[76,47,38,255],[38,9,0,255],[38,28,19,255],[255,127,0,255],[255,191,127,255],[165,82,0,255],[165,124,82,255],[127,63,0,255],[127,95,63,255],[76,38,0,255],[76,57,38,255],[38,19,0,255],[38,28,19,255],[255,191,0,255],[255,223,127,255],[165,124,0,255],[165,145,82,255],[127,95,0,255],[127,111,63,255],[76,57,0,255],[76,66,38,255],[38,28,0,255],[38,33,19,255],[255,255,0,255],[255,255,127,255],[165,165,0,255],[165,165,82,255],[127,127,0,255],[127,127,63,255],[76,76,0,255],[76,76,38,255],[38,38,0,255],[38,38,19,255],[191,255,0,255],[223,255,127,255],[124,165,0,255],[145,165,82,255],[95,127,0,255],[111,127,63,255],[57,76,0,255],[66,76,38,255],[28,38,0,255],[33,38,19,255],[127,255,0,255],[191,255,127,255],[82,165,0,255],[124,165,82,255],[63,127,0,255],[95,127,63,255],[38,76,0,255],[57,76,38,255],[19,38,0,255],[28,38,19,255],[63,255,0,255],[159,255,127,255],[41,165,0,255],[103,165,82,255],[31,127,0,255],[79,127,63,255],[19,76,0,255],[47,76,38,255],[9,38,0,255],[23,38,19,255],[0,255,0,255],[125,255,127,255],[0,165,0,255],[82,165,82,255],[0,127,0,255],[63,127,63,255],[0,76,0,255],[38,76,38,255],[0,38,0,255],[19,38,19,255],[0,255,63,255],[127,255,159,255],[0,165,41,255],[82,165,103,255],[0,127,31,255],[63,127,79,255],[0,76,19,255],[38,76,47,255],[0,38,9,255],[19,88,23,255],[0,255,127,255],[127,255,191,255],[0,165,82,255],[82,165,124,255],[0,127,63,255],[63,127,95,255],[0,76,38,255],[38,76,57,255],[0,38,19,255],[19,88,28,255],[0,255,191,255],[127,255,223,255],[0,165,124,255],[82,165,145,255],[0,127,95,255],[63,127,111,255],[0,76,57,255],[38,76,66,255],[0,38,28,255],[19,88,88,255],[0,255,255,255],[127,255,255,255],[0,165,165,255],[82,165,165,255],[0,127,127,255],[63,127,127,255],[0,76,76,255],[38,76,76,255],[0,38,38,255],[19,88,88,255],[0,191,255,255],[127,223,255,255],[0,124,165,255],[82,145,165,255],[0,95,127,255],[63,111,217,255],[0,57,76,255],[38,66,126,255],[0,28,38,255],[19,88,88,255],[0,127,255,255],[127,191,255,255],[0,82,165,255],[82,124,165,255],[0,63,127,255],[63,95,127,255],[0,38,76,255],[38,57,126,255],[0,19,38,255],[19,28,88,255],[0,63,255,255],[127,159,255,255],[0,41,165,255],[82,103,165,255],[0,31,127,255],[63,79,127,255],[0,19,76,255],[38,47,126,255],[0,9,38,255],[19,23,88,255],[0,0,255,255],[127,127,255,255],[0,0,165,255],[82,82,165,255],[0,0,127,255],[63,63,127,255],[0,0,76,255],[38,38,126,255],[0,0,38,255],[19,19,88,255],[63,0,255,255],[159,127,255,255],[41,0,165,255],[103,82,165,255],[31,0,127,255],[79,63,127,255],[19,0,76,255],[47,38,126,255],[9,0,38,255],[23,19,88,255],[127,0,255,255],[191,127,255,255],[165,0,82,255],[124,82,165,255],[63,0,127,255],[95,63,127,255],[38,0,76,255],[57,38,126,255],[19,0,38,255],[28,19,88,255],[191,0,255,255],[223,127,255,255],[124,0,165,255],[142,82,165,255],[95,0,127,255],[111,63,127,255],[57,0,76,255],[66,38,76,255],[28,0,38,255],[88,19,88,255],[255,0,255,255],[255,127,255,255],[165,0,165,255],[165,82,165,255],[127,0,127,255],[127,63,127,255],[76,0,76,255],[76,38,76,255],[38,0,38,255],[88,19,88,255],[255,0,191,255],[255,127,223,255],[165,0,124,255],[165,82,145,255],[127,0,95,255],[127,63,111,255],[76,0,57,255],[76,38,66,255],[38,0,28,255],[88,19,88,255],[255,0,127,255],[255,127,191,255],[165,0,82,255],[165,82,124,255],[127,0,63,255],[127,63,95,255],[76,0,38,255],[76,38,57,255],[38,0,19,255],[88,19,28,255],[255,0,63,255],[255,127,159,255],[165,0,41,255],[165,82,103,255],[127,0,31,255],[127,63,79,255],[76,0,19,255],[76,38,47,255],[38,0,9,255],[88,19,23,255],[0,0,0,255],[101,101,101,255],[102,102,102,255],[153,153,153,255],[204,204,204,255],[255,255,255,255]];class DxfReader{constructor(options){this.options=Object.assign({},{strict:!1,track:!0},options),this.trackPosition=this.options.track,this.trackPosition&&(this.line=0,this.column=0,this.c=0)}on(state,callback){return this["on"+state]=callback,this}absorb(group,callback){return void 0===this.absorbers&&(this.absorbers=new Map),this.absorbers.set(group,callback),this}write(data){return parse(this,data),this}close(){return this.isclosed=!0,this}}const emiterror=(reader,er)=>(reader.trackPosition&&(er+=`\nLine: ${reader.line}\nColumn: ${reader.column}\nChar: ${reader.c}`),er=new Error(er),reader.error=er,emitstate(reader,"onerror",er)),emitend=reader=>emitstate(reader,"onend",reader.data),emitstate=(reader,state,data)=>{const onhandler=state.toString();return reader[onhandler]&&reader[onhandler](reader,data),reader},parse=(reader,data)=>{if(reader.error)throw reader.error;if(reader.isclosed)return emiterror(reader,"Cannot write after close");if((reader=>{emitstate(reader,"onstart",reader.data)})(reader),null===data)return emitend(reader);reader.group=null,reader.value=null,reader.error=null,reader.position=0,reader.line=0,reader.column=0;let i=0,c="",l="";for(;null===reader.error&&(c=charAt(data,i++),c);)reader.trackPosition&&(reader.position++,"\n"===c?(reader.line++,reader.column=0):reader.column++),"\n"===c?(parseLine(reader,l),l=""):l+=c;return emitend(reader),reader},parseLine=(reader,line)=>{line=line.trim(),null===reader.group?(setDxfGroup(reader,line),reader.value=null):setDxfValue(reader,line),null!==reader.group&&null!==reader.value&&(((reader,group,value)=>{if(void 0!==reader.absorbers){const absorber=reader.absorbers.get(group);void 0!==absorber&&absorber(reader,group,value)}})(reader,reader.group,reader.value),reader.group=null,reader.value=null)},setDxfGroup=(reader,line)=>{const code=parseInt(line);isNaN(code)?(emiterror(reader,"Invalid group (int)"),reader.group=null):reader.group=code},setDxfValue=(reader,line)=>{reader.options.strict,reader.value=line},charAt=(data,i)=>data&&data.length>i?data.charAt(i):"",clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS$1=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};var index$b=Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(value=radius,constant=0,!(Number.isFinite(value)&&value>constant))throw new Error("radius must be greater than zero");var value,constant;if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS$1*EPS$1)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps)),point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})},line=points=>{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},findLayer=(obj,layers)=>{const lname=obj.lnam||"0";for(const layer of layers)if(layer.name===lname)return layer;return null},getColorNumber=(obj,layers)=>{let cn=obj.cnmb||-1;if(256===cn){cn=-1;const layer=findLayer(obj,layers);null!==layer&&(cn=layer.cnmb||-1)}return cn},getColor=(index,colorindex)=>{if(index<1)return null;index=((num,mod)=>{const remain=num%mod;return Math.floor(remain>=0?remain:remain+mod)})(index,colorindex.length);const color=colorindex[index];return[color[0]/255,color[1]/255,color[2]/255,color[3]/255]},instantiatePolygon=(obj,layers,options)=>{const vertices=[];if(vertices.push(index$d.fromValues(obj.pptx,obj.ppty,obj.pptz)),vertices.push(index$d.fromValues(obj.sptx,obj.spty,obj.sptz)),vertices.push(index$d.fromValues(obj.tptx,obj.tpty,obj.tptz)),obj.fptx){let pushit=!1;obj.tptx!==obj.fptx&&(pushit=!0),obj.tpty!==obj.fpty&&(pushit=!0),obj.tptz!==obj.fptz&&(pushit=!0),pushit&&vertices.push(index$d.fromValues(obj.fptx,obj.fpty,obj.fptz))}const cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygon=index$7.create(vertices);return color&&(polygon.color=color),polygon},instantiateLine=(obj,layers,options)=>{if(obj.pptz===obj.sptz&&0===obj.pptz){const p1=index$b.fromValues(obj.pptx,obj.ppty),p2=index$b.fromValues(obj.sptx,obj.spty);return line([p1,p2])}const p1=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),p2=index$d.fromValues(obj.sptx,obj.spty,obj.sptz);return line([p1,p2])},instantiateVector=obj=>{const d3line=parseInt("00000000000100000",2),d3mesh=parseInt("00000000001000000",2),d3face=parseInt("00000000010000000",2),flags=obj.lflg,vtype={};return(flags&d3line)===d3line||(flags&d3mesh)===d3mesh?vtype.vec=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz):(flags&d3face)===d3face?(vtype.vec=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),vtype.fvia=obj.fvia,vtype.fvib=obj.fvib,vtype.fvic=obj.fvic,vtype.fvid=obj.fvid):(vtype.vec=index$b.fromValues(obj.pptx,obj.ppty),vtype.bulg=obj.bulg),vtype},addSection=(path,x1,y1,bulg)=>{if(0===bulg)path=index$5.appendPoints([[x1,y1]],path);else{const points=index$5.toPoints(path),prev=points[points.length-1],curr=index$b.fromValues(x1,y1),r=index$b.distance(prev,curr)*((1+Math.pow(bulg,2))/(4*bulg)),clockwise=bulg<0,large=!1,d=4*Math.atan(bulg),res=16;path=index$5.appendArc({endpoint:[x1,y1],radius:[r,r],xaxisrotation:d,clockwise:clockwise,large:large,segments:res},path)}return path},instantiatePath2D=(obj,layers,options)=>{const closed=parseInt("00000000000000001",2),vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,bulgs=obj.bulgs,flags=obj.lflg;let path=index$5.create();const isclosed=(flags&closed)===closed;return vlen!==pptxs.length||vlen!==pptys.length||vlen!==bulgs.length||(pptxs.forEach(((item,index,array)=>{let bulg=0;index>0&&(bulg=bulgs[index-1]),path=addSection(path,pptxs[index],pptys[index],bulg)})),isclosed&&!path.isClosed&&(path=addSection(path,pptxs[0],pptys[0],bulgs[vlen-1]),path=index$5.close(path))),path},instantiateArc=(obj,layers,options)=>{obj.lthk;const pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid;let ang0=obj.ang0;ang0*=.017453292519943295;let ang1=obj.ang1;ang1*=.017453292519943295;return arc({center:[pptx,ppty],radius:swid,startAngle:ang0,endAngle:ang1,segments:16})},instantiateCircle=(obj,layers,options)=>{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===lthk){const cag=circle({center:[pptx,ppty],radius:swid,segments:16});return color&&(cag.color=color),cag}const csg=circle({center:[pptx,ppty],radius:swid,segments:16}).extrude({offset:[0,0,lthk]});return color&&(csg.color=color),csg},instantiateEllipse=(obj,layers,options)=>{const pptx=obj.pptx,ppty=obj.ppty,pptz=obj.pptz,sptx=obj.sptx,spty=obj.spty,sptz=obj.sptz,swid=obj.swid;if(0===pptz&&0===sptz){const center=index$b.fromValues(0,0),mjaxis=index$b.fromValues(sptx,spty),rx=index$b.distance(center,mjaxis),ry=rx*swid;let angle=180*Math.atan2(spty,sptx)/Math.PI;angle<1e-5&&(angle=0),angle*=.017453292519943295;const cag=ellipse({center:[0,0],radius:[rx,ry],segments:16}),matrix=index$c.fromZRotation(index$c.create(),angle);return index$c.multiply(matrix,matrix,index$c.fromTranslation(index$c.create(),[pptx,ppty,0])),index$a.transform(matrix,cag)}},instantiateMesh=(obj,layers,options)=>{const vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,pptzs=obj.pptzs,flen=obj.flen,fvals=obj.fvals,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygons=[];if(vlen===pptxs.length&&vlen===pptys.length&&vlen===pptzs.length&&flen===fvals.length){const faces=(fvals=>{const faces=[];let vi=0;for(;vi0;)face.push(fvals[vi++]),fi--;faces.push(face)}return faces})(fvals),points=((pptxs,pptys,pptzs)=>{const points=[];let vi=0;for(;vi{const closedM=parseInt("00000000000000001",2),d3line=parseInt("00000000000001000",2),d3mesh=parseInt("00000000000010000",2),closedN=parseInt("00000000000100000",2),d3face=parseInt("00000000001000000",2),flags=obj.lflg;let ptype=null;return(flags&d3line)===d3line?ptype=null:(flags&d3mesh)===d3mesh||(flags&d3face)===d3face?(ptype=index$6.create(),ptype.closedM=(flags&closedM)===closedM,ptype.closedN=(flags&closedN)===closedN):(ptype=index$5.create(),ptype.closedM=(flags&closedM)===closedM),"cnmb"in obj&&(ptype.cnmb=obj.cnmb),ptype},completeCurrent=(objects,baseobj,polygons,vectors,options)=>{if(index$5.isA(baseobj)){const points=vectors.map((vector=>vector.vec));objects.push(index$5.fromPoints({closed:baseobj.closed},points))}return index$6.isA(baseobj)&&objects.push(index$6.create(polygons)),null},translateVector2D=vector=>`${vector[0]},${vector[1]}`,translateVector3D=vector=>`${vector[0]},${vector[1]},${vector[2]}`,translatePolygon=polygon=>{const vertices=index$7.toVertices(polygon);let script="createPolygon([";return vertices.forEach((vertice=>{script+=`[${translateVector3D(vertice)}],`})),script+=`],${translateColor(polygon)})`,script},translateColor=polygon=>{let script="null";if("color"in polygon){const rgb=polygon.color;script=`[${rgb[0]},${rgb[1]},${rgb[2]},${rgb[3]}]`}return script},translateLine=(obj,layers,options)=>{const name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);let script="";if(!obj.pptz||obj.pptz===obj.sptz&&0===obj.pptz){const p1=index$b.fromValues(obj.pptx,obj.ppty),p2=index$b.fromValues(obj.sptx,obj.spty);script=` let ${name} = line([[${translateVector2D(p1)}],[${translateVector2D(p2)}]])\n`}else{const p1=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),p2=index$d.fromValues(obj.sptx,obj.spty,obj.sptz);script=` let ${name} = line([[${translateVector3D(p1)}],[${translateVector3D(p2)}]])\n`}color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateSection=(name,x1,y1,bulg,px,py)=>{if(0===bulg)return`path2.appendPoints([[${x1},${y1}]], ${name})\n`;const prev=index$b.fromValues(px,py),curr=index$b.fromValues(x1,y1),r=index$b.distance(prev,curr)*((1+Math.pow(bulg,2))/(4*bulg)),clockwise=bulg<0;return`path2.appendArc({endpoint: [${x1},${y1}],radius: [${r},${r}],xaxisrotation: ${4*Math.atan(bulg)},clockwise: ${clockwise},large: false,segments: 16}, ${name})\n`},translatePath2D=(obj,layers,options)=>{const closed=parseInt("00000000000000001",2),vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,bulgs=obj.bulgs,flags=obj.lflg,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);let script=` let ${name} = path2.create()\n`;const isclosed=(flags&closed)===closed;if(vlen===pptxs.length&&vlen===pptys.length&&vlen===bulgs.length){script+=` ${name} = path2.appendPoints([[${pptxs[0]}, ${pptys[0]}]], ${name})\n`;for(let i=0;i{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid;let ang0=obj.ang0,ang1=obj.ang1;const name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);ang0*=.017453292519943295,ang1*=.017453292519943295;if(0===lthk){let script=` let ${name} = arc({center: [${pptx}, ${ppty}], radius: ${swid}, startAngle: ${ang0}, endAngle: ${ang1}, segements: 16})\n`;return color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,void addToLayer(obj,layers)}let script=` let ${name} = arc({center: [${pptx}, ${ppty}], radius: ${swid}, startAngle: ${ang0}, endAngle: ${ang1}, segements: 16})\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateCircle=(obj,layers,options)=>{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===lthk){let script=` let ${name} = circle({center: [${pptx}, ${ppty}], radius: ${swid}, segments: 16})\n`;return color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,void addToLayer(obj,layers)}let script=` let ${name} = circle({center: [${pptx}, ${ppty}], radius: ${swid}, segments: 16}).extrude({offset: [0,0,${lthk}]}))\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateEllipse=(obj,layers,options)=>{const pptx=obj.pptx,ppty=obj.ppty,pptz=obj.pptz,sptx=obj.sptx,spty=obj.spty,sptz=obj.sptz,swid=obj.swid,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===pptz&&0===sptz){const center=index$b.fromValues(0,0),mjaxis=index$b.fromValues(sptx,spty),rx=index$b.distance(center,mjaxis);let script=` let ${name} = ellipse({center: [0, 0, 0], radius: [${rx}, ${rx*swid}], segments: 16})\n let ${name}matrix = mat4.multiply(mat4.create(), mat4.fromTranslation(mat4.create(), [${pptx}, ${ppty}, 0]), mat4.fromZRotation(mat4.create(), ${Math.atan2(spty,sptx)}))\n ${name} = geom2.transform(${name}matrix, ${name})\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)}},translateMesh=(obj,layers,options)=>{const vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,pptzs=obj.pptzs,flen=obj.flen,fvals=obj.fvals,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygons=[];if(vlen===pptxs.length&&vlen===pptys.length&&vlen===pptzs.length)if(flen===fvals.length){const faces=(fvals=>{const faces=[];let vi=0;for(;vi0;)face.push(fvals[vi++]),fi--;faces.push(face)}return faces})(fvals),points=((pptxs,pptys,pptzs)=>{const points=[];let vi=0;for(;vi{let layer=findLayer(obj,layers);null===layer&&(layer=(layers=>{for(const layer of layers)if("0"===layer.name)return layer;const layer={type:"layer",lnam:"layer0",name:"0",lscl:1,visb:0,spac:0,objects:[]};return layers.push(layer),layer})(layers)),"objects"in layer||(layer.objects=[]),layer.objects.push(obj)},getPolyType=obj=>{const closedM=parseInt("00000000000000001",2),d3line=parseInt("00000000000001000",2),d3mesh=parseInt("00000000000010000",2),closedN=parseInt("00000000000100000",2),d3face=parseInt("00000000001000000",2),flags=obj.lflg;let ptype=null;if((flags&d3line)===d3line){ptype={type:"3dline",isclosed:(flags&closedM)===closedM}}else if((flags&d3mesh)===d3mesh)ptype={type:"3dpolymesh"},ptype.fvia=obj.fvia,ptype.fvib=obj.fvib,ptype.closedM=(flags&closedM)===closedM,ptype.closedN=(flags&closedN)===closedN;else if((flags&d3face)===d3face)ptype={type:"3dpolyfaces"},ptype.fvia=obj.fvia,ptype.fvib=obj.fvib;else{ptype={type:"2dline",isclosed:(flags&closedM)===closedM}}return"cnmb"in obj&&(ptype.cnmb=obj.cnmb),"lnam"in obj&&(ptype.lnam=obj.lnam),ptype},translateCurrent=(obj,layers,parts,options)=>{if(null===obj)return null;const type=obj.type,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if("2dline"===type)return((obj,layers,parts,options)=>{obj.vlen=parts.length,obj.pptxs=[],obj.pptys=[],obj.bulgs=[];for(const part of parts)obj.pptxs.push(part.vec[0]),obj.pptys.push(part.vec[1]),obj.bulgs.push(part.bulg);return obj.isclosed?obj.lflg=parseInt("00000000000000001",2):obj.lflg=0,translatePath2D(obj,layers,options),null})(obj,layers,parts,options);if("3dline"===type)return null;if("3dpolymesh"===type){const facets=((meshM,meshN,parts,color,options)=>{const getVector=(x,y)=>parts[(x-1)*meshN+(y-1)].vec,facets=[];if(meshM*meshN!==parts.length)return facets;if(meshM<2|meshN<2)return facets;let i=1;for(;i{const faces=[];if(meshM+meshN!==parts.length)return faces;let i=meshM;for(;i0&&(part=parts[indexes[0]-1],vertices.push(part.vec),indexes[1]>0&&(part=parts[indexes[1]-1],vertices.push(part.vec),indexes[2]>0&&(part=parts[indexes[2]-1],vertices.push(part.vec),indexes[3]>0&&(part=parts[indexes[3]-1],vertices.push(part.vec))))),vertices.length>2){1===options.dxf.angdir&&(vertices=vertices.reverse());const polygon=index$7.create(vertices);faces.push(polygon)}i++}return faces})(obj.fvia,obj.fvib,parts,0,options);parts=faces}const name=obj.name;let script=` const ${name}_polygons = [\n`;for(const polygon of parts)script+=" "+translatePolygon(polygon)+",\n";return script+=` ]\n let ${name} = geom3.create(${name}_polygons)\n`,color&&(script+=` ${name}.color = [${color}]\n`),obj.script=script,addToLayer(obj,layers),null},saveVariable=(obj,options)=>{if("$ANGDIR"===(obj.name||"Unknown"))"lflg"in obj&&(options.dxf.angdir=obj.lflg)},handleError=(reader,error)=>{if(!0===reader.options.strict)throw error;console.log(`error: line ${error.line}, column ${error.column}, bad character [${error.c}]`)},handleStart=(reader,data)=>{},handleEnd=(reader,data)=>{},handleEntity=(reader,group,value)=>{let obj=null;switch(value){case"LAYER":obj={type:"layer"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(67)]=0,reader.objstack.push(obj);break;case"LINE":obj={type:"line"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=0,reader.objstack.push(obj);break;case"LWPOLYLINE":obj={type:"lwpolyline"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(38)]=0,obj[getTLA(39)]=0,obj[getTLA(43)]=0,obj[getTLA(70)]=0,obj[getTLA(90)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"MESH":obj={type:"mesh"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(91)]=0,obj[getTLA(92)]=0,obj[getTLA(93)]=0,obj[getTLA(94)]=0,obj[getTLA(95)]=0,obj.state=0,reader.objstack.push(obj);break;case"POLYLINE":obj={type:"polyline"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(10)]=0,obj[getTLA(20)]=0,obj[getTLA(30)]=0,obj[getTLA(39)]=0,obj[getTLA(40)]=0,obj[getTLA(41)]=0,obj[getTLA(70)]=0,obj[getTLA(71)]=0,obj[getTLA(72)]=0,obj[getTLA(73)]=0,obj[getTLA(74)]=0,obj[getTLA(75)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"ARC":obj={type:"arc"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(39)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"CIRCLE":obj={type:"circle"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(39)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"ELLIPSE":obj={type:"ellipse"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"VERTEX":obj={type:"vertex"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(10)]=0,obj[getTLA(20)]=0,obj[getTLA(30)]=0,obj[getTLA(40)]=0,obj[getTLA(41)]=0,obj[getTLA(42)]=0,obj[getTLA(70)]=0,obj[getTLA(71)]=0,obj[getTLA(72)]=0,obj[getTLA(73)]=0,obj[getTLA(74)]=0,reader.objstack.push(obj);break;case"3DFACE":obj={type:"3dface"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(70)]=0,reader.objstack.push(obj);break;case"SEQEND":obj={type:"seqend"},reader.objstack.push(obj);break;default:obj={},reader.objstack.push(obj)}},handleVariable=(reader,group,value)=>{const obj={type:"variable",name:value};reader.objstack.push(obj)},handleInt=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleDouble=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleXcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("lwpolyline"===obj.type?(void 0===obj.pptxs&&(obj.pptxs=[],obj.bulgs=[]),obj.pptxs.push(parseFloat(value)),obj.bulgs.push(0)):"mesh"===obj.type?(void 0===obj.pptxs&&(obj.pptxs=[]),obj.pptxs.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleYcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("lwpolyline"===obj.type||"mesh"===obj.type?(void 0===obj.pptys&&(obj.pptys=[]),obj.pptys.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleZcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("mesh"===obj.type?(void 0===obj.pptzs&&(obj.pptzs=[]),obj.pptzs.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleBulge=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("lwpolyline"===obj.type){const bulgs=obj.bulgs;if(void 0!==bulgs){obj.pptxs.length===bulgs.length&&(bulgs[bulgs.length-1]=parseFloat(value))}}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleLen=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("mesh"===obj.type){const state=obj.state;switch(group){case 91:obj[getTLA(group)]=parseFloat(value),obj.state=1;break;case 92:1===state?(obj.vlen=parseFloat(value),obj.state=2):(obj.plen=parseFloat(value),obj.state=6);break;case 93:obj[getTLA(group)]=parseFloat(value),obj.state=3;break;case 94:obj[getTLA(group)]=parseFloat(value),obj.state=4;break;case 95:obj[getTLA(group)]=parseFloat(value),obj.state=5;break;default:obj.state=7}}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleValue=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("mesh"===obj.type){switch(obj.state){case 3:void 0===obj.fvals&&(obj.fvals=[]),obj.fvals.push(parseFloat(value));break;case 4:void 0===obj.evals&&(obj.evals=[]),obj.evals.push(parseFloat(value))}}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleString=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=value),reader.objstack.push(obj)},handleName=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&void 0===obj[getTLA(group)]&&(obj[getTLA(group)]=value),reader.objstack.push(obj)},createReader=(src,options)=>{const dxfreader=new DxfReader(options);return dxfreader.on("error",handleError),dxfreader.on("start",handleStart),dxfreader.on("end",handleEnd),dxfreader.absorb(0,handleEntity),dxfreader.absorb(1,handleString),dxfreader.absorb(2,handleName),dxfreader.absorb(3,handleName),dxfreader.absorb(6,handleString),dxfreader.absorb(7,handleString),dxfreader.absorb(8,handleString),dxfreader.absorb(9,handleVariable),dxfreader.absorb(10,handleXcoord),dxfreader.absorb(11,handleDouble),dxfreader.absorb(12,handleDouble),dxfreader.absorb(13,handleDouble),dxfreader.absorb(20,handleYcoord),dxfreader.absorb(21,handleDouble),dxfreader.absorb(22,handleDouble),dxfreader.absorb(23,handleDouble),dxfreader.absorb(30,handleZcoord),dxfreader.absorb(31,handleDouble),dxfreader.absorb(32,handleDouble),dxfreader.absorb(33,handleDouble),dxfreader.absorb(39,handleDouble),dxfreader.absorb(40,handleDouble),dxfreader.absorb(41,handleDouble),dxfreader.absorb(42,handleBulge),dxfreader.absorb(50,handleDouble),dxfreader.absorb(51,handleDouble),dxfreader.absorb(62,handleInt),dxfreader.absorb(70,handleInt),dxfreader.absorb(71,handleInt),dxfreader.absorb(72,handleInt),dxfreader.absorb(73,handleInt),dxfreader.absorb(74,handleInt),dxfreader.absorb(75,handleInt),dxfreader.absorb(90,handleValue),dxfreader.absorb(91,handleLen),dxfreader.absorb(92,handleLen),dxfreader.absorb(93,handleLen),dxfreader.absorb(94,handleLen),dxfreader.absorb(95,handleLen),dxfreader.absorb(210,handleInt),dxfreader.absorb(220,handleInt),dxfreader.absorb(230,handleInt),dxfreader.objstack=[],dxfreader.objstack.push({type:"dxf"}),dxfreader.write(src),dxfreader.close(),dxfreader},instantiate=(src,options)=>{const objs=((reader,options)=>{const layers=[];let current=null;const polygons=[],objects=[],vectors=[];let p=null;for(const obj of reader.objstack)if(p=null,"type"in obj){switch(obj.type){case"dxf":break;case"layer":current=completeCurrent(objects,current,polygons,vectors),layers.push(obj);break;case"variable":case"seqend":current=completeCurrent(objects,current,polygons,vectors);break;case"3dface":p=instantiatePolygon(obj,layers,options),null===current&&(current=index$6.create());break;case"mesh":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateMesh(obj,layers,options));break;case"arc":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateArc(obj));break;case"circle":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateCircle(obj,layers,options));break;case"ellipse":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateEllipse(obj));break;case"line":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateLine(obj));break;case"polyline":current=completeCurrent(objects,current,polygons,vectors),null===current&&(current=getPolyType$1(obj));break;case"vertex":p=instantiateVector(obj);break;case"lwpolyline":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiatePath2D(obj))}index$7.isA(p)&&polygons.push(p),p&&"vec"in p&&3===p.vec.length&&vectors.push(p),p&&"vec"in p&&2===p.vec.length&&vectors.push(p)}return current=completeCurrent(objects,current,polygons,vectors),objects})(createReader(src,options),options);return objs},translate=(src,options)=>{const reader=createReader(src,options);let code=`// Produced by JSCAD IO Library : DXF Deserializer (${options.version})\n\n`;return code+=((reader,options)=>{const layers=[];let current=null,parts=[],numobjs=0,p=null;for(const obj of reader.objstack)if(p=null,"type"in obj){if("name"in obj){let name=obj.name;name=name.replace(/ /g,"_"),name=name.replace(/-/g,"_"),name=name.replace(/\./g,"_"),obj.name=name}else obj.name="jscad"+numobjs,numobjs+=1;switch(obj.type){case"dxf":break;case"layer":current=translateCurrent(current,layers,parts,options),parts=[],obj.objects=[],obj.lnam="layer"+layers.length,layers.push(obj);break;case"variable":current=translateCurrent(current,layers,parts,options),parts=[],saveVariable(obj,options);break;case"3dface":p=instantiatePolygon(obj,layers,options),null===current&&(current={type:"3dfaces"},current.name="jscad"+numobjs,numobjs+=1);break;case"mesh":current=translateCurrent(current,layers,parts,options),parts=[],translateMesh(obj,layers,options);break;case"arc":current=translateCurrent(current,layers,parts,options),parts=[],translateArc(obj,layers,options);break;case"circle":current=translateCurrent(current,layers,parts,options),parts=[],translateCircle(obj,layers,options);break;case"ellipse":current=translateCurrent(current,layers,parts,options),parts=[],translateEllipse(obj,layers,options);break;case"line":current=translateCurrent(current,layers,parts,options),parts=[],translateLine(obj,layers,options);break;case"polyline":current=translateCurrent(current,layers,parts,options),parts=[],null===current&&(current=getPolyType(obj),current.name="jscad"+numobjs,numobjs+=1);break;case"vertex":p=instantiateVector(obj);break;case"seqend":current=translateCurrent(current,layers,parts,options),parts=[];break;case"lwpolyline":current=translateCurrent(current,layers,parts,options),parts=[],translatePath2D(obj,layers,options)}index$7.isA(p)&&parts.push(p),p&&"vec"in p&&3===p.vec.length&&parts.push(p),p&&"vec"in p&&2===p.vec.length&&parts.push(p)}current=translateCurrent(current,layers,parts,options);let script="import * from '@jscad/modeling'\n\nexport const main = () => {\n let layers = []\n return layers.concat(";return layers.forEach((layer=>{const name=layer.lnam||"Unknown";script+=`${name}(),`})),script+="[])\n}\n",script+="\nconst createPolygon = (listofpoints, color) => {\n let polygon = poly3.create(listofpoints)\n return colorize(color, polygon)\n}\n",layers.forEach((layer=>{script+=(layer=>{let script=`const ${layer.lnam||"Unknown"} = () => {\n`;for(const object of layer.objects)script+=object.script;script+=" return [";for(const object of layer.objects)script+=object.name+",";return script+="]\n}\n",script})(layer)})),script})(reader,options),code},deserialize=(options,src)=>{const defaults={filename:"dxf",version:"3.0.1-alpha.0",output:"script",strict:!0,colorindex:colorIndex,dxf:{angdir:0,insunits:4,pfacevmax:4}};return options=Object.assign({},defaults,options),src=((stringOrArrayBuffer,defaultBinaryEncoding="utf-8")=>"string"==typeof stringOrArrayBuffer?stringOrArrayBuffer:new TextDecoder(defaultBinaryEncoding).decode(new Uint8Array(stringOrArrayBuffer)))(src),"script"===options.output?translate(src,options):instantiate(src,options)},mimeType="image/vnd.dxf";export{deserialize,mimeType}; diff --git a/packages/io/dxf-deserializer/dist/jscad-dxf-deserializer.min.js b/packages/io/dxf-deserializer/dist/jscad-dxf-deserializer.min.js index a8e154e41..df8db2c4d 100644 --- a/packages/io/dxf-deserializer/dist/jscad-dxf-deserializer.min.js +++ b/packages/io/dxf-deserializer/dist/jscad-dxf-deserializer.min.js @@ -1,7 +1,7 @@ /** * DXF Deserializer for JSCAD * @module @jscad/dxf-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -var global,factory;global=this,factory=function(exports){const dxfMap=new Map([[0,"etyp"],[1,"text"],[2,"name"],[3,"nam1"],[5,"hdle"],[6,"ltyp"],[7,"lsty"],[8,"lnam"],[9,"vari"],[10,"pptx"],[11,"sptx"],[12,"tptx"],[13,"fptx"],[20,"ppty"],[21,"spty"],[22,"tpty"],[23,"fpty"],[30,"pptz"],[31,"sptz"],[32,"tptz"],[33,"fptz"],[38,"elev"],[39,"lthk"],[40,"swid"],[41,"ewid"],[42,"bulg"],[43,"cwid"],[48,"lscl"],[50,"ang0"],[51,"ang1"],[60,"visb"],[62,"cnmb"],[67,"spac"],[70,"lflg"],[71,"fvia"],[72,"fvib"],[73,"fvic"],[74,"fvid"],[75,"cflg"],[90,"vlen"],[91,"slen"],[92,"plen"],[93,"flen"],[94,"elen"],[95,"clen"],[100,"sbnm"],[210,"etrx"],[220,"etry"],[230,"etrz"]]),getTLA=group=>dxfMap.get(group),colorIndex=[[0,0,0,255],[255,0,0,255],[255,255,0,255],[0,255,0,255],[0,255,255,255],[0,0,255,255],[255,0,255,255],[255,255,255,255],[128,128,128,255],[192,192,192,255],[255,0,0,255],[255,127,127,255],[165,0,0,255],[165,82,82,255],[127,0,0,255],[127,63,63,255],[76,0,0,255],[76,38,38,255],[38,0,0,255],[38,19,19,255],[255,63,0,255],[255,159,127,255],[165,41,0,255],[165,103,82,255],[127,31,0,255],[127,79,63,255],[76,19,0,255],[76,47,38,255],[38,9,0,255],[38,28,19,255],[255,127,0,255],[255,191,127,255],[165,82,0,255],[165,124,82,255],[127,63,0,255],[127,95,63,255],[76,38,0,255],[76,57,38,255],[38,19,0,255],[38,28,19,255],[255,191,0,255],[255,223,127,255],[165,124,0,255],[165,145,82,255],[127,95,0,255],[127,111,63,255],[76,57,0,255],[76,66,38,255],[38,28,0,255],[38,33,19,255],[255,255,0,255],[255,255,127,255],[165,165,0,255],[165,165,82,255],[127,127,0,255],[127,127,63,255],[76,76,0,255],[76,76,38,255],[38,38,0,255],[38,38,19,255],[191,255,0,255],[223,255,127,255],[124,165,0,255],[145,165,82,255],[95,127,0,255],[111,127,63,255],[57,76,0,255],[66,76,38,255],[28,38,0,255],[33,38,19,255],[127,255,0,255],[191,255,127,255],[82,165,0,255],[124,165,82,255],[63,127,0,255],[95,127,63,255],[38,76,0,255],[57,76,38,255],[19,38,0,255],[28,38,19,255],[63,255,0,255],[159,255,127,255],[41,165,0,255],[103,165,82,255],[31,127,0,255],[79,127,63,255],[19,76,0,255],[47,76,38,255],[9,38,0,255],[23,38,19,255],[0,255,0,255],[125,255,127,255],[0,165,0,255],[82,165,82,255],[0,127,0,255],[63,127,63,255],[0,76,0,255],[38,76,38,255],[0,38,0,255],[19,38,19,255],[0,255,63,255],[127,255,159,255],[0,165,41,255],[82,165,103,255],[0,127,31,255],[63,127,79,255],[0,76,19,255],[38,76,47,255],[0,38,9,255],[19,88,23,255],[0,255,127,255],[127,255,191,255],[0,165,82,255],[82,165,124,255],[0,127,63,255],[63,127,95,255],[0,76,38,255],[38,76,57,255],[0,38,19,255],[19,88,28,255],[0,255,191,255],[127,255,223,255],[0,165,124,255],[82,165,145,255],[0,127,95,255],[63,127,111,255],[0,76,57,255],[38,76,66,255],[0,38,28,255],[19,88,88,255],[0,255,255,255],[127,255,255,255],[0,165,165,255],[82,165,165,255],[0,127,127,255],[63,127,127,255],[0,76,76,255],[38,76,76,255],[0,38,38,255],[19,88,88,255],[0,191,255,255],[127,223,255,255],[0,124,165,255],[82,145,165,255],[0,95,127,255],[63,111,217,255],[0,57,76,255],[38,66,126,255],[0,28,38,255],[19,88,88,255],[0,127,255,255],[127,191,255,255],[0,82,165,255],[82,124,165,255],[0,63,127,255],[63,95,127,255],[0,38,76,255],[38,57,126,255],[0,19,38,255],[19,28,88,255],[0,63,255,255],[127,159,255,255],[0,41,165,255],[82,103,165,255],[0,31,127,255],[63,79,127,255],[0,19,76,255],[38,47,126,255],[0,9,38,255],[19,23,88,255],[0,0,255,255],[127,127,255,255],[0,0,165,255],[82,82,165,255],[0,0,127,255],[63,63,127,255],[0,0,76,255],[38,38,126,255],[0,0,38,255],[19,19,88,255],[63,0,255,255],[159,127,255,255],[41,0,165,255],[103,82,165,255],[31,0,127,255],[79,63,127,255],[19,0,76,255],[47,38,126,255],[9,0,38,255],[23,19,88,255],[127,0,255,255],[191,127,255,255],[165,0,82,255],[124,82,165,255],[63,0,127,255],[95,63,127,255],[38,0,76,255],[57,38,126,255],[19,0,38,255],[28,19,88,255],[191,0,255,255],[223,127,255,255],[124,0,165,255],[142,82,165,255],[95,0,127,255],[111,63,127,255],[57,0,76,255],[66,38,76,255],[28,0,38,255],[88,19,88,255],[255,0,255,255],[255,127,255,255],[165,0,165,255],[165,82,165,255],[127,0,127,255],[127,63,127,255],[76,0,76,255],[76,38,76,255],[38,0,38,255],[88,19,88,255],[255,0,191,255],[255,127,223,255],[165,0,124,255],[165,82,145,255],[127,0,95,255],[127,63,111,255],[76,0,57,255],[76,38,66,255],[38,0,28,255],[88,19,88,255],[255,0,127,255],[255,127,191,255],[165,0,82,255],[165,82,124,255],[127,0,63,255],[127,63,95,255],[76,0,38,255],[76,38,57,255],[38,0,19,255],[88,19,28,255],[255,0,63,255],[255,127,159,255],[165,0,41,255],[165,82,103,255],[127,0,31,255],[127,63,79,255],[76,0,19,255],[76,38,47,255],[38,0,9,255],[88,19,23,255],[0,0,0,255],[101,101,101,255],[102,102,102,255],[153,153,153,255],[204,204,204,255],[255,255,255,255]];class DxfReader{constructor(options){this.options=Object.assign({},{strict:!1,track:!0},options),this.trackPosition=this.options.track,this.trackPosition&&(this.line=0,this.column=0,this.c=0)}on(state,callback){return this["on"+state]=callback,this}absorb(group,callback){return void 0===this.absorbers&&(this.absorbers=new Map),this.absorbers.set(group,callback),this}write(data){return parse(this,data),this}close(){return this.isclosed=!0,this}}const emiterror=(reader,er)=>(reader.trackPosition&&(er+=`\nLine: ${reader.line}\nColumn: ${reader.column}\nChar: ${reader.c}`),er=new Error(er),reader.error=er,emitstate(reader,"onerror",er)),emitend=reader=>emitstate(reader,"onend",reader.data),emitstate=(reader,state,data)=>{const onhandler=state.toString();return reader[onhandler]&&reader[onhandler](reader,data),reader},parse=(reader,data)=>{if(reader.error)throw reader.error;if(reader.isclosed)return emiterror(reader,"Cannot write after close");if((reader=>{emitstate(reader,"onstart",reader.data)})(reader),null===data)return emitend(reader);reader.group=null,reader.value=null,reader.error=null,reader.position=0,reader.line=0,reader.column=0;let i=0,c="",l="";for(;null===reader.error&&(c=charAt(data,i++),c);)reader.trackPosition&&(reader.position++,"\n"===c?(reader.line++,reader.column=0):reader.column++),"\n"===c?(parseLine(reader,l),l=""):l+=c;return emitend(reader),reader},parseLine=(reader,line)=>{line=line.trim(),null===reader.group?(setDxfGroup(reader,line),reader.value=null):setDxfValue(reader,line),null!==reader.group&&null!==reader.value&&(((reader,group,value)=>{if(void 0!==reader.absorbers){const absorber=reader.absorbers.get(group);void 0!==absorber&&absorber(reader,group,value)}})(reader,reader.group,reader.value),reader.group=null,reader.value=null)},setDxfGroup=(reader,line)=>{const code=parseInt(line);isNaN(code)?(emiterror(reader,"Invalid group (int)"),reader.group=null):reader.group=code},setDxfValue=(reader,line)=>{reader.options.strict,reader.value=line},charAt=(data,i)=>data&&data.length>i?data.charAt(i):"",clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS$1=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};var index$b=Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(value=radius,constant=0,!(Number.isFinite(value)&&value>constant))throw new Error("radius must be greater than zero");var value,constant;if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS$1*EPS$1)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps)),point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})},line=points=>{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},findLayer=(obj,layers)=>{const lname=obj.lnam||"0";for(const layer of layers)if(layer.name===lname)return layer;return null},getColorNumber=(obj,layers)=>{let cn=obj.cnmb||-1;if(256===cn){cn=-1;const layer=findLayer(obj,layers);null!==layer&&(cn=layer.cnmb||-1)}return cn},getColor=(index,colorindex)=>{if(index<1)return null;index=((num,mod)=>{const remain=num%mod;return Math.floor(remain>=0?remain:remain+mod)})(index,colorindex.length);const color=colorindex[index];return[color[0]/255,color[1]/255,color[2]/255,color[3]/255]},instantiatePolygon=(obj,layers,options)=>{const vertices=[];if(vertices.push(index$d.fromValues(obj.pptx,obj.ppty,obj.pptz)),vertices.push(index$d.fromValues(obj.sptx,obj.spty,obj.sptz)),vertices.push(index$d.fromValues(obj.tptx,obj.tpty,obj.tptz)),obj.fptx){let pushit=!1;obj.tptx!==obj.fptx&&(pushit=!0),obj.tpty!==obj.fpty&&(pushit=!0),obj.tptz!==obj.fptz&&(pushit=!0),pushit&&vertices.push(index$d.fromValues(obj.fptx,obj.fpty,obj.fptz))}const cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygon=index$7.create(vertices);return color&&(polygon.color=color),polygon},instantiateLine=(obj,layers,options)=>{if(obj.pptz===obj.sptz&&0===obj.pptz){const p1=index$b.fromValues(obj.pptx,obj.ppty),p2=index$b.fromValues(obj.sptx,obj.spty);return line([p1,p2])}const p1=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),p2=index$d.fromValues(obj.sptx,obj.spty,obj.sptz);return line([p1,p2])},instantiateVector=obj=>{const d3line=parseInt("00000000000100000",2),d3mesh=parseInt("00000000001000000",2),d3face=parseInt("00000000010000000",2),flags=obj.lflg,vtype={};return(flags&d3line)===d3line||(flags&d3mesh)===d3mesh?vtype.vec=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz):(flags&d3face)===d3face?(vtype.vec=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),vtype.fvia=obj.fvia,vtype.fvib=obj.fvib,vtype.fvic=obj.fvic,vtype.fvid=obj.fvid):(vtype.vec=index$b.fromValues(obj.pptx,obj.ppty),vtype.bulg=obj.bulg),vtype},addSection=(path,x1,y1,bulg)=>{if(0===bulg)path=index$5.appendPoints([[x1,y1]],path);else{const points=index$5.toPoints(path),prev=points[points.length-1],curr=index$b.fromValues(x1,y1),r=index$b.distance(prev,curr)*((1+Math.pow(bulg,2))/(4*bulg)),clockwise=bulg<0,large=!1,d=4*Math.atan(bulg),res=16;path=index$5.appendArc({endpoint:[x1,y1],radius:[r,r],xaxisrotation:d,clockwise:clockwise,large:large,segments:res},path)}return path},instantiatePath2D=(obj,layers,options)=>{const closed=parseInt("00000000000000001",2),vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,bulgs=obj.bulgs,flags=obj.lflg;let path=index$5.create();const isclosed=(flags&closed)===closed;return vlen!==pptxs.length||vlen!==pptys.length||vlen!==bulgs.length||(pptxs.forEach(((item,index,array)=>{let bulg=0;index>0&&(bulg=bulgs[index-1]),path=addSection(path,pptxs[index],pptys[index],bulg)})),isclosed&&!path.isClosed&&(path=addSection(path,pptxs[0],pptys[0],bulgs[vlen-1]),path=index$5.close(path))),path},instantiateArc=(obj,layers,options)=>{obj.lthk;const pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid;let ang0=obj.ang0;ang0*=.017453292519943295;let ang1=obj.ang1;return ang1*=.017453292519943295,arc({center:[pptx,ppty],radius:swid,startAngle:ang0,endAngle:ang1,segments:16})},instantiateCircle=(obj,layers,options)=>{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===lthk){const cag=circle({center:[pptx,ppty],radius:swid,segments:16});return color&&(cag.color=color),cag}const csg=circle({center:[pptx,ppty],radius:swid,segments:16}).extrude({offset:[0,0,lthk]});return color&&(csg.color=color),csg},instantiateEllipse=(obj,layers,options)=>{const pptx=obj.pptx,ppty=obj.ppty,pptz=obj.pptz,sptx=obj.sptx,spty=obj.spty,sptz=obj.sptz,swid=obj.swid;if(0===pptz&&0===sptz){const center=index$b.fromValues(0,0),mjaxis=index$b.fromValues(sptx,spty),rx=index$b.distance(center,mjaxis),ry=rx*swid;let angle=180*Math.atan2(spty,sptx)/Math.PI;angle<1e-5&&(angle=0),angle*=.017453292519943295;const cag=ellipse({center:[0,0],radius:[rx,ry],segments:16}),matrix=index$c.fromZRotation(index$c.create(),angle);return index$c.multiply(matrix,matrix,index$c.fromTranslation(index$c.create(),[pptx,ppty,0])),index$a.transform(matrix,cag)}},instantiateMesh=(obj,layers,options)=>{const vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,pptzs=obj.pptzs,flen=obj.flen,fvals=obj.fvals,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygons=[];if(vlen===pptxs.length&&vlen===pptys.length&&vlen===pptzs.length&&flen===fvals.length){const faces=(fvals=>{const faces=[];let vi=0;for(;vi0;)face.push(fvals[vi++]),fi--;faces.push(face)}return faces})(fvals),points=((pptxs,pptys,pptzs)=>{const points=[];let vi=0;for(;vi{const closedM=parseInt("00000000000000001",2),d3line=parseInt("00000000000001000",2),d3mesh=parseInt("00000000000010000",2),closedN=parseInt("00000000000100000",2),d3face=parseInt("00000000001000000",2),flags=obj.lflg;let ptype=null;return(flags&d3line)===d3line?ptype=null:(flags&d3mesh)===d3mesh||(flags&d3face)===d3face?(ptype=index$6.create(),ptype.closedM=(flags&closedM)===closedM,ptype.closedN=(flags&closedN)===closedN):(ptype=index$5.create(),ptype.closedM=(flags&closedM)===closedM),"cnmb"in obj&&(ptype.cnmb=obj.cnmb),ptype},completeCurrent=(objects,baseobj,polygons,vectors,options)=>{if(index$5.isA(baseobj)){const points=vectors.map((vector=>vector.vec));objects.push(index$5.fromPoints({closed:baseobj.closed},points))}return index$6.isA(baseobj)&&objects.push(index$6.create(polygons)),null},translateVector2D=vector=>`${vector[0]},${vector[1]}`,translateVector3D=vector=>`${vector[0]},${vector[1]},${vector[2]}`,translatePolygon=polygon=>{const vertices=index$7.toVertices(polygon);let script="createPolygon([";return vertices.forEach((vertice=>{script+=`[${translateVector3D(vertice)}],`})),script+=`],${translateColor(polygon)})`,script},translateColor=polygon=>{let script="null";if("color"in polygon){const rgb=polygon.color;script=`[${rgb[0]},${rgb[1]},${rgb[2]},${rgb[3]}]`}return script},translateLine=(obj,layers,options)=>{const name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);let script="";if(!obj.pptz||obj.pptz===obj.sptz&&0===obj.pptz){const p1=index$b.fromValues(obj.pptx,obj.ppty),p2=index$b.fromValues(obj.sptx,obj.spty);script=` let ${name} = line([[${translateVector2D(p1)}],[${translateVector2D(p2)}]])\n`}else{const p1=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),p2=index$d.fromValues(obj.sptx,obj.spty,obj.sptz);script=` let ${name} = line([[${translateVector3D(p1)}],[${translateVector3D(p2)}]])\n`}color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateSection=(name,x1,y1,bulg,px,py)=>{if(0===bulg)return`path2.appendPoints([[${x1},${y1}]], ${name})\n`;const prev=index$b.fromValues(px,py),curr=index$b.fromValues(x1,y1),r=index$b.distance(prev,curr)*((1+Math.pow(bulg,2))/(4*bulg)),clockwise=bulg<0;return`path2.appendArc({endpoint: [${x1},${y1}],radius: [${r},${r}],xaxisrotation: ${4*Math.atan(bulg)},clockwise: ${clockwise},large: false,segments: 16}, ${name})\n`},translatePath2D=(obj,layers,options)=>{const closed=parseInt("00000000000000001",2),vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,bulgs=obj.bulgs,flags=obj.lflg,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);let script=` let ${name} = path2.create()\n`;const isclosed=(flags&closed)===closed;if(vlen===pptxs.length&&vlen===pptys.length&&vlen===bulgs.length){script+=` ${name} = path2.appendPoints([[${pptxs[0]}, ${pptys[0]}]], ${name})\n`;for(let i=0;i{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid;let ang0=obj.ang0,ang1=obj.ang1;const name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(ang0*=.017453292519943295,ang1*=.017453292519943295,0===lthk){let script=` let ${name} = arc({center: [${pptx}, ${ppty}], radius: ${swid}, startAngle: ${ang0}, endAngle: ${ang1}, segements: 16})\n`;return color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,void addToLayer(obj,layers)}let script=` let ${name} = arc({center: [${pptx}, ${ppty}], radius: ${swid}, startAngle: ${ang0}, endAngle: ${ang1}, segements: 16})\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateCircle=(obj,layers,options)=>{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===lthk){let script=` let ${name} = circle({center: [${pptx}, ${ppty}], radius: ${swid}, segments: 16})\n`;return color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,void addToLayer(obj,layers)}let script=` let ${name} = circle({center: [${pptx}, ${ppty}], radius: ${swid}, segments: 16}).extrude({offset: [0,0,${lthk}]}))\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateEllipse=(obj,layers,options)=>{const pptx=obj.pptx,ppty=obj.ppty,pptz=obj.pptz,sptx=obj.sptx,spty=obj.spty,sptz=obj.sptz,swid=obj.swid,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===pptz&&0===sptz){const center=index$b.fromValues(0,0),mjaxis=index$b.fromValues(sptx,spty),rx=index$b.distance(center,mjaxis);let script=` let ${name} = ellipse({center: [0, 0, 0], radius: [${rx}, ${rx*swid}], segments: 16})\n let ${name}matrix = mat4.multiply(mat4.create(), mat4.fromTranslation(mat4.create(), [${pptx}, ${ppty}, 0]), mat4.fromZRotation(mat4.create(), ${Math.atan2(spty,sptx)}))\n ${name} = geom2.transform(${name}matrix, ${name})\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)}},translateMesh=(obj,layers,options)=>{const vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,pptzs=obj.pptzs,flen=obj.flen,fvals=obj.fvals,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygons=[];if(vlen===pptxs.length&&vlen===pptys.length&&vlen===pptzs.length)if(flen===fvals.length){const faces=(fvals=>{const faces=[];let vi=0;for(;vi0;)face.push(fvals[vi++]),fi--;faces.push(face)}return faces})(fvals),points=((pptxs,pptys,pptzs)=>{const points=[];let vi=0;for(;vi{let layer=findLayer(obj,layers);null===layer&&(layer=(layers=>{for(const layer of layers)if("0"===layer.name)return layer;const layer={type:"layer",lnam:"layer0",name:"0",lscl:1,visb:0,spac:0,objects:[]};return layers.push(layer),layer})(layers)),"objects"in layer||(layer.objects=[]),layer.objects.push(obj)},getPolyType=obj=>{const closedM=parseInt("00000000000000001",2),d3line=parseInt("00000000000001000",2),d3mesh=parseInt("00000000000010000",2),closedN=parseInt("00000000000100000",2),d3face=parseInt("00000000001000000",2),flags=obj.lflg;let ptype=null;return(flags&d3line)===d3line?ptype={type:"3dline",isclosed:(flags&closedM)===closedM}:(flags&d3mesh)===d3mesh?(ptype={type:"3dpolymesh"},ptype.fvia=obj.fvia,ptype.fvib=obj.fvib,ptype.closedM=(flags&closedM)===closedM,ptype.closedN=(flags&closedN)===closedN):(flags&d3face)===d3face?(ptype={type:"3dpolyfaces"},ptype.fvia=obj.fvia,ptype.fvib=obj.fvib):ptype={type:"2dline",isclosed:(flags&closedM)===closedM},"cnmb"in obj&&(ptype.cnmb=obj.cnmb),"lnam"in obj&&(ptype.lnam=obj.lnam),ptype},translateCurrent=(obj,layers,parts,options)=>{if(null===obj)return null;const type=obj.type,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if("2dline"===type)return((obj,layers,parts,options)=>{obj.vlen=parts.length,obj.pptxs=[],obj.pptys=[],obj.bulgs=[];for(const part of parts)obj.pptxs.push(part.vec[0]),obj.pptys.push(part.vec[1]),obj.bulgs.push(part.bulg);return obj.isclosed?obj.lflg=parseInt("00000000000000001",2):obj.lflg=0,translatePath2D(obj,layers,options),null})(obj,layers,parts,options);if("3dline"===type)return null;if("3dpolymesh"===type){const facets=((meshM,meshN,parts,color,options)=>{const getVector=(x,y)=>parts[(x-1)*meshN+(y-1)].vec,facets=[];if(meshM*meshN!==parts.length)return facets;if(meshM<2|meshN<2)return facets;let i=1;for(;i{const faces=[];if(meshM+meshN!==parts.length)return faces;let i=meshM;for(;i0&&(part=parts[indexes[0]-1],vertices.push(part.vec),indexes[1]>0&&(part=parts[indexes[1]-1],vertices.push(part.vec),indexes[2]>0&&(part=parts[indexes[2]-1],vertices.push(part.vec),indexes[3]>0&&(part=parts[indexes[3]-1],vertices.push(part.vec))))),vertices.length>2){1===options.dxf.angdir&&(vertices=vertices.reverse());const polygon=index$7.create(vertices);faces.push(polygon)}i++}return faces})(obj.fvia,obj.fvib,parts,0,options);parts=faces}const name=obj.name;let script=` const ${name}_polygons = [\n`;for(const polygon of parts)script+=" "+translatePolygon(polygon)+",\n";return script+=` ]\n let ${name} = geom3.create(${name}_polygons)\n`,color&&(script+=` ${name}.color = [${color}]\n`),obj.script=script,addToLayer(obj,layers),null},saveVariable=(obj,options)=>{"$ANGDIR"===(obj.name||"Unknown")&&"lflg"in obj&&(options.dxf.angdir=obj.lflg)},handleError=(reader,error)=>{if(!0===reader.options.strict)throw error;console.log(`error: line ${error.line}, column ${error.column}, bad character [${error.c}]`)},handleStart=(reader,data)=>{},handleEnd=(reader,data)=>{},handleEntity=(reader,group,value)=>{let obj=null;switch(value){case"LAYER":obj={type:"layer"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(67)]=0,reader.objstack.push(obj);break;case"LINE":obj={type:"line"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=0,reader.objstack.push(obj);break;case"LWPOLYLINE":obj={type:"lwpolyline"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(38)]=0,obj[getTLA(39)]=0,obj[getTLA(43)]=0,obj[getTLA(70)]=0,obj[getTLA(90)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"MESH":obj={type:"mesh"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(91)]=0,obj[getTLA(92)]=0,obj[getTLA(93)]=0,obj[getTLA(94)]=0,obj[getTLA(95)]=0,obj.state=0,reader.objstack.push(obj);break;case"POLYLINE":obj={type:"polyline"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(10)]=0,obj[getTLA(20)]=0,obj[getTLA(30)]=0,obj[getTLA(39)]=0,obj[getTLA(40)]=0,obj[getTLA(41)]=0,obj[getTLA(70)]=0,obj[getTLA(71)]=0,obj[getTLA(72)]=0,obj[getTLA(73)]=0,obj[getTLA(74)]=0,obj[getTLA(75)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"ARC":obj={type:"arc"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(39)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"CIRCLE":obj={type:"circle"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(39)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"ELLIPSE":obj={type:"ellipse"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"VERTEX":obj={type:"vertex"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(10)]=0,obj[getTLA(20)]=0,obj[getTLA(30)]=0,obj[getTLA(40)]=0,obj[getTLA(41)]=0,obj[getTLA(42)]=0,obj[getTLA(70)]=0,obj[getTLA(71)]=0,obj[getTLA(72)]=0,obj[getTLA(73)]=0,obj[getTLA(74)]=0,reader.objstack.push(obj);break;case"3DFACE":obj={type:"3dface"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(70)]=0,reader.objstack.push(obj);break;case"SEQEND":obj={type:"seqend"},reader.objstack.push(obj);break;default:obj={},reader.objstack.push(obj)}},handleVariable=(reader,group,value)=>{const obj={type:"variable",name:value};reader.objstack.push(obj)},handleInt=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleDouble=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleXcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("lwpolyline"===obj.type?(void 0===obj.pptxs&&(obj.pptxs=[],obj.bulgs=[]),obj.pptxs.push(parseFloat(value)),obj.bulgs.push(0)):"mesh"===obj.type?(void 0===obj.pptxs&&(obj.pptxs=[]),obj.pptxs.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleYcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("lwpolyline"===obj.type||"mesh"===obj.type?(void 0===obj.pptys&&(obj.pptys=[]),obj.pptys.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleZcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("mesh"===obj.type?(void 0===obj.pptzs&&(obj.pptzs=[]),obj.pptzs.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleBulge=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("lwpolyline"===obj.type){const bulgs=obj.bulgs;void 0!==bulgs&&obj.pptxs.length===bulgs.length&&(bulgs[bulgs.length-1]=parseFloat(value))}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleLen=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("mesh"===obj.type){const state=obj.state;switch(group){case 91:obj[getTLA(group)]=parseFloat(value),obj.state=1;break;case 92:1===state?(obj.vlen=parseFloat(value),obj.state=2):(obj.plen=parseFloat(value),obj.state=6);break;case 93:obj[getTLA(group)]=parseFloat(value),obj.state=3;break;case 94:obj[getTLA(group)]=parseFloat(value),obj.state=4;break;case 95:obj[getTLA(group)]=parseFloat(value),obj.state=5;break;default:obj.state=7}}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleValue=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("mesh"===obj.type)switch(obj.state){case 3:void 0===obj.fvals&&(obj.fvals=[]),obj.fvals.push(parseFloat(value));break;case 4:void 0===obj.evals&&(obj.evals=[]),obj.evals.push(parseFloat(value))}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleString=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=value),reader.objstack.push(obj)},handleName=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&void 0===obj[getTLA(group)]&&(obj[getTLA(group)]=value),reader.objstack.push(obj)},createReader=(src,options)=>{const dxfreader=new DxfReader(options);return dxfreader.on("error",handleError),dxfreader.on("start",handleStart),dxfreader.on("end",handleEnd),dxfreader.absorb(0,handleEntity),dxfreader.absorb(1,handleString),dxfreader.absorb(2,handleName),dxfreader.absorb(3,handleName),dxfreader.absorb(6,handleString),dxfreader.absorb(7,handleString),dxfreader.absorb(8,handleString),dxfreader.absorb(9,handleVariable),dxfreader.absorb(10,handleXcoord),dxfreader.absorb(11,handleDouble),dxfreader.absorb(12,handleDouble),dxfreader.absorb(13,handleDouble),dxfreader.absorb(20,handleYcoord),dxfreader.absorb(21,handleDouble),dxfreader.absorb(22,handleDouble),dxfreader.absorb(23,handleDouble),dxfreader.absorb(30,handleZcoord),dxfreader.absorb(31,handleDouble),dxfreader.absorb(32,handleDouble),dxfreader.absorb(33,handleDouble),dxfreader.absorb(39,handleDouble),dxfreader.absorb(40,handleDouble),dxfreader.absorb(41,handleDouble),dxfreader.absorb(42,handleBulge),dxfreader.absorb(50,handleDouble),dxfreader.absorb(51,handleDouble),dxfreader.absorb(62,handleInt),dxfreader.absorb(70,handleInt),dxfreader.absorb(71,handleInt),dxfreader.absorb(72,handleInt),dxfreader.absorb(73,handleInt),dxfreader.absorb(74,handleInt),dxfreader.absorb(75,handleInt),dxfreader.absorb(90,handleValue),dxfreader.absorb(91,handleLen),dxfreader.absorb(92,handleLen),dxfreader.absorb(93,handleLen),dxfreader.absorb(94,handleLen),dxfreader.absorb(95,handleLen),dxfreader.absorb(210,handleInt),dxfreader.absorb(220,handleInt),dxfreader.absorb(230,handleInt),dxfreader.objstack=[],dxfreader.objstack.push({type:"dxf"}),dxfreader.write(src),dxfreader.close(),dxfreader},instantiate=(src,options)=>{const objs=((reader,options)=>{const layers=[];let current=null;const polygons=[],objects=[],vectors=[];let p=null;for(const obj of reader.objstack)if(p=null,"type"in obj){switch(obj.type){case"dxf":break;case"layer":current=completeCurrent(objects,current,polygons,vectors),layers.push(obj);break;case"variable":case"seqend":current=completeCurrent(objects,current,polygons,vectors);break;case"3dface":p=instantiatePolygon(obj,layers,options),null===current&&(current=index$6.create());break;case"mesh":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateMesh(obj,layers,options));break;case"arc":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateArc(obj));break;case"circle":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateCircle(obj,layers,options));break;case"ellipse":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateEllipse(obj));break;case"line":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateLine(obj));break;case"polyline":current=completeCurrent(objects,current,polygons,vectors),null===current&&(current=getPolyType$1(obj));break;case"vertex":p=instantiateVector(obj);break;case"lwpolyline":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiatePath2D(obj))}index$7.isA(p)&&polygons.push(p),p&&"vec"in p&&3===p.vec.length&&vectors.push(p),p&&"vec"in p&&2===p.vec.length&&vectors.push(p)}return current=completeCurrent(objects,current,polygons,vectors),objects})(createReader(src,options),options);return objs},translate=(src,options)=>{const reader=createReader(src,options);let code=`// Produced by JSCAD IO Library : DXF Deserializer (${options.version})\n\n`;return code+=((reader,options)=>{const layers=[];let current=null,parts=[],numobjs=0,p=null;for(const obj of reader.objstack)if(p=null,"type"in obj){if("name"in obj){let name=obj.name;name=name.replace(/ /g,"_"),name=name.replace(/-/g,"_"),name=name.replace(/\./g,"_"),obj.name=name}else obj.name="jscad"+numobjs,numobjs+=1;switch(obj.type){case"dxf":break;case"layer":current=translateCurrent(current,layers,parts,options),parts=[],obj.objects=[],obj.lnam="layer"+layers.length,layers.push(obj);break;case"variable":current=translateCurrent(current,layers,parts,options),parts=[],saveVariable(obj,options);break;case"3dface":p=instantiatePolygon(obj,layers,options),null===current&&(current={type:"3dfaces"},current.name="jscad"+numobjs,numobjs+=1);break;case"mesh":current=translateCurrent(current,layers,parts,options),parts=[],translateMesh(obj,layers,options);break;case"arc":current=translateCurrent(current,layers,parts,options),parts=[],translateArc(obj,layers,options);break;case"circle":current=translateCurrent(current,layers,parts,options),parts=[],translateCircle(obj,layers,options);break;case"ellipse":current=translateCurrent(current,layers,parts,options),parts=[],translateEllipse(obj,layers,options);break;case"line":current=translateCurrent(current,layers,parts,options),parts=[],translateLine(obj,layers,options);break;case"polyline":current=translateCurrent(current,layers,parts,options),parts=[],null===current&&(current=getPolyType(obj),current.name="jscad"+numobjs,numobjs+=1);break;case"vertex":p=instantiateVector(obj);break;case"seqend":current=translateCurrent(current,layers,parts,options),parts=[];break;case"lwpolyline":current=translateCurrent(current,layers,parts,options),parts=[],translatePath2D(obj,layers,options)}index$7.isA(p)&&parts.push(p),p&&"vec"in p&&3===p.vec.length&&parts.push(p),p&&"vec"in p&&2===p.vec.length&&parts.push(p)}current=translateCurrent(current,layers,parts,options);let script="import * from '@jscad/modeling'\n\nexport const main = () => {\n let layers = []\n return layers.concat(";return layers.forEach((layer=>{const name=layer.lnam||"Unknown";script+=`${name}(),`})),script+="[])\n}\n",script+="\nconst createPolygon = (listofpoints, color) => {\n let polygon = poly3.create(listofpoints)\n return colorize(color, polygon)\n}\n",layers.forEach((layer=>{script+=(layer=>{let script=`const ${layer.lnam||"Unknown"} = () => {\n`;for(const object of layer.objects)script+=object.script;script+=" return [";for(const object of layer.objects)script+=object.name+",";return script+="]\n}\n",script})(layer)})),script})(reader,options),code};exports.deserialize=(options,src)=>{const defaults={filename:"dxf",version:"3.0.0-alpha.0",output:"script",strict:!0,colorindex:colorIndex,dxf:{angdir:0,insunits:4,pfacevmax:4}};return"script"===(options=Object.assign({},defaults,options)).output?translate(src,options):instantiate(src,options)},exports.mimeType="image/vnd.dxf",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadDxfDeserializer={}); +var global,factory;global=this,factory=function(exports){const dxfMap=new Map([[0,"etyp"],[1,"text"],[2,"name"],[3,"nam1"],[5,"hdle"],[6,"ltyp"],[7,"lsty"],[8,"lnam"],[9,"vari"],[10,"pptx"],[11,"sptx"],[12,"tptx"],[13,"fptx"],[20,"ppty"],[21,"spty"],[22,"tpty"],[23,"fpty"],[30,"pptz"],[31,"sptz"],[32,"tptz"],[33,"fptz"],[38,"elev"],[39,"lthk"],[40,"swid"],[41,"ewid"],[42,"bulg"],[43,"cwid"],[48,"lscl"],[50,"ang0"],[51,"ang1"],[60,"visb"],[62,"cnmb"],[67,"spac"],[70,"lflg"],[71,"fvia"],[72,"fvib"],[73,"fvic"],[74,"fvid"],[75,"cflg"],[90,"vlen"],[91,"slen"],[92,"plen"],[93,"flen"],[94,"elen"],[95,"clen"],[100,"sbnm"],[210,"etrx"],[220,"etry"],[230,"etrz"]]),getTLA=group=>dxfMap.get(group),colorIndex=[[0,0,0,255],[255,0,0,255],[255,255,0,255],[0,255,0,255],[0,255,255,255],[0,0,255,255],[255,0,255,255],[255,255,255,255],[128,128,128,255],[192,192,192,255],[255,0,0,255],[255,127,127,255],[165,0,0,255],[165,82,82,255],[127,0,0,255],[127,63,63,255],[76,0,0,255],[76,38,38,255],[38,0,0,255],[38,19,19,255],[255,63,0,255],[255,159,127,255],[165,41,0,255],[165,103,82,255],[127,31,0,255],[127,79,63,255],[76,19,0,255],[76,47,38,255],[38,9,0,255],[38,28,19,255],[255,127,0,255],[255,191,127,255],[165,82,0,255],[165,124,82,255],[127,63,0,255],[127,95,63,255],[76,38,0,255],[76,57,38,255],[38,19,0,255],[38,28,19,255],[255,191,0,255],[255,223,127,255],[165,124,0,255],[165,145,82,255],[127,95,0,255],[127,111,63,255],[76,57,0,255],[76,66,38,255],[38,28,0,255],[38,33,19,255],[255,255,0,255],[255,255,127,255],[165,165,0,255],[165,165,82,255],[127,127,0,255],[127,127,63,255],[76,76,0,255],[76,76,38,255],[38,38,0,255],[38,38,19,255],[191,255,0,255],[223,255,127,255],[124,165,0,255],[145,165,82,255],[95,127,0,255],[111,127,63,255],[57,76,0,255],[66,76,38,255],[28,38,0,255],[33,38,19,255],[127,255,0,255],[191,255,127,255],[82,165,0,255],[124,165,82,255],[63,127,0,255],[95,127,63,255],[38,76,0,255],[57,76,38,255],[19,38,0,255],[28,38,19,255],[63,255,0,255],[159,255,127,255],[41,165,0,255],[103,165,82,255],[31,127,0,255],[79,127,63,255],[19,76,0,255],[47,76,38,255],[9,38,0,255],[23,38,19,255],[0,255,0,255],[125,255,127,255],[0,165,0,255],[82,165,82,255],[0,127,0,255],[63,127,63,255],[0,76,0,255],[38,76,38,255],[0,38,0,255],[19,38,19,255],[0,255,63,255],[127,255,159,255],[0,165,41,255],[82,165,103,255],[0,127,31,255],[63,127,79,255],[0,76,19,255],[38,76,47,255],[0,38,9,255],[19,88,23,255],[0,255,127,255],[127,255,191,255],[0,165,82,255],[82,165,124,255],[0,127,63,255],[63,127,95,255],[0,76,38,255],[38,76,57,255],[0,38,19,255],[19,88,28,255],[0,255,191,255],[127,255,223,255],[0,165,124,255],[82,165,145,255],[0,127,95,255],[63,127,111,255],[0,76,57,255],[38,76,66,255],[0,38,28,255],[19,88,88,255],[0,255,255,255],[127,255,255,255],[0,165,165,255],[82,165,165,255],[0,127,127,255],[63,127,127,255],[0,76,76,255],[38,76,76,255],[0,38,38,255],[19,88,88,255],[0,191,255,255],[127,223,255,255],[0,124,165,255],[82,145,165,255],[0,95,127,255],[63,111,217,255],[0,57,76,255],[38,66,126,255],[0,28,38,255],[19,88,88,255],[0,127,255,255],[127,191,255,255],[0,82,165,255],[82,124,165,255],[0,63,127,255],[63,95,127,255],[0,38,76,255],[38,57,126,255],[0,19,38,255],[19,28,88,255],[0,63,255,255],[127,159,255,255],[0,41,165,255],[82,103,165,255],[0,31,127,255],[63,79,127,255],[0,19,76,255],[38,47,126,255],[0,9,38,255],[19,23,88,255],[0,0,255,255],[127,127,255,255],[0,0,165,255],[82,82,165,255],[0,0,127,255],[63,63,127,255],[0,0,76,255],[38,38,126,255],[0,0,38,255],[19,19,88,255],[63,0,255,255],[159,127,255,255],[41,0,165,255],[103,82,165,255],[31,0,127,255],[79,63,127,255],[19,0,76,255],[47,38,126,255],[9,0,38,255],[23,19,88,255],[127,0,255,255],[191,127,255,255],[165,0,82,255],[124,82,165,255],[63,0,127,255],[95,63,127,255],[38,0,76,255],[57,38,126,255],[19,0,38,255],[28,19,88,255],[191,0,255,255],[223,127,255,255],[124,0,165,255],[142,82,165,255],[95,0,127,255],[111,63,127,255],[57,0,76,255],[66,38,76,255],[28,0,38,255],[88,19,88,255],[255,0,255,255],[255,127,255,255],[165,0,165,255],[165,82,165,255],[127,0,127,255],[127,63,127,255],[76,0,76,255],[76,38,76,255],[38,0,38,255],[88,19,88,255],[255,0,191,255],[255,127,223,255],[165,0,124,255],[165,82,145,255],[127,0,95,255],[127,63,111,255],[76,0,57,255],[76,38,66,255],[38,0,28,255],[88,19,88,255],[255,0,127,255],[255,127,191,255],[165,0,82,255],[165,82,124,255],[127,0,63,255],[127,63,95,255],[76,0,38,255],[76,38,57,255],[38,0,19,255],[88,19,28,255],[255,0,63,255],[255,127,159,255],[165,0,41,255],[165,82,103,255],[127,0,31,255],[127,63,79,255],[76,0,19,255],[76,38,47,255],[38,0,9,255],[88,19,23,255],[0,0,0,255],[101,101,101,255],[102,102,102,255],[153,153,153,255],[204,204,204,255],[255,255,255,255]];class DxfReader{constructor(options){this.options=Object.assign({},{strict:!1,track:!0},options),this.trackPosition=this.options.track,this.trackPosition&&(this.line=0,this.column=0,this.c=0)}on(state,callback){return this["on"+state]=callback,this}absorb(group,callback){return void 0===this.absorbers&&(this.absorbers=new Map),this.absorbers.set(group,callback),this}write(data){return parse(this,data),this}close(){return this.isclosed=!0,this}}const emiterror=(reader,er)=>(reader.trackPosition&&(er+=`\nLine: ${reader.line}\nColumn: ${reader.column}\nChar: ${reader.c}`),er=new Error(er),reader.error=er,emitstate(reader,"onerror",er)),emitend=reader=>emitstate(reader,"onend",reader.data),emitstate=(reader,state,data)=>{const onhandler=state.toString();return reader[onhandler]&&reader[onhandler](reader,data),reader},parse=(reader,data)=>{if(reader.error)throw reader.error;if(reader.isclosed)return emiterror(reader,"Cannot write after close");if((reader=>{emitstate(reader,"onstart",reader.data)})(reader),null===data)return emitend(reader);reader.group=null,reader.value=null,reader.error=null,reader.position=0,reader.line=0,reader.column=0;let i=0,c="",l="";for(;null===reader.error&&(c=charAt(data,i++),c);)reader.trackPosition&&(reader.position++,"\n"===c?(reader.line++,reader.column=0):reader.column++),"\n"===c?(parseLine(reader,l),l=""):l+=c;return emitend(reader),reader},parseLine=(reader,line)=>{line=line.trim(),null===reader.group?(setDxfGroup(reader,line),reader.value=null):setDxfValue(reader,line),null!==reader.group&&null!==reader.value&&(((reader,group,value)=>{if(void 0!==reader.absorbers){const absorber=reader.absorbers.get(group);void 0!==absorber&&absorber(reader,group,value)}})(reader,reader.group,reader.value),reader.group=null,reader.value=null)},setDxfGroup=(reader,line)=>{const code=parseInt(line);isNaN(code)?(emiterror(reader,"Invalid group (int)"),reader.group=null):reader.group=code},setDxfValue=(reader,line)=>{reader.options.strict,reader.value=line},charAt=(data,i)=>data&&data.length>i?data.charAt(i):"",clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS$1=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};var index$b=Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(value=radius,constant=0,!(Number.isFinite(value)&&value>constant))throw new Error("radius must be greater than zero");var value,constant;if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS$1*EPS$1)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps)),point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})},line=points=>{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},findLayer=(obj,layers)=>{const lname=obj.lnam||"0";for(const layer of layers)if(layer.name===lname)return layer;return null},getColorNumber=(obj,layers)=>{let cn=obj.cnmb||-1;if(256===cn){cn=-1;const layer=findLayer(obj,layers);null!==layer&&(cn=layer.cnmb||-1)}return cn},getColor=(index,colorindex)=>{if(index<1)return null;index=((num,mod)=>{const remain=num%mod;return Math.floor(remain>=0?remain:remain+mod)})(index,colorindex.length);const color=colorindex[index];return[color[0]/255,color[1]/255,color[2]/255,color[3]/255]},instantiatePolygon=(obj,layers,options)=>{const vertices=[];if(vertices.push(index$d.fromValues(obj.pptx,obj.ppty,obj.pptz)),vertices.push(index$d.fromValues(obj.sptx,obj.spty,obj.sptz)),vertices.push(index$d.fromValues(obj.tptx,obj.tpty,obj.tptz)),obj.fptx){let pushit=!1;obj.tptx!==obj.fptx&&(pushit=!0),obj.tpty!==obj.fpty&&(pushit=!0),obj.tptz!==obj.fptz&&(pushit=!0),pushit&&vertices.push(index$d.fromValues(obj.fptx,obj.fpty,obj.fptz))}const cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygon=index$7.create(vertices);return color&&(polygon.color=color),polygon},instantiateLine=(obj,layers,options)=>{if(obj.pptz===obj.sptz&&0===obj.pptz){const p1=index$b.fromValues(obj.pptx,obj.ppty),p2=index$b.fromValues(obj.sptx,obj.spty);return line([p1,p2])}const p1=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),p2=index$d.fromValues(obj.sptx,obj.spty,obj.sptz);return line([p1,p2])},instantiateVector=obj=>{const d3line=parseInt("00000000000100000",2),d3mesh=parseInt("00000000001000000",2),d3face=parseInt("00000000010000000",2),flags=obj.lflg,vtype={};return(flags&d3line)===d3line||(flags&d3mesh)===d3mesh?vtype.vec=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz):(flags&d3face)===d3face?(vtype.vec=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),vtype.fvia=obj.fvia,vtype.fvib=obj.fvib,vtype.fvic=obj.fvic,vtype.fvid=obj.fvid):(vtype.vec=index$b.fromValues(obj.pptx,obj.ppty),vtype.bulg=obj.bulg),vtype},addSection=(path,x1,y1,bulg)=>{if(0===bulg)path=index$5.appendPoints([[x1,y1]],path);else{const points=index$5.toPoints(path),prev=points[points.length-1],curr=index$b.fromValues(x1,y1),r=index$b.distance(prev,curr)*((1+Math.pow(bulg,2))/(4*bulg)),clockwise=bulg<0,large=!1,d=4*Math.atan(bulg),res=16;path=index$5.appendArc({endpoint:[x1,y1],radius:[r,r],xaxisrotation:d,clockwise:clockwise,large:large,segments:res},path)}return path},instantiatePath2D=(obj,layers,options)=>{const closed=parseInt("00000000000000001",2),vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,bulgs=obj.bulgs,flags=obj.lflg;let path=index$5.create();const isclosed=(flags&closed)===closed;return vlen!==pptxs.length||vlen!==pptys.length||vlen!==bulgs.length||(pptxs.forEach(((item,index,array)=>{let bulg=0;index>0&&(bulg=bulgs[index-1]),path=addSection(path,pptxs[index],pptys[index],bulg)})),isclosed&&!path.isClosed&&(path=addSection(path,pptxs[0],pptys[0],bulgs[vlen-1]),path=index$5.close(path))),path},instantiateArc=(obj,layers,options)=>{obj.lthk;const pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid;let ang0=obj.ang0;ang0*=.017453292519943295;let ang1=obj.ang1;return ang1*=.017453292519943295,arc({center:[pptx,ppty],radius:swid,startAngle:ang0,endAngle:ang1,segments:16})},instantiateCircle=(obj,layers,options)=>{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===lthk){const cag=circle({center:[pptx,ppty],radius:swid,segments:16});return color&&(cag.color=color),cag}const csg=circle({center:[pptx,ppty],radius:swid,segments:16}).extrude({offset:[0,0,lthk]});return color&&(csg.color=color),csg},instantiateEllipse=(obj,layers,options)=>{const pptx=obj.pptx,ppty=obj.ppty,pptz=obj.pptz,sptx=obj.sptx,spty=obj.spty,sptz=obj.sptz,swid=obj.swid;if(0===pptz&&0===sptz){const center=index$b.fromValues(0,0),mjaxis=index$b.fromValues(sptx,spty),rx=index$b.distance(center,mjaxis),ry=rx*swid;let angle=180*Math.atan2(spty,sptx)/Math.PI;angle<1e-5&&(angle=0),angle*=.017453292519943295;const cag=ellipse({center:[0,0],radius:[rx,ry],segments:16}),matrix=index$c.fromZRotation(index$c.create(),angle);return index$c.multiply(matrix,matrix,index$c.fromTranslation(index$c.create(),[pptx,ppty,0])),index$a.transform(matrix,cag)}},instantiateMesh=(obj,layers,options)=>{const vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,pptzs=obj.pptzs,flen=obj.flen,fvals=obj.fvals,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygons=[];if(vlen===pptxs.length&&vlen===pptys.length&&vlen===pptzs.length&&flen===fvals.length){const faces=(fvals=>{const faces=[];let vi=0;for(;vi0;)face.push(fvals[vi++]),fi--;faces.push(face)}return faces})(fvals),points=((pptxs,pptys,pptzs)=>{const points=[];let vi=0;for(;vi{const closedM=parseInt("00000000000000001",2),d3line=parseInt("00000000000001000",2),d3mesh=parseInt("00000000000010000",2),closedN=parseInt("00000000000100000",2),d3face=parseInt("00000000001000000",2),flags=obj.lflg;let ptype=null;return(flags&d3line)===d3line?ptype=null:(flags&d3mesh)===d3mesh||(flags&d3face)===d3face?(ptype=index$6.create(),ptype.closedM=(flags&closedM)===closedM,ptype.closedN=(flags&closedN)===closedN):(ptype=index$5.create(),ptype.closedM=(flags&closedM)===closedM),"cnmb"in obj&&(ptype.cnmb=obj.cnmb),ptype},completeCurrent=(objects,baseobj,polygons,vectors,options)=>{if(index$5.isA(baseobj)){const points=vectors.map((vector=>vector.vec));objects.push(index$5.fromPoints({closed:baseobj.closed},points))}return index$6.isA(baseobj)&&objects.push(index$6.create(polygons)),null},translateVector2D=vector=>`${vector[0]},${vector[1]}`,translateVector3D=vector=>`${vector[0]},${vector[1]},${vector[2]}`,translatePolygon=polygon=>{const vertices=index$7.toVertices(polygon);let script="createPolygon([";return vertices.forEach((vertice=>{script+=`[${translateVector3D(vertice)}],`})),script+=`],${translateColor(polygon)})`,script},translateColor=polygon=>{let script="null";if("color"in polygon){const rgb=polygon.color;script=`[${rgb[0]},${rgb[1]},${rgb[2]},${rgb[3]}]`}return script},translateLine=(obj,layers,options)=>{const name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);let script="";if(!obj.pptz||obj.pptz===obj.sptz&&0===obj.pptz){const p1=index$b.fromValues(obj.pptx,obj.ppty),p2=index$b.fromValues(obj.sptx,obj.spty);script=` let ${name} = line([[${translateVector2D(p1)}],[${translateVector2D(p2)}]])\n`}else{const p1=index$d.fromValues(obj.pptx,obj.ppty,obj.pptz),p2=index$d.fromValues(obj.sptx,obj.spty,obj.sptz);script=` let ${name} = line([[${translateVector3D(p1)}],[${translateVector3D(p2)}]])\n`}color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateSection=(name,x1,y1,bulg,px,py)=>{if(0===bulg)return`path2.appendPoints([[${x1},${y1}]], ${name})\n`;const prev=index$b.fromValues(px,py),curr=index$b.fromValues(x1,y1),r=index$b.distance(prev,curr)*((1+Math.pow(bulg,2))/(4*bulg)),clockwise=bulg<0;return`path2.appendArc({endpoint: [${x1},${y1}],radius: [${r},${r}],xaxisrotation: ${4*Math.atan(bulg)},clockwise: ${clockwise},large: false,segments: 16}, ${name})\n`},translatePath2D=(obj,layers,options)=>{const closed=parseInt("00000000000000001",2),vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,bulgs=obj.bulgs,flags=obj.lflg,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);let script=` let ${name} = path2.create()\n`;const isclosed=(flags&closed)===closed;if(vlen===pptxs.length&&vlen===pptys.length&&vlen===bulgs.length){script+=` ${name} = path2.appendPoints([[${pptxs[0]}, ${pptys[0]}]], ${name})\n`;for(let i=0;i{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid;let ang0=obj.ang0,ang1=obj.ang1;const name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(ang0*=.017453292519943295,ang1*=.017453292519943295,0===lthk){let script=` let ${name} = arc({center: [${pptx}, ${ppty}], radius: ${swid}, startAngle: ${ang0}, endAngle: ${ang1}, segements: 16})\n`;return color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,void addToLayer(obj,layers)}let script=` let ${name} = arc({center: [${pptx}, ${ppty}], radius: ${swid}, startAngle: ${ang0}, endAngle: ${ang1}, segements: 16})\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateCircle=(obj,layers,options)=>{const lthk=obj.lthk,pptx=obj.pptx,ppty=obj.ppty,swid=obj.swid,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===lthk){let script=` let ${name} = circle({center: [${pptx}, ${ppty}], radius: ${swid}, segments: 16})\n`;return color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,void addToLayer(obj,layers)}let script=` let ${name} = circle({center: [${pptx}, ${ppty}], radius: ${swid}, segments: 16}).extrude({offset: [0,0,${lthk}]}))\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)},translateEllipse=(obj,layers,options)=>{const pptx=obj.pptx,ppty=obj.ppty,pptz=obj.pptz,sptx=obj.sptx,spty=obj.spty,sptz=obj.sptz,swid=obj.swid,name=obj.name,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if(0===pptz&&0===sptz){const center=index$b.fromValues(0,0),mjaxis=index$b.fromValues(sptx,spty),rx=index$b.distance(center,mjaxis);let script=` let ${name} = ellipse({center: [0, 0, 0], radius: [${rx}, ${rx*swid}], segments: 16})\n let ${name}matrix = mat4.multiply(mat4.create(), mat4.fromTranslation(mat4.create(), [${pptx}, ${ppty}, 0]), mat4.fromZRotation(mat4.create(), ${Math.atan2(spty,sptx)}))\n ${name} = geom2.transform(${name}matrix, ${name})\n`;color&&(script+=` ${name} = colorize([${color[0]}, ${color[1]}, ${color[2]}, 1], ${name})\n`),obj.script=script,addToLayer(obj,layers)}},translateMesh=(obj,layers,options)=>{const vlen=obj.vlen,pptxs=obj.pptxs,pptys=obj.pptys,pptzs=obj.pptzs,flen=obj.flen,fvals=obj.fvals,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex),polygons=[];if(vlen===pptxs.length&&vlen===pptys.length&&vlen===pptzs.length)if(flen===fvals.length){const faces=(fvals=>{const faces=[];let vi=0;for(;vi0;)face.push(fvals[vi++]),fi--;faces.push(face)}return faces})(fvals),points=((pptxs,pptys,pptzs)=>{const points=[];let vi=0;for(;vi{let layer=findLayer(obj,layers);null===layer&&(layer=(layers=>{for(const layer of layers)if("0"===layer.name)return layer;const layer={type:"layer",lnam:"layer0",name:"0",lscl:1,visb:0,spac:0,objects:[]};return layers.push(layer),layer})(layers)),"objects"in layer||(layer.objects=[]),layer.objects.push(obj)},getPolyType=obj=>{const closedM=parseInt("00000000000000001",2),d3line=parseInt("00000000000001000",2),d3mesh=parseInt("00000000000010000",2),closedN=parseInt("00000000000100000",2),d3face=parseInt("00000000001000000",2),flags=obj.lflg;let ptype=null;return(flags&d3line)===d3line?ptype={type:"3dline",isclosed:(flags&closedM)===closedM}:(flags&d3mesh)===d3mesh?(ptype={type:"3dpolymesh"},ptype.fvia=obj.fvia,ptype.fvib=obj.fvib,ptype.closedM=(flags&closedM)===closedM,ptype.closedN=(flags&closedN)===closedN):(flags&d3face)===d3face?(ptype={type:"3dpolyfaces"},ptype.fvia=obj.fvia,ptype.fvib=obj.fvib):ptype={type:"2dline",isclosed:(flags&closedM)===closedM},"cnmb"in obj&&(ptype.cnmb=obj.cnmb),"lnam"in obj&&(ptype.lnam=obj.lnam),ptype},translateCurrent=(obj,layers,parts,options)=>{if(null===obj)return null;const type=obj.type,cn=getColorNumber(obj,layers),color=getColor(cn,options.colorindex);if("2dline"===type)return((obj,layers,parts,options)=>{obj.vlen=parts.length,obj.pptxs=[],obj.pptys=[],obj.bulgs=[];for(const part of parts)obj.pptxs.push(part.vec[0]),obj.pptys.push(part.vec[1]),obj.bulgs.push(part.bulg);return obj.isclosed?obj.lflg=parseInt("00000000000000001",2):obj.lflg=0,translatePath2D(obj,layers,options),null})(obj,layers,parts,options);if("3dline"===type)return null;if("3dpolymesh"===type){const facets=((meshM,meshN,parts,color,options)=>{const getVector=(x,y)=>parts[(x-1)*meshN+(y-1)].vec,facets=[];if(meshM*meshN!==parts.length)return facets;if(meshM<2|meshN<2)return facets;let i=1;for(;i{const faces=[];if(meshM+meshN!==parts.length)return faces;let i=meshM;for(;i0&&(part=parts[indexes[0]-1],vertices.push(part.vec),indexes[1]>0&&(part=parts[indexes[1]-1],vertices.push(part.vec),indexes[2]>0&&(part=parts[indexes[2]-1],vertices.push(part.vec),indexes[3]>0&&(part=parts[indexes[3]-1],vertices.push(part.vec))))),vertices.length>2){1===options.dxf.angdir&&(vertices=vertices.reverse());const polygon=index$7.create(vertices);faces.push(polygon)}i++}return faces})(obj.fvia,obj.fvib,parts,0,options);parts=faces}const name=obj.name;let script=` const ${name}_polygons = [\n`;for(const polygon of parts)script+=" "+translatePolygon(polygon)+",\n";return script+=` ]\n let ${name} = geom3.create(${name}_polygons)\n`,color&&(script+=` ${name}.color = [${color}]\n`),obj.script=script,addToLayer(obj,layers),null},saveVariable=(obj,options)=>{"$ANGDIR"===(obj.name||"Unknown")&&"lflg"in obj&&(options.dxf.angdir=obj.lflg)},handleError=(reader,error)=>{if(!0===reader.options.strict)throw error;console.log(`error: line ${error.line}, column ${error.column}, bad character [${error.c}]`)},handleStart=(reader,data)=>{},handleEnd=(reader,data)=>{},handleEntity=(reader,group,value)=>{let obj=null;switch(value){case"LAYER":obj={type:"layer"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(67)]=0,reader.objstack.push(obj);break;case"LINE":obj={type:"line"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=0,reader.objstack.push(obj);break;case"LWPOLYLINE":obj={type:"lwpolyline"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(38)]=0,obj[getTLA(39)]=0,obj[getTLA(43)]=0,obj[getTLA(70)]=0,obj[getTLA(90)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"MESH":obj={type:"mesh"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(91)]=0,obj[getTLA(92)]=0,obj[getTLA(93)]=0,obj[getTLA(94)]=0,obj[getTLA(95)]=0,obj.state=0,reader.objstack.push(obj);break;case"POLYLINE":obj={type:"polyline"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(10)]=0,obj[getTLA(20)]=0,obj[getTLA(30)]=0,obj[getTLA(39)]=0,obj[getTLA(40)]=0,obj[getTLA(41)]=0,obj[getTLA(70)]=0,obj[getTLA(71)]=0,obj[getTLA(72)]=0,obj[getTLA(73)]=0,obj[getTLA(74)]=0,obj[getTLA(75)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"ARC":obj={type:"arc"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(39)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"CIRCLE":obj={type:"circle"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(39)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"ELLIPSE":obj={type:"ellipse"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(210)]=0,obj[getTLA(220)]=0,obj[getTLA(230)]=1,reader.objstack.push(obj);break;case"VERTEX":obj={type:"vertex"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(10)]=0,obj[getTLA(20)]=0,obj[getTLA(30)]=0,obj[getTLA(40)]=0,obj[getTLA(41)]=0,obj[getTLA(42)]=0,obj[getTLA(70)]=0,obj[getTLA(71)]=0,obj[getTLA(72)]=0,obj[getTLA(73)]=0,obj[getTLA(74)]=0,reader.objstack.push(obj);break;case"3DFACE":obj={type:"3dface"},obj[getTLA(48)]=1,obj[getTLA(60)]=0,obj[getTLA(62)]=256,obj[getTLA(67)]=0,obj[getTLA(70)]=0,reader.objstack.push(obj);break;case"SEQEND":obj={type:"seqend"},reader.objstack.push(obj);break;default:obj={},reader.objstack.push(obj)}},handleVariable=(reader,group,value)=>{const obj={type:"variable",name:value};reader.objstack.push(obj)},handleInt=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleDouble=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleXcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("lwpolyline"===obj.type?(void 0===obj.pptxs&&(obj.pptxs=[],obj.bulgs=[]),obj.pptxs.push(parseFloat(value)),obj.bulgs.push(0)):"mesh"===obj.type?(void 0===obj.pptxs&&(obj.pptxs=[]),obj.pptxs.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleYcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("lwpolyline"===obj.type||"mesh"===obj.type?(void 0===obj.pptys&&(obj.pptys=[]),obj.pptys.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleZcoord=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&("mesh"===obj.type?(void 0===obj.pptzs&&(obj.pptzs=[]),obj.pptzs.push(parseFloat(value))):obj[getTLA(group)]=parseFloat(value)),reader.objstack.push(obj)},handleBulge=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("lwpolyline"===obj.type){const bulgs=obj.bulgs;void 0!==bulgs&&obj.pptxs.length===bulgs.length&&(bulgs[bulgs.length-1]=parseFloat(value))}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleLen=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("mesh"===obj.type){const state=obj.state;switch(group){case 91:obj[getTLA(group)]=parseFloat(value),obj.state=1;break;case 92:1===state?(obj.vlen=parseFloat(value),obj.state=2):(obj.plen=parseFloat(value),obj.state=6);break;case 93:obj[getTLA(group)]=parseFloat(value),obj.state=3;break;case 94:obj[getTLA(group)]=parseFloat(value),obj.state=4;break;case 95:obj[getTLA(group)]=parseFloat(value),obj.state=5;break;default:obj.state=7}}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleValue=(reader,group,value)=>{const obj=reader.objstack.pop();if("type"in obj)if("mesh"===obj.type)switch(obj.state){case 3:void 0===obj.fvals&&(obj.fvals=[]),obj.fvals.push(parseFloat(value));break;case 4:void 0===obj.evals&&(obj.evals=[]),obj.evals.push(parseFloat(value))}else obj[getTLA(group)]=parseFloat(value);reader.objstack.push(obj)},handleString=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&(obj[getTLA(group)]=value),reader.objstack.push(obj)},handleName=(reader,group,value)=>{const obj=reader.objstack.pop();"type"in obj&&void 0===obj[getTLA(group)]&&(obj[getTLA(group)]=value),reader.objstack.push(obj)},createReader=(src,options)=>{const dxfreader=new DxfReader(options);return dxfreader.on("error",handleError),dxfreader.on("start",handleStart),dxfreader.on("end",handleEnd),dxfreader.absorb(0,handleEntity),dxfreader.absorb(1,handleString),dxfreader.absorb(2,handleName),dxfreader.absorb(3,handleName),dxfreader.absorb(6,handleString),dxfreader.absorb(7,handleString),dxfreader.absorb(8,handleString),dxfreader.absorb(9,handleVariable),dxfreader.absorb(10,handleXcoord),dxfreader.absorb(11,handleDouble),dxfreader.absorb(12,handleDouble),dxfreader.absorb(13,handleDouble),dxfreader.absorb(20,handleYcoord),dxfreader.absorb(21,handleDouble),dxfreader.absorb(22,handleDouble),dxfreader.absorb(23,handleDouble),dxfreader.absorb(30,handleZcoord),dxfreader.absorb(31,handleDouble),dxfreader.absorb(32,handleDouble),dxfreader.absorb(33,handleDouble),dxfreader.absorb(39,handleDouble),dxfreader.absorb(40,handleDouble),dxfreader.absorb(41,handleDouble),dxfreader.absorb(42,handleBulge),dxfreader.absorb(50,handleDouble),dxfreader.absorb(51,handleDouble),dxfreader.absorb(62,handleInt),dxfreader.absorb(70,handleInt),dxfreader.absorb(71,handleInt),dxfreader.absorb(72,handleInt),dxfreader.absorb(73,handleInt),dxfreader.absorb(74,handleInt),dxfreader.absorb(75,handleInt),dxfreader.absorb(90,handleValue),dxfreader.absorb(91,handleLen),dxfreader.absorb(92,handleLen),dxfreader.absorb(93,handleLen),dxfreader.absorb(94,handleLen),dxfreader.absorb(95,handleLen),dxfreader.absorb(210,handleInt),dxfreader.absorb(220,handleInt),dxfreader.absorb(230,handleInt),dxfreader.objstack=[],dxfreader.objstack.push({type:"dxf"}),dxfreader.write(src),dxfreader.close(),dxfreader},instantiate=(src,options)=>{const objs=((reader,options)=>{const layers=[];let current=null;const polygons=[],objects=[],vectors=[];let p=null;for(const obj of reader.objstack)if(p=null,"type"in obj){switch(obj.type){case"dxf":break;case"layer":current=completeCurrent(objects,current,polygons,vectors),layers.push(obj);break;case"variable":case"seqend":current=completeCurrent(objects,current,polygons,vectors);break;case"3dface":p=instantiatePolygon(obj,layers,options),null===current&&(current=index$6.create());break;case"mesh":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateMesh(obj,layers,options));break;case"arc":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateArc(obj));break;case"circle":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateCircle(obj,layers,options));break;case"ellipse":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateEllipse(obj));break;case"line":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiateLine(obj));break;case"polyline":current=completeCurrent(objects,current,polygons,vectors),null===current&&(current=getPolyType$1(obj));break;case"vertex":p=instantiateVector(obj);break;case"lwpolyline":current=completeCurrent(objects,current,polygons,vectors),objects.push(instantiatePath2D(obj))}index$7.isA(p)&&polygons.push(p),p&&"vec"in p&&3===p.vec.length&&vectors.push(p),p&&"vec"in p&&2===p.vec.length&&vectors.push(p)}return current=completeCurrent(objects,current,polygons,vectors),objects})(createReader(src,options),options);return objs},translate=(src,options)=>{const reader=createReader(src,options);let code=`// Produced by JSCAD IO Library : DXF Deserializer (${options.version})\n\n`;return code+=((reader,options)=>{const layers=[];let current=null,parts=[],numobjs=0,p=null;for(const obj of reader.objstack)if(p=null,"type"in obj){if("name"in obj){let name=obj.name;name=name.replace(/ /g,"_"),name=name.replace(/-/g,"_"),name=name.replace(/\./g,"_"),obj.name=name}else obj.name="jscad"+numobjs,numobjs+=1;switch(obj.type){case"dxf":break;case"layer":current=translateCurrent(current,layers,parts,options),parts=[],obj.objects=[],obj.lnam="layer"+layers.length,layers.push(obj);break;case"variable":current=translateCurrent(current,layers,parts,options),parts=[],saveVariable(obj,options);break;case"3dface":p=instantiatePolygon(obj,layers,options),null===current&&(current={type:"3dfaces"},current.name="jscad"+numobjs,numobjs+=1);break;case"mesh":current=translateCurrent(current,layers,parts,options),parts=[],translateMesh(obj,layers,options);break;case"arc":current=translateCurrent(current,layers,parts,options),parts=[],translateArc(obj,layers,options);break;case"circle":current=translateCurrent(current,layers,parts,options),parts=[],translateCircle(obj,layers,options);break;case"ellipse":current=translateCurrent(current,layers,parts,options),parts=[],translateEllipse(obj,layers,options);break;case"line":current=translateCurrent(current,layers,parts,options),parts=[],translateLine(obj,layers,options);break;case"polyline":current=translateCurrent(current,layers,parts,options),parts=[],null===current&&(current=getPolyType(obj),current.name="jscad"+numobjs,numobjs+=1);break;case"vertex":p=instantiateVector(obj);break;case"seqend":current=translateCurrent(current,layers,parts,options),parts=[];break;case"lwpolyline":current=translateCurrent(current,layers,parts,options),parts=[],translatePath2D(obj,layers,options)}index$7.isA(p)&&parts.push(p),p&&"vec"in p&&3===p.vec.length&&parts.push(p),p&&"vec"in p&&2===p.vec.length&&parts.push(p)}current=translateCurrent(current,layers,parts,options);let script="import * from '@jscad/modeling'\n\nexport const main = () => {\n let layers = []\n return layers.concat(";return layers.forEach((layer=>{const name=layer.lnam||"Unknown";script+=`${name}(),`})),script+="[])\n}\n",script+="\nconst createPolygon = (listofpoints, color) => {\n let polygon = poly3.create(listofpoints)\n return colorize(color, polygon)\n}\n",layers.forEach((layer=>{script+=(layer=>{let script=`const ${layer.lnam||"Unknown"} = () => {\n`;for(const object of layer.objects)script+=object.script;script+=" return [";for(const object of layer.objects)script+=object.name+",";return script+="]\n}\n",script})(layer)})),script})(reader,options),code};exports.deserialize=(options,src)=>{const defaults={filename:"dxf",version:"3.0.1-alpha.0",output:"script",strict:!0,colorindex:colorIndex,dxf:{angdir:0,insunits:4,pfacevmax:4}};return options=Object.assign({},defaults,options),src=((stringOrArrayBuffer,defaultBinaryEncoding="utf-8")=>"string"==typeof stringOrArrayBuffer?stringOrArrayBuffer:new TextDecoder(defaultBinaryEncoding).decode(new Uint8Array(stringOrArrayBuffer)))(src),"script"===options.output?translate(src,options):instantiate(src,options)},exports.mimeType="image/vnd.dxf",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadDxfDeserializer={}); diff --git a/packages/io/dxf-deserializer/package.json b/packages/io/dxf-deserializer/package.json index ef22997c5..79d1defaf 100644 --- a/packages/io/dxf-deserializer/package.json +++ b/packages/io/dxf-deserializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/dxf-deserializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "DXF Deserializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -33,8 +33,8 @@ ], "license": "MIT", "dependencies": { - "@jscad/modeling": "workspace:3.0.0-alpha.0", - "@jscad/io-utils": "workspace:3.0.0-alpha.0" + "@jscad/io-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0" }, "devDependencies": { "@rollup/plugin-node-resolve": "^15.2.1", diff --git a/packages/io/dxf-serializer/CHANGELOG.md b/packages/io/dxf-serializer/CHANGELOG.md index d173a13ad..e3993c5f2 100644 --- a/packages/io/dxf-serializer/CHANGELOG.md +++ b/packages/io/dxf-serializer/CHANGELOG.md @@ -3,6 +3,17 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/dxf-serializer@2.1.12...@jscad/dxf-serializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) +* **regl-renderer:** added rollup configuration to create ES6 bundle, adjusted imports and exports ([#1259](https://github.com/jscad/OpenJSCAD.org/issues/1259)) ([47a66bc](https://github.com/jscad/OpenJSCAD.org/commit/47a66bc07a137a748ce8571ea5d043ebaab9418d)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/dxf-serializer@2.1.12...@jscad/dxf-serializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/dxf-serializer/dist/jscad-dxf-serializer.es.js b/packages/io/dxf-serializer/dist/jscad-dxf-serializer.es.js index 44afc8d2b..1a65587df 100644 --- a/packages/io/dxf-serializer/dist/jscad-dxf-serializer.es.js +++ b/packages/io/dxf-serializer/dist/jscad-dxf-serializer.es.js @@ -1,19 +1,19 @@ /** * DXF Serializer for JSCAD * @module @jscad/dxf-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ /** * JSCAD Utility functions for arrays * @module @jscad/array-utils - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out}; +const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out}; /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT - */Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const defaults={geom2To:"lwpolyline",geom3To:"3dface",pathTo:"lwpolyline",statusCallback:null,colorIndex:colorIndex};if((options=Object.assign({},defaults,options)).entityId=0,0===(objects=(objects=flatten$1(objects)).filter((object=>index$6.isA(object)||index$a.isA(object)||index$5.isA(object)))).length)throw new Error("only JSCAD geometries can be serialized to DXF");var array;array=((options,...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results})({snap:!0,triangulate:!0},objects),objects=Array.isArray(array)?array:null==array?[]:[array];return[`999\nCreated by JSCAD\n 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1027\n 9\n$ACADMAINTVER\n 70\n8\n 9\n$DWGCODEPAGE\n 3\nANSI_1252\n 9\n$LASTSAVEDBY\n 1\nunknown\n 9\n$REQUIREDVERSIONS\n160\n0\n 9\n$INSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$EXTMIN\n 10\n1e+20\n 20\n1e+20\n 30\n1e+20\n 9\n$EXTMAX\n 10\n-1e+20\n 20\n-1e+20\n 30\n-1e+20\n 9\n$LIMMIN\n 10\n0.0\n 20\n0.0\n 9\n$LIMMAX\n 10\n12.0\n 20\n9.0\n 9\n$ORTHOMODE\n 70\n0\n 9\n$REGENMODE\n 70\n1\n 9\n$FILLMODE\n 70\n1\n 9\n$QTEXTMODE\n 70\n0\n 9\n$MIRRTEXT\n 70\n0\n 9\n$LTSCALE\n 40\n1.0\n 9\n$ATTMODE\n 70\n1\n 9\n$TEXTSIZE\n 40\n0.2\n 9\n$TRACEWID\n 40\n0.05\n 9\n$TEXTSTYLE\n 7\nNotes\n 9\n$CLAYER\n 8\n0\n 9\n$CELTYPE\n 6\nByLayer\n 9\n$CECOLOR\n 62\n256\n 9\n$CELTSCALE\n 40\n1.0\n 9\n$DISPSILH\n 70\n0\n 9\n$DIMSCALE\n 40\n1.0\n 9\n$DIMASZ\n 40\n3.0\n 9\n$DIMEXO\n 40\n1.5\n 9\n$DIMDLI\n 40\n6.0\n 9\n$DIMRND\n 40\n0.0\n 9\n$DIMDLE\n 40\n0.0\n 9\n$DIMEXE\n 40\n3.0\n 9\n$DIMTP\n 40\n0.0\n 9\n$DIMTM\n 40\n0.0\n 9\n$DIMTXT\n 40\n3.0\n 9\n$DIMCEN\n 40\n3.0\n 9\n$DIMTSZ\n 40\n0.0\n 9\n$DIMTOL\n 70\n0\n 9\n$DIMLIM\n 70\n0\n 9\n$DIMTIH\n 70\n0\n 9\n$DIMTOH\n 70\n0\n 9\n$DIMSE1\n 70\n0\n 9\n$DIMSE2\n 70\n0\n 9\n$DIMTAD\n 70\n1\n 9\n$DIMZIN\n 70\n3\n 9\n$DIMBLK\n 1\n\n 9\n$DIMASO\n 70\n1\n 9\n$DIMSHO\n 70\n1\n 9\n$DIMPOST\n 1\n\n 9\n$DIMAPOST\n 1\n\n 9\n$DIMALT\n 70\n0\n 9\n$DIMALTD\n 70\n2\n 9\n$DIMALTF\n 40\n25.4\n 9\n$DIMLFAC\n 40\n1.0\n 9\n$DIMTOFL\n 70\n0\n 9\n$DIMTVP\n 40\n0.0\n 9\n$DIMTIX\n 70\n0\n 9\n$DIMSOXD\n 70\n0\n 9\n$DIMSAH\n 70\n0\n 9\n$DIMBLK1\n 1\n\n 9\n$DIMBLK2\n 1\n\n 9\n$DIMSTYLE\n 2\nCivil-Metric\n 9\n$DIMCLRD\n 70\n0\n 9\n$DIMCLRE\n 70\n0\n 9\n$DIMCLRT\n 70\n0\n 9\n$DIMTFAC\n 40\n1.0\n 9\n$DIMGAP\n 40\n2.0\n 9\n$DIMJUST\n 70\n0\n 9\n$DIMSD1\n 70\n0\n 9\n$DIMSD2\n 70\n0\n 9\n$DIMTOLJ\n 70\n1\n 9\n$DIMTZIN\n 70\n0\n 9\n$DIMALTZ\n 70\n0\n 9\n$DIMALTTZ\n 70\n0\n 9\n$DIMUPT\n 70\n0\n 9\n$DIMDEC\n 70\n2\n 9\n$DIMTDEC\n 70\n2\n 9\n$DIMALTU\n 70\n2\n 9\n$DIMALTTD\n 70\n2\n 9\n$DIMTXSTY\n 7\nStandard\n 9\n$DIMAUNIT\n 70\n0\n 9\n$DIMADEC\n 70\n2\n 9\n$DIMALTRND\n 40\n0.0\n 9\n$DIMAZIN\n 70\n2\n 9\n$DIMDSEP\n 70\n46\n 9\n$DIMATFIT\n 70\n3\n 9\n$DIMFRAC\n 70\n1\n 9\n$DIMLDRBLK\n 1\n\n 9\n$DIMLUNIT\n 70\n2\n 9\n$DIMLWD\n 70\n-2\n 9\n$DIMLWE\n 70\n-2\n 9\n$DIMTMOVE\n 70\n0\n 9\n$DIMFXL\n 40\n1.0\n 9\n$DIMFXLON\n 70\n0\n 9\n$DIMJOGANG\n 40\n0.785398163397\n 9\n$DIMTFILL\n 70\n0\n 9\n$DIMTFILLCLR\n 70\n0\n 9\n$DIMARCSYM\n 70\n0\n 9\n$DIMLTYPE\n 6\n\n 9\n$DIMLTEX1\n 6\n\n 9\n$DIMLTEX2\n 6\n\n 9\n$DIMTXTDIRECTION\n 70\n0\n 9\n$LUNITS\n 70\n2\n 9\n$LUPREC\n 70\n4\n 9\n$SKETCHINC\n 40\n0.1\n 9\n$FILLETRAD\n 40\n0.0\n 9\n$AUNITS\n 70\n4\n 9\n$AUPREC\n 70\n5\n 9\n$MENU\n 1\n.\n 9\n$ELEVATION\n 40\n0.0\n 9\n$PELEVATION\n 40\n0.0\n 9\n$THICKNESS\n 40\n0.0\n 9\n$LIMCHECK\n 70\n0\n 9\n$CHAMFERA\n 40\n0.0\n 9\n$CHAMFERB\n 40\n0.0\n 9\n$CHAMFERC\n 40\n0.0\n 9\n$CHAMFERD\n 40\n0.0\n 9\n$SKPOLY\n 70\n0\n 9\n$TDCREATE\n 40\n2457986.69756\n 9\n$TDUCREATE\n 40\n2455631.2632\n 9\n$TDUPDATE\n 40\n2457986.69756\n 9\n$TDUUPDATE\n 40\n2456436.43179\n 9\n$TDINDWG\n 40\n0.0003490741\n 9\n$TDUSRTIMER\n 40\n0.0003487153\n 9\n$USRTIMER\n 70\n1\n 9\n$ANGBASE\n 50\n0.0\n 9\n$ANGDIR\n 70\n0\n 9\n$PDMODE\n 70\n0\n 9\n$PDSIZE\n 40\n0.0\n 9\n$PLINEWID\n 40\n0.0\n 9\n$SPLFRAME\n 70\n0\n 9\n$SPLINETYPE\n 70\n6\n 9\n$SPLINESEGS\n 70\n8\n 9\n$HANDSEED\n 5\n5C7\n 9\n$SURFTAB1\n 70\n6\n 9\n$SURFTAB2\n 70\n6\n 9\n$SURFTYPE\n 70\n6\n 9\n$SURFU\n 70\n6\n 9\n$SURFV\n 70\n6\n 9\n$UCSBASE\n 2\n\n 9\n$UCSNAME\n 2\n\n 9\n$UCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$UCSORTHOREF\n 2\n\n 9\n$UCSORTHOVIEW\n 70\n0\n 9\n$UCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSBASE\n 2\n\n 9\n$PUCSNAME\n 2\n\n 9\n$PUCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$PUCSORTHOREF\n 2\n\n 9\n$PUCSORTHOVIEW\n 70\n0\n 9\n$PUCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$USERI1\n 70\n0\n 9\n$USERI2\n 70\n0\n 9\n$USERI3\n 70\n0\n 9\n$USERI4\n 70\n0\n 9\n$USERI5\n 70\n0\n 9\n$USERR1\n 40\n0.0\n 9\n$USERR2\n 40\n0.0\n 9\n$USERR3\n 40\n0.0\n 9\n$USERR4\n 40\n0.0\n 9\n$USERR5\n 40\n0.0\n 9\n$WORLDVIEW\n 70\n1\n 9\n$SHADEDGE\n 70\n3\n 9\n$SHADEDIF\n 70\n70\n 9\n$TILEMODE\n 70\n1\n 9\n$MAXACTVP\n 70\n64\n 9\n$PINSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PLIMCHECK\n 70\n0\n 9\n$PEXTMIN\n 10\n0.628866766397\n 20\n0.799999952316\n 30\n0.0\n 9\n$PEXTMAX\n 10\n9.02886638493\n 20\n7.19999957085\n 30\n0.0\n 9\n$PLIMMIN\n 10\n-0.700541819174\n 20\n-0.228100386192\n 9\n$PLIMMAX\n 10\n10.2994579405\n 20\n8.27189937351\n 9\n$UNITMODE\n 70\n0\n 9\n$VISRETAIN\n 70\n1\n 9\n$PLINEGEN\n 70\n0\n 9\n$PSLTSCALE\n 70\n1\n 9\n$TREEDEPTH\n 70\n3020\n 9\n$CMLSTYLE\n 2\nStandard\n 9\n$CMLJUST\n 70\n0\n 9\n$CMLSCALE\n 40\n1.0\n 9\n$PROXYGRAPHICS\n 70\n1\n 9\n$MEASUREMENT\n 70\n1\n 9\n$CELWEIGHT\n370\n-1\n 9\n$ENDCAPS\n280\n0\n 9\n$JOINSTYLE\n280\n0\n 9\n$LWDISPLAY\n290\n0\n 9\n$INSUNITS\n 70\n4\n 9\n$HYPERLINKBASE\n 1\n\n 9\n$STYLESHEET\n 1\n\n 9\n$XEDIT\n290\n1\n 9\n$CEPSNTYPE\n380\n0\n 9\n$PSTYLEMODE\n290\n1\n 9\n$FINGERPRINTGUID\n 2\n{39DB1BDD-BC6C-46D3-A333-DFCC0DC4782D}\n 9\n$VERSIONGUID\n 2\n{69EEBB2D-7039-498F-9366-3F994E4A07E7}\n 9\n$EXTNAMES\n290\n1\n 9\n$PSVPSCALE\n 40\n0.0\n 9\n$OLESTARTUP\n290\n0\n 9\n$SORTENTS\n280\n127\n 9\n$INDEXCTL\n280\n0\n 9\n$HIDETEXT\n280\n1\n 9\n$XCLIPFRAME\n280\n0\n 9\n$HALOGAP\n280\n0\n 9\n$OBSCOLOR\n 70\n257\n 9\n$OBSLTYPE\n280\n0\n 9\n$INTERSECTIONDISPLAY\n280\n0\n 9\n$INTERSECTIONCOLOR\n 70\n257\n 9\n$DIMASSOC\n280\n2\n 9\n$PROJECTNAME\n 1\n\n 9\n$CAMERADISPLAY\n290\n0\n 9\n$LENSLENGTH\n 40\n50.0\n 9\n$CAMERAHEIGHT\n 40\n0.0\n 9\n$STEPSPERSEC\n 40\n2.0\n 9\n$STEPSIZE\n 40\n6.0\n 9\n$3DDWFPREC\n 40\n2.0\n 9\n$PSOLWIDTH\n 40\n0.25\n 9\n$PSOLHEIGHT\n 40\n4.0\n 9\n$LOFTANG1\n 40\n1.57079632679\n 9\n$LOFTANG2\n 40\n1.57079632679\n 9\n$LOFTMAG1\n 40\n0.0\n 9\n$LOFTMAG2\n 40\n0.0\n 9\n$LOFTPARAM\n 70\n7\n 9\n$LOFTNORMALS\n280\n1\n 9\n$LATITUDE\n 40\n37.795\n 9\n$LONGITUDE\n 40\n-122.394\n 9\n$NORTHDIRECTION\n 40\n0.0\n 9\n$TIMEZONE\n 70\n-8000\n 9\n$LIGHTGLYPHDISPLAY\n280\n1\n 9\n$TILEMODELIGHTSYNCH\n280\n1\n 9\n$CMATERIAL\n347\n96\n 9\n$SOLIDHIST\n280\n1\n 9\n$SHOWHIST\n280\n1\n 9\n$DWFFRAME\n280\n2\n 9\n$DGNFRAME\n280\n0\n 9\n$REALWORLDSCALE\n290\n1\n 9\n$INTERFERECOLOR\n 62\n1\n 9\n$INTERFEREOBJVS\n345\nA3\n 9\n$INTERFEREVPVS\n346\nA0\n 9\n$CSHADOW\n280\n0\n 9\n$SHADOWPLANELOCATION\n 40\n0.0\n 0\nENDSEC\n 0\nSECTION\n 2\nCLASSES\n 0\nCLASS\n 1\nACDBDICTIONARYWDFLT\n 2\nAcDbDictionaryWithDefault\n 3\nObjectDBX Classes\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nDICTIONARYVAR\n 2\nAcDbDictionaryVar\n 3\nObjectDBX Classes\n 90\n0\n 91\n15\n280\n0\n281\n0\n 0\nCLASS\n 1\nTABLESTYLE\n 2\nAcDbTableStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nMATERIAL\n 2\nAcDbMaterial\n 3\nObjectDBX Classes\n 90\n1153\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nVISUALSTYLE\n 2\nAcDbVisualStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n26\n280\n0\n281\n0\n 0\nCLASS\n 1\nSCALE\n 2\nAcDbScale\n 3\nObjectDBX Classes\n 90\n1153\n 91\n17\n280\n0\n281\n0\n 0\nCLASS\n 1\nMLEADERSTYLE\n 2\nAcDbMLeaderStyle\n 3\nACDB_MLEADERSTYLE_CLASS\n 90\n4095\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nCELLSTYLEMAP\n 2\nAcDbCellStyleMap\n 3\nObjectDBX Classes\n 90\n1152\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nEXACXREFPANELOBJECT\n 2\nExAcXREFPanelObject\n 3\nEXAC_ESW\n 90\n1025\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nNPOCOLLECTION\n 2\nAcDbImpNonPersistentObjectsCollection\n 3\nObjectDBX Classes\n 90\n1153\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nLAYER_INDEX\n 2\nAcDbLayerIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nSPATIAL_INDEX\n 2\nAcDbSpatialIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nIDBUFFER\n 2\nAcDbIdBuffer\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nDIMASSOC\n 2\nAcDbDimAssoc\n 3\n"AcDbDimAssoc|Product Desc: AcDim ARX App For Dimension|Company: Autodesk, Inc.|WEB Address: www.autodesk.com"\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBSECTIONVIEWSTYLE\n 2\nAcDbSectionViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBDETAILVIEWSTYLE\n 2\nAcDbDetailViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF\n 2\nAcDbRasterImageDef\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nRASTERVARIABLES\n 2\nAcDbRasterVariables\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF_REACTOR\n 2\nAcDbRasterImageDefReactor\n 3\nISM\n 90\n1\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGE\n 2\nAcDbRasterImage\n 3\nISM\n 90\n2175\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nPDFDEFINITION\n 2\nAcDbPdfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nPDFUNDERLAY\n 2\nAcDbPdfReference\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDWFDEFINITION\n 2\nAcDbDwfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDWFUNDERLAY\n 2\nAcDbDwfReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDGNDEFINITION\n 2\nAcDbDgnDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDGNUNDERLAY\n 2\nAcDbDgnReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nENDSEC\n 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nVPORT\n 5\n8\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLTYPE\n 5\n5F\n330\n0\n100\nAcDbSymbolTable\n 70\n7\n 0\nLTYPE\n 5\n14\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByBlock\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n15\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByLayer\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n16\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nContinuous\n 70\n0\n 3\nSolid line\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n1B1\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nCENTER\n 70\n0\n 3\nCenter ____ _ ____ _ ____ _ ____ _ ____ _ ____\n 72\n65\n 73\n4\n 40\n2.0\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B2\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nDASHED\n 70\n0\n 3\nDashed __ __ __ __ __ __ __ __ __ __ __ __ __ _\n 72\n65\n 73\n2\n 40\n0.75\n 49\n0.5\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B3\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nPHANTOM\n 70\n0\n 3\nPhantom ______ __ __ ______ __ __ ______\n 72\n65\n 73\n6\n 40\n2.5\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n39E\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nHIDDEN\n 70\n0\n 3\nHidden __ __ __ __ __ __ __ __ __ __ __ __ __ __\n 72\n65\n 73\n2\n 40\n9.525\n 49\n6.35\n 74\n0\n 49\n-3.175\n 74\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLAYER\n 5\n2\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nLAYER\n 5\n10\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\n0\n 70\n0\n 6\nContinuous\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n1B4\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nView Port\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n21D\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nDefpoints\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nSTYLE\n 5\n3\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nSTYLE\n 5\n11\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nStandard\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\nDC\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\n178\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nNotes\n 70\n0\n 40\n3.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nENDTAB\n 0\nTABLE\n 2\nVIEW\n 5\n6\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nUCS\n 5\n7\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nAPPID\n 5\n9\n330\n0\n100\nAcDbSymbolTable\n 70\n12\n 0\nAPPID\n 5\n12\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD\n 70\n0\n 0\nAPPID\n 5\nDD\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnoPO\n 70\n0\n 0\nAPPID\n 5\nDE\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnotative\n 70\n0\n 0\nAPPID\n 5\nDF\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMJAG\n 70\n0\n 0\nAPPID\n 5\nE0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMTALN\n 70\n0\n 0\nAPPID\n 5\n107\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_MLEADERVER\n 70\n0\n 0\nAPPID\n 5\n1B5\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcAecLayerStandard\n 70\n0\n 0\nAPPID\n 5\n1BA\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_EXEMPT_FROM_CAD_STANDARDS\n 70\n0\n 0\nAPPID\n 5\n237\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMBREAK\n 70\n0\n 0\nAPPID\n 5\n28E\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_PSEXT\n 70\n0\n 0\nAPPID\n 5\n4B0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_NAV_VCDISPLAY\n 70\n0\n 0\nAPPID\n 5\n4E3\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nHATCHBACKGROUNDCOLOR\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nDIMSTYLE\n 5\nA\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n100\nAcDbDimStyleTable\n 71\n3\n340\n242\n340\n27\n340\nE1\n 0\nDIMSTYLE\n105\n27\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nStandard\n 70\n0\n 41\n3.0\n 42\n2.0\n 43\n9.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\nE1\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n3.0\n 42\n2.5\n 43\n10.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nAcadAnnotative\n1000\nAnnotativeData\n1002\n{\n1070\n1\n1070\n1\n1002\n}\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\n242\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nCivil-Metric\n 70\n0\n 41\n3.0\n 42\n1.5\n 43\n6.0\n 44\n3.0\n 73\n0\n 74\n0\n 77\n1\n 78\n3\n 79\n2\n140\n3.0\n141\n3.0\n147\n2.0\n179\n2\n271\n2\n272\n2\n276\n1\n340\n11\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n3.0\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nBLOCK_RECORD\n 5\n1\n330\n0\n100\nAcDbSymbolTable\n 70\n4\n 0\nBLOCK_RECORD\n 5\n1F\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Model_Space\n340\n530\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n58\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Paper_Space\n340\n531\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n238\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_ArchTick\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n23C\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_Open30\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nENDTAB\n 0\nENDSEC\n 0\nSECTION\n 2\nBLOCKS\n 0\nBLOCK\n 5\n23A\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_ArchTick\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_ArchTick\n 1\n\n 0\nENDBLK\n 5\n23B\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n20\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Model_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Model_Space\n 1\n\n 0\nENDBLK\n 5\n21\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n5A\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Paper_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Paper_Space\n 1\n\n 0\nENDBLK\n 5\n5B\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n240\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_Open30\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_Open30\n 1\n\n 0\nENDBLK\n 5\n241\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nENDSEC\n${dxfEntities(objects,options)}\n 0\nSECTION\n 2\nOBJECTS\n 0\nDICTIONARY\n 5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n 3\nACAD_COLOR\n350\n524\n 3\nACAD_GROUP\n350\n525\n 3\nACAD_LAYOUT\n350\n526\n 3\nACAD_MATERIAL\n350\n527\n 3\nACAD_MLEADERSTYLE\n350\n528\n 3\nACAD_MLINESTYLE\n350\n529\n 3\nACAD_PLOTSETTINGS\n350\n52A\n 3\nACAD_PLOTSTYLENAME\n350\n52C\n 3\nACAD_SCALELIST\n350\n52D\n 3\nACAD_TABLESTYLE\n350\n52E\n 3\nACAD_VISUALSTYLE\n350\n52F\n 0\nDICTIONARY\n 5\n524\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n525\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n526\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nModel\n350\n530\n 3\nLayout1\n350\n531\n 0\nDICTIONARY\n 5\n527\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n528\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n529\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52A\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nACDBPLACEHOLDER\n 5\n52B\n330\n52C\n 0\nACDBDICTIONARYWDFLT\n 5\n52C\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nNormal\n350\n52B\n100\nAcDbDictionaryWithDefault\n340\n52B\n 0\nDICTIONARY\n 5\n52D\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52E\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52F\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nLAYOUT\n 5\n530\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n14.53\n 70\n11952\n 72\n0\n 73\n1\n 74\n0\n 7\n\n 75\n0\n147\n0.069\n148\n114.98\n149\n300.29\n100\nAcDbLayout\n 1\nModel\n 70\n1\n 71\n0\n 10\n0.0\n 20\n0.0\n 11\n12.0\n 21\n9.0\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.0\n 24\n0.0\n 34\n0.0\n 15\n0.0\n 25\n0.0\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n1F\n 0\nLAYOUT\n 5\n531\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n1.0\n 70\n688\n 72\n0\n 73\n1\n 74\n5\n 7\nacad.ctb\n 75\n16\n147\n1.0\n148\n0.0\n149\n0.0\n100\nAcDbLayout\n 1\nLayout1\n 70\n1\n 71\n1\n 10\n-0.7\n 20\n-0.23\n 11\n10.3\n 21\n8.27\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.63\n 24\n0.8\n 34\n0.0\n 15\n9.0\n 25\n7.2\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n58\n 0\nENDSEC\n 0\nEOF\n`]},dxfEntities=(objects,options)=>{const entityContents=objects.map(((object,i)=>{if(index$a.isA(object)){const color=object.color,name=object.name,paths=index$a.toOutlines(object).map((outline=>({closed:!0,points:outline,color:color,name:name})));return"polyline"===options.geom2To?PathsToPolyine(paths,options):PathsToLwpolyline(paths,options)}if(index$6.isA(object))return"polyline"===options.geom3To?PolygonsToPolyline(object,options):PolygonsTo3DFaces(object,options);if(index$5.isA(object)){const color=object.color,name=object.name,path={closed:object.isClosed,points:index$5.toPoints(object),color:color,name:name};return PathsToLwpolyline([path],options)}return""}));let section=" 0\nSECTION\n 2\nENTITIES\n";return entityContents.forEach((content=>{content&&(section+=content)})),section+=" 0\nENDSEC",section},PathsToLwpolyline=(paths,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";return paths.forEach(((path,i)=>{if(path.points.length<1)return;const numpointsClosed=path.points.length+(path.closed?1:0);str+=` 0\nLWPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(path,options)}\n 8\n0\n 67\n0\n 62\n${getColorNumber(path,options)}\n 100\nAcDbPolyline\n 90\n${numpointsClosed}\n 70\n${path.closed?1:0}\n`;for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped];str+=` 10\n${point[0]}\n 20\n${point[1]}\n`}options.statusCallback&&options.statusCallback({progress:100*i/paths.length})})),options.statusCallback&&options.statusCallback({progress:100}),[str]},PathsToPolyine=(paths,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";return paths.forEach(((path,i)=>{const numpointsClosed=path.points.length+(path.closed?1:0);str+=` 0\nPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(path,options)}\n 8\n0\n 62\n${getColorNumber(path,options)}\n 100\nAcDb2dPolyline\n`;for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped];str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb2dVertex\n 10\n${point[0]}\n 20\n${point[1]}\n`}str+=` 0\nSEQEND\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n`,options.statusCallback&&options.statusCallback({progress:100*i/paths.length})})),options.statusCallback&&options.statusCallback({progress:100}),[str]},PolygonsTo3DFaces=(object,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";const polygons=index$6.toPolygons(object),objectColor=getColorNumber(object,options);return polygons.forEach(((polygon,i)=>{const polyColor=polygon.color?getColorNumber(polygon,options):objectColor;polygonToTriangles(polygon).forEach(((triangle,i)=>{str+=triangleTo3DFaces(triangle,options,polyColor)}))})),options.statusCallback&&options.statusCallback({progress:100}),[str]},polygonToTriangles=polygon=>{const length=polygon.vertices.length-2;if(length<1)return[];const pivot=polygon.vertices[0],triangles=[];for(let i=0;i{const corner10=triangle[0],corner11=triangle[1],corner12=triangle[2],corner13=triangle[2];return` 0\n3DFACE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 62\n${color}\n 100\nAcDbFace\n 70\n0\n 10\n${corner10[0]}\n 20\n${corner10[1]}\n 30\n${corner10[2]}\n 11\n${corner11[0]}\n 21\n${corner11[1]}\n 31\n${corner11[2]}\n 12\n${corner12[0]}\n 22\n${corner12[1]}\n 32\n${corner12[2]}\n 13\n${corner13[0]}\n 23\n${corner13[1]}\n 33\n${corner13[2]}\n`},PolygonsToPolyline=(object,options)=>{let str="";const mesh=polygons2polyfaces(index$6.toPolygons(object));return mesh.faces.length>0&&(str+=` 0\nPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(object,options)}\n 8\n0\n 62\n${getColorNumber(object,options)}\n 100\nAcDb3dPolyline\n 70\n64\n 71\n${mesh.vertices.length}\n 72\n${mesh.faces.length}\n`,mesh.vertices.forEach((vertex=>{str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n${vertex[0]}\n 20\n${vertex[1]}\n 30\n${vertex[2]}\n 70\n192\n`})),mesh.faces.forEach((face=>{str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n0\n 20\n0\n 30\n0\n 70\n128\n 71\n${face[0]}\n 72\n${face[1]}\n 73\n${face[2]}\n 74\n${face[3]}\n`}))),[str]},polygons2polyfaces=polygons=>{const faces=[],vertices=[];for(let i=0;i{options.entityId++;const padded="00000"+options.entityId.toString(16).toUpperCase();return"CAD"+padded.substr(padded.length-5)},getName=(object,options)=>{if(object.name)return object.name;const padded="00000"+options.entityId.toString(16).toUpperCase();return"CAD"+padded.substr(padded.length-5)},getColorNumber=(object,options)=>{let colorNumber=256;if(object.color){const r=Math.floor(255*object.color[0]),g=Math.floor(255*object.color[1]),b=Math.floor(255*object.color[2]),index=options.colorIndex;let closest=765;for(let i=1;i{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},colorIndex=[[0,0,0,255],[255,0,0,255],[255,255,0,255],[0,255,0,255],[0,255,255,255],[0,0,255,255],[255,0,255,255],[255,255,255,255],[128,128,128,255],[192,192,192,255],[255,0,0,255],[255,127,127,255],[165,0,0,255],[165,82,82,255],[127,0,0,255],[127,63,63,255],[76,0,0,255],[76,38,38,255],[38,0,0,255],[38,19,19,255],[255,63,0,255],[255,159,127,255],[165,41,0,255],[165,103,82,255],[127,31,0,255],[127,79,63,255],[76,19,0,255],[76,47,38,255],[38,9,0,255],[38,28,19,255],[255,127,0,255],[255,191,127,255],[165,82,0,255],[165,124,82,255],[127,63,0,255],[127,95,63,255],[76,38,0,255],[76,57,38,255],[38,19,0,255],[38,28,19,255],[255,191,0,255],[255,223,127,255],[165,124,0,255],[165,145,82,255],[127,95,0,255],[127,111,63,255],[76,57,0,255],[76,66,38,255],[38,28,0,255],[38,33,19,255],[255,255,0,255],[255,255,127,255],[165,165,0,255],[165,165,82,255],[127,127,0,255],[127,127,63,255],[76,76,0,255],[76,76,38,255],[38,38,0,255],[38,38,19,255],[191,255,0,255],[223,255,127,255],[124,165,0,255],[145,165,82,255],[95,127,0,255],[111,127,63,255],[57,76,0,255],[66,76,38,255],[28,38,0,255],[33,38,19,255],[127,255,0,255],[191,255,127,255],[82,165,0,255],[124,165,82,255],[63,127,0,255],[95,127,63,255],[38,76,0,255],[57,76,38,255],[19,38,0,255],[28,38,19,255],[63,255,0,255],[159,255,127,255],[41,165,0,255],[103,165,82,255],[31,127,0,255],[79,127,63,255],[19,76,0,255],[47,76,38,255],[9,38,0,255],[23,38,19,255],[0,255,0,255],[125,255,127,255],[0,165,0,255],[82,165,82,255],[0,127,0,255],[63,127,63,255],[0,76,0,255],[38,76,38,255],[0,38,0,255],[19,38,19,255],[0,255,63,255],[127,255,159,255],[0,165,41,255],[82,165,103,255],[0,127,31,255],[63,127,79,255],[0,76,19,255],[38,76,47,255],[0,38,9,255],[19,88,23,255],[0,255,127,255],[127,255,191,255],[0,165,82,255],[82,165,124,255],[0,127,63,255],[63,127,95,255],[0,76,38,255],[38,76,57,255],[0,38,19,255],[19,88,28,255],[0,255,191,255],[127,255,223,255],[0,165,124,255],[82,165,145,255],[0,127,95,255],[63,127,111,255],[0,76,57,255],[38,76,66,255],[0,38,28,255],[19,88,88,255],[0,255,255,255],[127,255,255,255],[0,165,165,255],[82,165,165,255],[0,127,127,255],[63,127,127,255],[0,76,76,255],[38,76,76,255],[0,38,38,255],[19,88,88,255],[0,191,255,255],[127,223,255,255],[0,124,165,255],[82,145,165,255],[0,95,127,255],[63,111,217,255],[0,57,76,255],[38,66,126,255],[0,28,38,255],[19,88,88,255],[0,127,255,255],[127,191,255,255],[0,82,165,255],[82,124,165,255],[0,63,127,255],[63,95,127,255],[0,38,76,255],[38,57,126,255],[0,19,38,255],[19,28,88,255],[0,63,255,255],[127,159,255,255],[0,41,165,255],[82,103,165,255],[0,31,127,255],[63,79,127,255],[0,19,76,255],[38,47,126,255],[0,9,38,255],[19,23,88,255],[0,0,255,255],[127,127,255,255],[0,0,165,255],[82,82,165,255],[0,0,127,255],[63,63,127,255],[0,0,76,255],[38,38,126,255],[0,0,38,255],[19,19,88,255],[63,0,255,255],[159,127,255,255],[41,0,165,255],[103,82,165,255],[31,0,127,255],[79,63,127,255],[19,0,76,255],[47,38,126,255],[9,0,38,255],[23,19,88,255],[127,0,255,255],[191,127,255,255],[165,0,82,255],[124,82,165,255],[63,0,127,255],[95,63,127,255],[38,0,76,255],[57,38,126,255],[19,0,38,255],[28,19,88,255],[191,0,255,255],[223,127,255,255],[124,0,165,255],[142,82,165,255],[95,0,127,255],[111,63,127,255],[57,0,76,255],[66,38,76,255],[28,0,38,255],[88,19,88,255],[255,0,255,255],[255,127,255,255],[165,0,165,255],[165,82,165,255],[127,0,127,255],[127,63,127,255],[76,0,76,255],[76,38,76,255],[38,0,38,255],[88,19,88,255],[255,0,191,255],[255,127,223,255],[165,0,124,255],[165,82,145,255],[127,0,95,255],[127,63,111,255],[76,0,57,255],[76,38,66,255],[38,0,28,255],[88,19,88,255],[255,0,127,255],[255,127,191,255],[165,0,82,255],[165,82,124,255],[127,0,63,255],[127,63,95,255],[76,0,38,255],[76,38,57,255],[38,0,19,255],[88,19,28,255],[255,0,63,255],[255,127,159,255],[165,0,41,255],[165,82,103,255],[127,0,31,255],[127,63,79,255],[76,0,19,255],[76,38,47,255],[38,0,9,255],[88,19,23,255],[0,0,0,255],[101,101,101,255],[102,102,102,255],[153,153,153,255],[204,204,204,255],[255,255,255,255]],mimeType="image/vnd.dxf",serialize=(options,...objects)=>{const defaults={geom2To:"lwpolyline",geom3To:"3dface",pathTo:"lwpolyline",statusCallback:null,colorIndex:colorIndex};if((options=Object.assign({},defaults,options)).entityId=0,0===(objects=(objects=flatten$1(objects)).filter((object=>index$6.isA(object)||index$a.isA(object)||index$5.isA(object)))).length)throw new Error("only JSCAD geometries can be serialized to DXF");var array;array=generalize({snap:!0,triangulate:!0},objects),objects=Array.isArray(array)?array:null==array?[]:[array];return[`999\nCreated by JSCAD\n 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1027\n 9\n$ACADMAINTVER\n 70\n8\n 9\n$DWGCODEPAGE\n 3\nANSI_1252\n 9\n$LASTSAVEDBY\n 1\nunknown\n 9\n$REQUIREDVERSIONS\n160\n0\n 9\n$INSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$EXTMIN\n 10\n1e+20\n 20\n1e+20\n 30\n1e+20\n 9\n$EXTMAX\n 10\n-1e+20\n 20\n-1e+20\n 30\n-1e+20\n 9\n$LIMMIN\n 10\n0.0\n 20\n0.0\n 9\n$LIMMAX\n 10\n12.0\n 20\n9.0\n 9\n$ORTHOMODE\n 70\n0\n 9\n$REGENMODE\n 70\n1\n 9\n$FILLMODE\n 70\n1\n 9\n$QTEXTMODE\n 70\n0\n 9\n$MIRRTEXT\n 70\n0\n 9\n$LTSCALE\n 40\n1.0\n 9\n$ATTMODE\n 70\n1\n 9\n$TEXTSIZE\n 40\n0.2\n 9\n$TRACEWID\n 40\n0.05\n 9\n$TEXTSTYLE\n 7\nNotes\n 9\n$CLAYER\n 8\n0\n 9\n$CELTYPE\n 6\nByLayer\n 9\n$CECOLOR\n 62\n256\n 9\n$CELTSCALE\n 40\n1.0\n 9\n$DISPSILH\n 70\n0\n 9\n$DIMSCALE\n 40\n1.0\n 9\n$DIMASZ\n 40\n3.0\n 9\n$DIMEXO\n 40\n1.5\n 9\n$DIMDLI\n 40\n6.0\n 9\n$DIMRND\n 40\n0.0\n 9\n$DIMDLE\n 40\n0.0\n 9\n$DIMEXE\n 40\n3.0\n 9\n$DIMTP\n 40\n0.0\n 9\n$DIMTM\n 40\n0.0\n 9\n$DIMTXT\n 40\n3.0\n 9\n$DIMCEN\n 40\n3.0\n 9\n$DIMTSZ\n 40\n0.0\n 9\n$DIMTOL\n 70\n0\n 9\n$DIMLIM\n 70\n0\n 9\n$DIMTIH\n 70\n0\n 9\n$DIMTOH\n 70\n0\n 9\n$DIMSE1\n 70\n0\n 9\n$DIMSE2\n 70\n0\n 9\n$DIMTAD\n 70\n1\n 9\n$DIMZIN\n 70\n3\n 9\n$DIMBLK\n 1\n\n 9\n$DIMASO\n 70\n1\n 9\n$DIMSHO\n 70\n1\n 9\n$DIMPOST\n 1\n\n 9\n$DIMAPOST\n 1\n\n 9\n$DIMALT\n 70\n0\n 9\n$DIMALTD\n 70\n2\n 9\n$DIMALTF\n 40\n25.4\n 9\n$DIMLFAC\n 40\n1.0\n 9\n$DIMTOFL\n 70\n0\n 9\n$DIMTVP\n 40\n0.0\n 9\n$DIMTIX\n 70\n0\n 9\n$DIMSOXD\n 70\n0\n 9\n$DIMSAH\n 70\n0\n 9\n$DIMBLK1\n 1\n\n 9\n$DIMBLK2\n 1\n\n 9\n$DIMSTYLE\n 2\nCivil-Metric\n 9\n$DIMCLRD\n 70\n0\n 9\n$DIMCLRE\n 70\n0\n 9\n$DIMCLRT\n 70\n0\n 9\n$DIMTFAC\n 40\n1.0\n 9\n$DIMGAP\n 40\n2.0\n 9\n$DIMJUST\n 70\n0\n 9\n$DIMSD1\n 70\n0\n 9\n$DIMSD2\n 70\n0\n 9\n$DIMTOLJ\n 70\n1\n 9\n$DIMTZIN\n 70\n0\n 9\n$DIMALTZ\n 70\n0\n 9\n$DIMALTTZ\n 70\n0\n 9\n$DIMUPT\n 70\n0\n 9\n$DIMDEC\n 70\n2\n 9\n$DIMTDEC\n 70\n2\n 9\n$DIMALTU\n 70\n2\n 9\n$DIMALTTD\n 70\n2\n 9\n$DIMTXSTY\n 7\nStandard\n 9\n$DIMAUNIT\n 70\n0\n 9\n$DIMADEC\n 70\n2\n 9\n$DIMALTRND\n 40\n0.0\n 9\n$DIMAZIN\n 70\n2\n 9\n$DIMDSEP\n 70\n46\n 9\n$DIMATFIT\n 70\n3\n 9\n$DIMFRAC\n 70\n1\n 9\n$DIMLDRBLK\n 1\n\n 9\n$DIMLUNIT\n 70\n2\n 9\n$DIMLWD\n 70\n-2\n 9\n$DIMLWE\n 70\n-2\n 9\n$DIMTMOVE\n 70\n0\n 9\n$DIMFXL\n 40\n1.0\n 9\n$DIMFXLON\n 70\n0\n 9\n$DIMJOGANG\n 40\n0.785398163397\n 9\n$DIMTFILL\n 70\n0\n 9\n$DIMTFILLCLR\n 70\n0\n 9\n$DIMARCSYM\n 70\n0\n 9\n$DIMLTYPE\n 6\n\n 9\n$DIMLTEX1\n 6\n\n 9\n$DIMLTEX2\n 6\n\n 9\n$DIMTXTDIRECTION\n 70\n0\n 9\n$LUNITS\n 70\n2\n 9\n$LUPREC\n 70\n4\n 9\n$SKETCHINC\n 40\n0.1\n 9\n$FILLETRAD\n 40\n0.0\n 9\n$AUNITS\n 70\n4\n 9\n$AUPREC\n 70\n5\n 9\n$MENU\n 1\n.\n 9\n$ELEVATION\n 40\n0.0\n 9\n$PELEVATION\n 40\n0.0\n 9\n$THICKNESS\n 40\n0.0\n 9\n$LIMCHECK\n 70\n0\n 9\n$CHAMFERA\n 40\n0.0\n 9\n$CHAMFERB\n 40\n0.0\n 9\n$CHAMFERC\n 40\n0.0\n 9\n$CHAMFERD\n 40\n0.0\n 9\n$SKPOLY\n 70\n0\n 9\n$TDCREATE\n 40\n2457986.69756\n 9\n$TDUCREATE\n 40\n2455631.2632\n 9\n$TDUPDATE\n 40\n2457986.69756\n 9\n$TDUUPDATE\n 40\n2456436.43179\n 9\n$TDINDWG\n 40\n0.0003490741\n 9\n$TDUSRTIMER\n 40\n0.0003487153\n 9\n$USRTIMER\n 70\n1\n 9\n$ANGBASE\n 50\n0.0\n 9\n$ANGDIR\n 70\n0\n 9\n$PDMODE\n 70\n0\n 9\n$PDSIZE\n 40\n0.0\n 9\n$PLINEWID\n 40\n0.0\n 9\n$SPLFRAME\n 70\n0\n 9\n$SPLINETYPE\n 70\n6\n 9\n$SPLINESEGS\n 70\n8\n 9\n$HANDSEED\n 5\n5C7\n 9\n$SURFTAB1\n 70\n6\n 9\n$SURFTAB2\n 70\n6\n 9\n$SURFTYPE\n 70\n6\n 9\n$SURFU\n 70\n6\n 9\n$SURFV\n 70\n6\n 9\n$UCSBASE\n 2\n\n 9\n$UCSNAME\n 2\n\n 9\n$UCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$UCSORTHOREF\n 2\n\n 9\n$UCSORTHOVIEW\n 70\n0\n 9\n$UCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSBASE\n 2\n\n 9\n$PUCSNAME\n 2\n\n 9\n$PUCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$PUCSORTHOREF\n 2\n\n 9\n$PUCSORTHOVIEW\n 70\n0\n 9\n$PUCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$USERI1\n 70\n0\n 9\n$USERI2\n 70\n0\n 9\n$USERI3\n 70\n0\n 9\n$USERI4\n 70\n0\n 9\n$USERI5\n 70\n0\n 9\n$USERR1\n 40\n0.0\n 9\n$USERR2\n 40\n0.0\n 9\n$USERR3\n 40\n0.0\n 9\n$USERR4\n 40\n0.0\n 9\n$USERR5\n 40\n0.0\n 9\n$WORLDVIEW\n 70\n1\n 9\n$SHADEDGE\n 70\n3\n 9\n$SHADEDIF\n 70\n70\n 9\n$TILEMODE\n 70\n1\n 9\n$MAXACTVP\n 70\n64\n 9\n$PINSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PLIMCHECK\n 70\n0\n 9\n$PEXTMIN\n 10\n0.628866766397\n 20\n0.799999952316\n 30\n0.0\n 9\n$PEXTMAX\n 10\n9.02886638493\n 20\n7.19999957085\n 30\n0.0\n 9\n$PLIMMIN\n 10\n-0.700541819174\n 20\n-0.228100386192\n 9\n$PLIMMAX\n 10\n10.2994579405\n 20\n8.27189937351\n 9\n$UNITMODE\n 70\n0\n 9\n$VISRETAIN\n 70\n1\n 9\n$PLINEGEN\n 70\n0\n 9\n$PSLTSCALE\n 70\n1\n 9\n$TREEDEPTH\n 70\n3020\n 9\n$CMLSTYLE\n 2\nStandard\n 9\n$CMLJUST\n 70\n0\n 9\n$CMLSCALE\n 40\n1.0\n 9\n$PROXYGRAPHICS\n 70\n1\n 9\n$MEASUREMENT\n 70\n1\n 9\n$CELWEIGHT\n370\n-1\n 9\n$ENDCAPS\n280\n0\n 9\n$JOINSTYLE\n280\n0\n 9\n$LWDISPLAY\n290\n0\n 9\n$INSUNITS\n 70\n4\n 9\n$HYPERLINKBASE\n 1\n\n 9\n$STYLESHEET\n 1\n\n 9\n$XEDIT\n290\n1\n 9\n$CEPSNTYPE\n380\n0\n 9\n$PSTYLEMODE\n290\n1\n 9\n$FINGERPRINTGUID\n 2\n{39DB1BDD-BC6C-46D3-A333-DFCC0DC4782D}\n 9\n$VERSIONGUID\n 2\n{69EEBB2D-7039-498F-9366-3F994E4A07E7}\n 9\n$EXTNAMES\n290\n1\n 9\n$PSVPSCALE\n 40\n0.0\n 9\n$OLESTARTUP\n290\n0\n 9\n$SORTENTS\n280\n127\n 9\n$INDEXCTL\n280\n0\n 9\n$HIDETEXT\n280\n1\n 9\n$XCLIPFRAME\n280\n0\n 9\n$HALOGAP\n280\n0\n 9\n$OBSCOLOR\n 70\n257\n 9\n$OBSLTYPE\n280\n0\n 9\n$INTERSECTIONDISPLAY\n280\n0\n 9\n$INTERSECTIONCOLOR\n 70\n257\n 9\n$DIMASSOC\n280\n2\n 9\n$PROJECTNAME\n 1\n\n 9\n$CAMERADISPLAY\n290\n0\n 9\n$LENSLENGTH\n 40\n50.0\n 9\n$CAMERAHEIGHT\n 40\n0.0\n 9\n$STEPSPERSEC\n 40\n2.0\n 9\n$STEPSIZE\n 40\n6.0\n 9\n$3DDWFPREC\n 40\n2.0\n 9\n$PSOLWIDTH\n 40\n0.25\n 9\n$PSOLHEIGHT\n 40\n4.0\n 9\n$LOFTANG1\n 40\n1.57079632679\n 9\n$LOFTANG2\n 40\n1.57079632679\n 9\n$LOFTMAG1\n 40\n0.0\n 9\n$LOFTMAG2\n 40\n0.0\n 9\n$LOFTPARAM\n 70\n7\n 9\n$LOFTNORMALS\n280\n1\n 9\n$LATITUDE\n 40\n37.795\n 9\n$LONGITUDE\n 40\n-122.394\n 9\n$NORTHDIRECTION\n 40\n0.0\n 9\n$TIMEZONE\n 70\n-8000\n 9\n$LIGHTGLYPHDISPLAY\n280\n1\n 9\n$TILEMODELIGHTSYNCH\n280\n1\n 9\n$CMATERIAL\n347\n96\n 9\n$SOLIDHIST\n280\n1\n 9\n$SHOWHIST\n280\n1\n 9\n$DWFFRAME\n280\n2\n 9\n$DGNFRAME\n280\n0\n 9\n$REALWORLDSCALE\n290\n1\n 9\n$INTERFERECOLOR\n 62\n1\n 9\n$INTERFEREOBJVS\n345\nA3\n 9\n$INTERFEREVPVS\n346\nA0\n 9\n$CSHADOW\n280\n0\n 9\n$SHADOWPLANELOCATION\n 40\n0.0\n 0\nENDSEC\n 0\nSECTION\n 2\nCLASSES\n 0\nCLASS\n 1\nACDBDICTIONARYWDFLT\n 2\nAcDbDictionaryWithDefault\n 3\nObjectDBX Classes\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nDICTIONARYVAR\n 2\nAcDbDictionaryVar\n 3\nObjectDBX Classes\n 90\n0\n 91\n15\n280\n0\n281\n0\n 0\nCLASS\n 1\nTABLESTYLE\n 2\nAcDbTableStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nMATERIAL\n 2\nAcDbMaterial\n 3\nObjectDBX Classes\n 90\n1153\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nVISUALSTYLE\n 2\nAcDbVisualStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n26\n280\n0\n281\n0\n 0\nCLASS\n 1\nSCALE\n 2\nAcDbScale\n 3\nObjectDBX Classes\n 90\n1153\n 91\n17\n280\n0\n281\n0\n 0\nCLASS\n 1\nMLEADERSTYLE\n 2\nAcDbMLeaderStyle\n 3\nACDB_MLEADERSTYLE_CLASS\n 90\n4095\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nCELLSTYLEMAP\n 2\nAcDbCellStyleMap\n 3\nObjectDBX Classes\n 90\n1152\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nEXACXREFPANELOBJECT\n 2\nExAcXREFPanelObject\n 3\nEXAC_ESW\n 90\n1025\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nNPOCOLLECTION\n 2\nAcDbImpNonPersistentObjectsCollection\n 3\nObjectDBX Classes\n 90\n1153\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nLAYER_INDEX\n 2\nAcDbLayerIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nSPATIAL_INDEX\n 2\nAcDbSpatialIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nIDBUFFER\n 2\nAcDbIdBuffer\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nDIMASSOC\n 2\nAcDbDimAssoc\n 3\n"AcDbDimAssoc|Product Desc: AcDim ARX App For Dimension|Company: Autodesk, Inc.|WEB Address: www.autodesk.com"\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBSECTIONVIEWSTYLE\n 2\nAcDbSectionViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBDETAILVIEWSTYLE\n 2\nAcDbDetailViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF\n 2\nAcDbRasterImageDef\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nRASTERVARIABLES\n 2\nAcDbRasterVariables\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF_REACTOR\n 2\nAcDbRasterImageDefReactor\n 3\nISM\n 90\n1\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGE\n 2\nAcDbRasterImage\n 3\nISM\n 90\n2175\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nPDFDEFINITION\n 2\nAcDbPdfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nPDFUNDERLAY\n 2\nAcDbPdfReference\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDWFDEFINITION\n 2\nAcDbDwfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDWFUNDERLAY\n 2\nAcDbDwfReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDGNDEFINITION\n 2\nAcDbDgnDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDGNUNDERLAY\n 2\nAcDbDgnReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nENDSEC\n 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nVPORT\n 5\n8\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLTYPE\n 5\n5F\n330\n0\n100\nAcDbSymbolTable\n 70\n7\n 0\nLTYPE\n 5\n14\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByBlock\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n15\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByLayer\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n16\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nContinuous\n 70\n0\n 3\nSolid line\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n1B1\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nCENTER\n 70\n0\n 3\nCenter ____ _ ____ _ ____ _ ____ _ ____ _ ____\n 72\n65\n 73\n4\n 40\n2.0\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B2\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nDASHED\n 70\n0\n 3\nDashed __ __ __ __ __ __ __ __ __ __ __ __ __ _\n 72\n65\n 73\n2\n 40\n0.75\n 49\n0.5\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B3\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nPHANTOM\n 70\n0\n 3\nPhantom ______ __ __ ______ __ __ ______\n 72\n65\n 73\n6\n 40\n2.5\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n39E\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nHIDDEN\n 70\n0\n 3\nHidden __ __ __ __ __ __ __ __ __ __ __ __ __ __\n 72\n65\n 73\n2\n 40\n9.525\n 49\n6.35\n 74\n0\n 49\n-3.175\n 74\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLAYER\n 5\n2\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nLAYER\n 5\n10\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\n0\n 70\n0\n 6\nContinuous\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n1B4\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nView Port\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n21D\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nDefpoints\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nSTYLE\n 5\n3\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nSTYLE\n 5\n11\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nStandard\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\nDC\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\n178\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nNotes\n 70\n0\n 40\n3.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nENDTAB\n 0\nTABLE\n 2\nVIEW\n 5\n6\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nUCS\n 5\n7\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nAPPID\n 5\n9\n330\n0\n100\nAcDbSymbolTable\n 70\n12\n 0\nAPPID\n 5\n12\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD\n 70\n0\n 0\nAPPID\n 5\nDD\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnoPO\n 70\n0\n 0\nAPPID\n 5\nDE\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnotative\n 70\n0\n 0\nAPPID\n 5\nDF\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMJAG\n 70\n0\n 0\nAPPID\n 5\nE0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMTALN\n 70\n0\n 0\nAPPID\n 5\n107\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_MLEADERVER\n 70\n0\n 0\nAPPID\n 5\n1B5\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcAecLayerStandard\n 70\n0\n 0\nAPPID\n 5\n1BA\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_EXEMPT_FROM_CAD_STANDARDS\n 70\n0\n 0\nAPPID\n 5\n237\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMBREAK\n 70\n0\n 0\nAPPID\n 5\n28E\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_PSEXT\n 70\n0\n 0\nAPPID\n 5\n4B0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_NAV_VCDISPLAY\n 70\n0\n 0\nAPPID\n 5\n4E3\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nHATCHBACKGROUNDCOLOR\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nDIMSTYLE\n 5\nA\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n100\nAcDbDimStyleTable\n 71\n3\n340\n242\n340\n27\n340\nE1\n 0\nDIMSTYLE\n105\n27\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nStandard\n 70\n0\n 41\n3.0\n 42\n2.0\n 43\n9.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\nE1\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n3.0\n 42\n2.5\n 43\n10.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nAcadAnnotative\n1000\nAnnotativeData\n1002\n{\n1070\n1\n1070\n1\n1002\n}\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\n242\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nCivil-Metric\n 70\n0\n 41\n3.0\n 42\n1.5\n 43\n6.0\n 44\n3.0\n 73\n0\n 74\n0\n 77\n1\n 78\n3\n 79\n2\n140\n3.0\n141\n3.0\n147\n2.0\n179\n2\n271\n2\n272\n2\n276\n1\n340\n11\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n3.0\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nBLOCK_RECORD\n 5\n1\n330\n0\n100\nAcDbSymbolTable\n 70\n4\n 0\nBLOCK_RECORD\n 5\n1F\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Model_Space\n340\n530\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n58\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Paper_Space\n340\n531\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n238\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_ArchTick\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n23C\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_Open30\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nENDTAB\n 0\nENDSEC\n 0\nSECTION\n 2\nBLOCKS\n 0\nBLOCK\n 5\n23A\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_ArchTick\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_ArchTick\n 1\n\n 0\nENDBLK\n 5\n23B\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n20\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Model_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Model_Space\n 1\n\n 0\nENDBLK\n 5\n21\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n5A\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Paper_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Paper_Space\n 1\n\n 0\nENDBLK\n 5\n5B\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n240\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_Open30\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_Open30\n 1\n\n 0\nENDBLK\n 5\n241\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nENDSEC\n${dxfEntities(objects,options)}\n 0\nSECTION\n 2\nOBJECTS\n 0\nDICTIONARY\n 5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n 3\nACAD_COLOR\n350\n524\n 3\nACAD_GROUP\n350\n525\n 3\nACAD_LAYOUT\n350\n526\n 3\nACAD_MATERIAL\n350\n527\n 3\nACAD_MLEADERSTYLE\n350\n528\n 3\nACAD_MLINESTYLE\n350\n529\n 3\nACAD_PLOTSETTINGS\n350\n52A\n 3\nACAD_PLOTSTYLENAME\n350\n52C\n 3\nACAD_SCALELIST\n350\n52D\n 3\nACAD_TABLESTYLE\n350\n52E\n 3\nACAD_VISUALSTYLE\n350\n52F\n 0\nDICTIONARY\n 5\n524\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n525\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n526\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nModel\n350\n530\n 3\nLayout1\n350\n531\n 0\nDICTIONARY\n 5\n527\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n528\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n529\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52A\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nACDBPLACEHOLDER\n 5\n52B\n330\n52C\n 0\nACDBDICTIONARYWDFLT\n 5\n52C\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nNormal\n350\n52B\n100\nAcDbDictionaryWithDefault\n340\n52B\n 0\nDICTIONARY\n 5\n52D\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52E\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52F\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nLAYOUT\n 5\n530\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n14.53\n 70\n11952\n 72\n0\n 73\n1\n 74\n0\n 7\n\n 75\n0\n147\n0.069\n148\n114.98\n149\n300.29\n100\nAcDbLayout\n 1\nModel\n 70\n1\n 71\n0\n 10\n0.0\n 20\n0.0\n 11\n12.0\n 21\n9.0\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.0\n 24\n0.0\n 34\n0.0\n 15\n0.0\n 25\n0.0\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n1F\n 0\nLAYOUT\n 5\n531\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n1.0\n 70\n688\n 72\n0\n 73\n1\n 74\n5\n 7\nacad.ctb\n 75\n16\n147\n1.0\n148\n0.0\n149\n0.0\n100\nAcDbLayout\n 1\nLayout1\n 70\n1\n 71\n1\n 10\n-0.7\n 20\n-0.23\n 11\n10.3\n 21\n8.27\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.63\n 24\n0.8\n 34\n0.0\n 15\n9.0\n 25\n7.2\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n58\n 0\nENDSEC\n 0\nEOF\n`]},dxfEntities=(objects,options)=>{const entityContents=objects.map(((object,i)=>{if(index$a.isA(object)){const color=object.color,name=object.name,paths=index$a.toOutlines(object).map((outline=>({closed:!0,points:outline,color:color,name:name})));return"polyline"===options.geom2To?PathsToPolyine(paths,options):PathsToLwpolyline(paths,options)}if(index$6.isA(object))return"polyline"===options.geom3To?PolygonsToPolyline(object,options):PolygonsTo3DFaces(object,options);if(index$5.isA(object)){const color=object.color,name=object.name,path={closed:object.isClosed,points:index$5.toPoints(object),color:color,name:name};return PathsToLwpolyline([path],options)}return""}));let section=" 0\nSECTION\n 2\nENTITIES\n";return entityContents.forEach((content=>{content&&(section+=content)})),section+=" 0\nENDSEC",section},PathsToLwpolyline=(paths,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";return paths.forEach(((path,i)=>{if(path.points.length<1)return;const numpointsClosed=path.points.length+(path.closed?1:0);str+=` 0\nLWPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(path,options)}\n 8\n0\n 67\n0\n 62\n${getColorNumber(path,options)}\n 100\nAcDbPolyline\n 90\n${numpointsClosed}\n 70\n${path.closed?1:0}\n`;for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped];str+=` 10\n${point[0]}\n 20\n${point[1]}\n`}options.statusCallback&&options.statusCallback({progress:100*i/paths.length})})),options.statusCallback&&options.statusCallback({progress:100}),[str]},PathsToPolyine=(paths,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";return paths.forEach(((path,i)=>{const numpointsClosed=path.points.length+(path.closed?1:0);str+=` 0\nPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(path,options)}\n 8\n0\n 62\n${getColorNumber(path,options)}\n 100\nAcDb2dPolyline\n`;for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped];str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb2dVertex\n 10\n${point[0]}\n 20\n${point[1]}\n`}str+=` 0\nSEQEND\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n`,options.statusCallback&&options.statusCallback({progress:100*i/paths.length})})),options.statusCallback&&options.statusCallback({progress:100}),[str]},PolygonsTo3DFaces=(object,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";const polygons=index$6.toPolygons(object),objectColor=getColorNumber(object,options);return polygons.forEach(((polygon,i)=>{const polyColor=polygon.color?getColorNumber(polygon,options):objectColor;polygonToTriangles(polygon).forEach(((triangle,i)=>{str+=triangleTo3DFaces(triangle,options,polyColor)}))})),options.statusCallback&&options.statusCallback({progress:100}),[str]},polygonToTriangles=polygon=>{const length=polygon.vertices.length-2;if(length<1)return[];const pivot=polygon.vertices[0],triangles=[];for(let i=0;i{const corner10=triangle[0],corner11=triangle[1],corner12=triangle[2],corner13=triangle[2];return` 0\n3DFACE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 62\n${color}\n 100\nAcDbFace\n 70\n0\n 10\n${corner10[0]}\n 20\n${corner10[1]}\n 30\n${corner10[2]}\n 11\n${corner11[0]}\n 21\n${corner11[1]}\n 31\n${corner11[2]}\n 12\n${corner12[0]}\n 22\n${corner12[1]}\n 32\n${corner12[2]}\n 13\n${corner13[0]}\n 23\n${corner13[1]}\n 33\n${corner13[2]}\n`},PolygonsToPolyline=(object,options)=>{let str="";const mesh=polygons2polyfaces(index$6.toPolygons(object));return mesh.faces.length>0&&(str+=` 0\nPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(object,options)}\n 8\n0\n 62\n${getColorNumber(object,options)}\n 100\nAcDb3dPolyline\n 70\n64\n 71\n${mesh.vertices.length}\n 72\n${mesh.faces.length}\n`,mesh.vertices.forEach((vertex=>{str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n${vertex[0]}\n 20\n${vertex[1]}\n 30\n${vertex[2]}\n 70\n192\n`})),mesh.faces.forEach((face=>{str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n0\n 20\n0\n 30\n0\n 70\n128\n 71\n${face[0]}\n 72\n${face[1]}\n 73\n${face[2]}\n 74\n${face[3]}\n`}))),[str]},polygons2polyfaces=polygons=>{const faces=[],vertices=[];for(let i=0;i{options.entityId++;const padded="00000"+options.entityId.toString(16).toUpperCase();return"CAD"+padded.substr(padded.length-5)},getName=(object,options)=>{if(object.name)return object.name;const padded="00000"+options.entityId.toString(16).toUpperCase();return"CAD"+padded.substr(padded.length-5)},getColorNumber=(object,options)=>{let colorNumber=256;if(object.color){const r=Math.floor(255*object.color[0]),g=Math.floor(255*object.color[1]),b=Math.floor(255*object.color[2]),index=options.colorIndex;let closest=765;for(let i=1;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out}; +const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out}; /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT - */Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const entityContents=objects.map(((object,i)=>{if(index$a.isA(object)){const color=object.color,name=object.name,paths=index$a.toOutlines(object).map((outline=>({closed:!0,points:outline,color:color,name:name})));return"polyline"===options.geom2To?PathsToPolyine(paths,options):PathsToLwpolyline(paths,options)}if(index$6.isA(object))return"polyline"===options.geom3To?PolygonsToPolyline(object,options):PolygonsTo3DFaces(object,options);if(index$5.isA(object)){const color=object.color,name=object.name,path={closed:object.isClosed,points:index$5.toPoints(object),color:color,name:name};return PathsToLwpolyline([path],options)}return""}));let section=" 0\nSECTION\n 2\nENTITIES\n";return entityContents.forEach((content=>{content&&(section+=content)})),section+=" 0\nENDSEC",section},PathsToLwpolyline=(paths,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";return paths.forEach(((path,i)=>{if(path.points.length<1)return;const numpointsClosed=path.points.length+(path.closed?1:0);str+=` 0\nLWPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(path,options)}\n 8\n0\n 67\n0\n 62\n${getColorNumber(path,options)}\n 100\nAcDbPolyline\n 90\n${numpointsClosed}\n 70\n${path.closed?1:0}\n`;for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped];str+=` 10\n${point[0]}\n 20\n${point[1]}\n`}options.statusCallback&&options.statusCallback({progress:100*i/paths.length})})),options.statusCallback&&options.statusCallback({progress:100}),[str]},PathsToPolyine=(paths,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";return paths.forEach(((path,i)=>{const numpointsClosed=path.points.length+(path.closed?1:0);str+=` 0\nPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(path,options)}\n 8\n0\n 62\n${getColorNumber(path,options)}\n 100\nAcDb2dPolyline\n`;for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped];str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb2dVertex\n 10\n${point[0]}\n 20\n${point[1]}\n`}str+=` 0\nSEQEND\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n`,options.statusCallback&&options.statusCallback({progress:100*i/paths.length})})),options.statusCallback&&options.statusCallback({progress:100}),[str]},PolygonsTo3DFaces=(object,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";const polygons=index$6.toPolygons(object),objectColor=getColorNumber(object,options);return polygons.forEach(((polygon,i)=>{const polyColor=polygon.color?getColorNumber(polygon,options):objectColor;polygonToTriangles(polygon).forEach(((triangle,i)=>{str+=triangleTo3DFaces(triangle,options,polyColor)}))})),options.statusCallback&&options.statusCallback({progress:100}),[str]},polygonToTriangles=polygon=>{const length=polygon.vertices.length-2;if(length<1)return[];const pivot=polygon.vertices[0],triangles=[];for(let i=0;i{const corner10=triangle[0],corner11=triangle[1],corner12=triangle[2],corner13=triangle[2];return` 0\n3DFACE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 62\n${color}\n 100\nAcDbFace\n 70\n0\n 10\n${corner10[0]}\n 20\n${corner10[1]}\n 30\n${corner10[2]}\n 11\n${corner11[0]}\n 21\n${corner11[1]}\n 31\n${corner11[2]}\n 12\n${corner12[0]}\n 22\n${corner12[1]}\n 32\n${corner12[2]}\n 13\n${corner13[0]}\n 23\n${corner13[1]}\n 33\n${corner13[2]}\n`},PolygonsToPolyline=(object,options)=>{let str="";const mesh=polygons2polyfaces(index$6.toPolygons(object));return mesh.faces.length>0&&(str+=` 0\nPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(object,options)}\n 8\n0\n 62\n${getColorNumber(object,options)}\n 100\nAcDb3dPolyline\n 70\n64\n 71\n${mesh.vertices.length}\n 72\n${mesh.faces.length}\n`,mesh.vertices.forEach((vertex=>{str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n${vertex[0]}\n 20\n${vertex[1]}\n 30\n${vertex[2]}\n 70\n192\n`})),mesh.faces.forEach((face=>{str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n0\n 20\n0\n 30\n0\n 70\n128\n 71\n${face[0]}\n 72\n${face[1]}\n 73\n${face[2]}\n 74\n${face[3]}\n`}))),[str]},polygons2polyfaces=polygons=>{const faces=[],vertices=[];for(let i=0;i{options.entityId++;const padded="00000"+options.entityId.toString(16).toUpperCase();return"CAD"+padded.substr(padded.length-5)},getName=(object,options)=>{if(object.name)return object.name;const padded="00000"+options.entityId.toString(16).toUpperCase();return"CAD"+padded.substr(padded.length-5)},getColorNumber=(object,options)=>{let colorNumber=256;if(object.color){const r=Math.floor(255*object.color[0]),g=Math.floor(255*object.color[1]),b=Math.floor(255*object.color[2]),index=options.colorIndex;let closest=765;for(let i=1;i{const defaults={geom2To:"lwpolyline",geom3To:"3dface",pathTo:"lwpolyline",statusCallback:null,colorIndex:colorIndex};if((options=Object.assign({},defaults,options)).entityId=0,0===(objects=(objects=flatten$1(objects)).filter((object=>index$6.isA(object)||index$a.isA(object)||index$5.isA(object)))).length)throw new Error("only JSCAD geometries can be serialized to DXF");var array;return array=((options,...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results})({snap:!0,triangulate:!0},objects),objects=Array.isArray(array)?array:null==array?[]:[array],[`999\nCreated by JSCAD\n 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1027\n 9\n$ACADMAINTVER\n 70\n8\n 9\n$DWGCODEPAGE\n 3\nANSI_1252\n 9\n$LASTSAVEDBY\n 1\nunknown\n 9\n$REQUIREDVERSIONS\n160\n0\n 9\n$INSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$EXTMIN\n 10\n1e+20\n 20\n1e+20\n 30\n1e+20\n 9\n$EXTMAX\n 10\n-1e+20\n 20\n-1e+20\n 30\n-1e+20\n 9\n$LIMMIN\n 10\n0.0\n 20\n0.0\n 9\n$LIMMAX\n 10\n12.0\n 20\n9.0\n 9\n$ORTHOMODE\n 70\n0\n 9\n$REGENMODE\n 70\n1\n 9\n$FILLMODE\n 70\n1\n 9\n$QTEXTMODE\n 70\n0\n 9\n$MIRRTEXT\n 70\n0\n 9\n$LTSCALE\n 40\n1.0\n 9\n$ATTMODE\n 70\n1\n 9\n$TEXTSIZE\n 40\n0.2\n 9\n$TRACEWID\n 40\n0.05\n 9\n$TEXTSTYLE\n 7\nNotes\n 9\n$CLAYER\n 8\n0\n 9\n$CELTYPE\n 6\nByLayer\n 9\n$CECOLOR\n 62\n256\n 9\n$CELTSCALE\n 40\n1.0\n 9\n$DISPSILH\n 70\n0\n 9\n$DIMSCALE\n 40\n1.0\n 9\n$DIMASZ\n 40\n3.0\n 9\n$DIMEXO\n 40\n1.5\n 9\n$DIMDLI\n 40\n6.0\n 9\n$DIMRND\n 40\n0.0\n 9\n$DIMDLE\n 40\n0.0\n 9\n$DIMEXE\n 40\n3.0\n 9\n$DIMTP\n 40\n0.0\n 9\n$DIMTM\n 40\n0.0\n 9\n$DIMTXT\n 40\n3.0\n 9\n$DIMCEN\n 40\n3.0\n 9\n$DIMTSZ\n 40\n0.0\n 9\n$DIMTOL\n 70\n0\n 9\n$DIMLIM\n 70\n0\n 9\n$DIMTIH\n 70\n0\n 9\n$DIMTOH\n 70\n0\n 9\n$DIMSE1\n 70\n0\n 9\n$DIMSE2\n 70\n0\n 9\n$DIMTAD\n 70\n1\n 9\n$DIMZIN\n 70\n3\n 9\n$DIMBLK\n 1\n\n 9\n$DIMASO\n 70\n1\n 9\n$DIMSHO\n 70\n1\n 9\n$DIMPOST\n 1\n\n 9\n$DIMAPOST\n 1\n\n 9\n$DIMALT\n 70\n0\n 9\n$DIMALTD\n 70\n2\n 9\n$DIMALTF\n 40\n25.4\n 9\n$DIMLFAC\n 40\n1.0\n 9\n$DIMTOFL\n 70\n0\n 9\n$DIMTVP\n 40\n0.0\n 9\n$DIMTIX\n 70\n0\n 9\n$DIMSOXD\n 70\n0\n 9\n$DIMSAH\n 70\n0\n 9\n$DIMBLK1\n 1\n\n 9\n$DIMBLK2\n 1\n\n 9\n$DIMSTYLE\n 2\nCivil-Metric\n 9\n$DIMCLRD\n 70\n0\n 9\n$DIMCLRE\n 70\n0\n 9\n$DIMCLRT\n 70\n0\n 9\n$DIMTFAC\n 40\n1.0\n 9\n$DIMGAP\n 40\n2.0\n 9\n$DIMJUST\n 70\n0\n 9\n$DIMSD1\n 70\n0\n 9\n$DIMSD2\n 70\n0\n 9\n$DIMTOLJ\n 70\n1\n 9\n$DIMTZIN\n 70\n0\n 9\n$DIMALTZ\n 70\n0\n 9\n$DIMALTTZ\n 70\n0\n 9\n$DIMUPT\n 70\n0\n 9\n$DIMDEC\n 70\n2\n 9\n$DIMTDEC\n 70\n2\n 9\n$DIMALTU\n 70\n2\n 9\n$DIMALTTD\n 70\n2\n 9\n$DIMTXSTY\n 7\nStandard\n 9\n$DIMAUNIT\n 70\n0\n 9\n$DIMADEC\n 70\n2\n 9\n$DIMALTRND\n 40\n0.0\n 9\n$DIMAZIN\n 70\n2\n 9\n$DIMDSEP\n 70\n46\n 9\n$DIMATFIT\n 70\n3\n 9\n$DIMFRAC\n 70\n1\n 9\n$DIMLDRBLK\n 1\n\n 9\n$DIMLUNIT\n 70\n2\n 9\n$DIMLWD\n 70\n-2\n 9\n$DIMLWE\n 70\n-2\n 9\n$DIMTMOVE\n 70\n0\n 9\n$DIMFXL\n 40\n1.0\n 9\n$DIMFXLON\n 70\n0\n 9\n$DIMJOGANG\n 40\n0.785398163397\n 9\n$DIMTFILL\n 70\n0\n 9\n$DIMTFILLCLR\n 70\n0\n 9\n$DIMARCSYM\n 70\n0\n 9\n$DIMLTYPE\n 6\n\n 9\n$DIMLTEX1\n 6\n\n 9\n$DIMLTEX2\n 6\n\n 9\n$DIMTXTDIRECTION\n 70\n0\n 9\n$LUNITS\n 70\n2\n 9\n$LUPREC\n 70\n4\n 9\n$SKETCHINC\n 40\n0.1\n 9\n$FILLETRAD\n 40\n0.0\n 9\n$AUNITS\n 70\n4\n 9\n$AUPREC\n 70\n5\n 9\n$MENU\n 1\n.\n 9\n$ELEVATION\n 40\n0.0\n 9\n$PELEVATION\n 40\n0.0\n 9\n$THICKNESS\n 40\n0.0\n 9\n$LIMCHECK\n 70\n0\n 9\n$CHAMFERA\n 40\n0.0\n 9\n$CHAMFERB\n 40\n0.0\n 9\n$CHAMFERC\n 40\n0.0\n 9\n$CHAMFERD\n 40\n0.0\n 9\n$SKPOLY\n 70\n0\n 9\n$TDCREATE\n 40\n2457986.69756\n 9\n$TDUCREATE\n 40\n2455631.2632\n 9\n$TDUPDATE\n 40\n2457986.69756\n 9\n$TDUUPDATE\n 40\n2456436.43179\n 9\n$TDINDWG\n 40\n0.0003490741\n 9\n$TDUSRTIMER\n 40\n0.0003487153\n 9\n$USRTIMER\n 70\n1\n 9\n$ANGBASE\n 50\n0.0\n 9\n$ANGDIR\n 70\n0\n 9\n$PDMODE\n 70\n0\n 9\n$PDSIZE\n 40\n0.0\n 9\n$PLINEWID\n 40\n0.0\n 9\n$SPLFRAME\n 70\n0\n 9\n$SPLINETYPE\n 70\n6\n 9\n$SPLINESEGS\n 70\n8\n 9\n$HANDSEED\n 5\n5C7\n 9\n$SURFTAB1\n 70\n6\n 9\n$SURFTAB2\n 70\n6\n 9\n$SURFTYPE\n 70\n6\n 9\n$SURFU\n 70\n6\n 9\n$SURFV\n 70\n6\n 9\n$UCSBASE\n 2\n\n 9\n$UCSNAME\n 2\n\n 9\n$UCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$UCSORTHOREF\n 2\n\n 9\n$UCSORTHOVIEW\n 70\n0\n 9\n$UCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSBASE\n 2\n\n 9\n$PUCSNAME\n 2\n\n 9\n$PUCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$PUCSORTHOREF\n 2\n\n 9\n$PUCSORTHOVIEW\n 70\n0\n 9\n$PUCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$USERI1\n 70\n0\n 9\n$USERI2\n 70\n0\n 9\n$USERI3\n 70\n0\n 9\n$USERI4\n 70\n0\n 9\n$USERI5\n 70\n0\n 9\n$USERR1\n 40\n0.0\n 9\n$USERR2\n 40\n0.0\n 9\n$USERR3\n 40\n0.0\n 9\n$USERR4\n 40\n0.0\n 9\n$USERR5\n 40\n0.0\n 9\n$WORLDVIEW\n 70\n1\n 9\n$SHADEDGE\n 70\n3\n 9\n$SHADEDIF\n 70\n70\n 9\n$TILEMODE\n 70\n1\n 9\n$MAXACTVP\n 70\n64\n 9\n$PINSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PLIMCHECK\n 70\n0\n 9\n$PEXTMIN\n 10\n0.628866766397\n 20\n0.799999952316\n 30\n0.0\n 9\n$PEXTMAX\n 10\n9.02886638493\n 20\n7.19999957085\n 30\n0.0\n 9\n$PLIMMIN\n 10\n-0.700541819174\n 20\n-0.228100386192\n 9\n$PLIMMAX\n 10\n10.2994579405\n 20\n8.27189937351\n 9\n$UNITMODE\n 70\n0\n 9\n$VISRETAIN\n 70\n1\n 9\n$PLINEGEN\n 70\n0\n 9\n$PSLTSCALE\n 70\n1\n 9\n$TREEDEPTH\n 70\n3020\n 9\n$CMLSTYLE\n 2\nStandard\n 9\n$CMLJUST\n 70\n0\n 9\n$CMLSCALE\n 40\n1.0\n 9\n$PROXYGRAPHICS\n 70\n1\n 9\n$MEASUREMENT\n 70\n1\n 9\n$CELWEIGHT\n370\n-1\n 9\n$ENDCAPS\n280\n0\n 9\n$JOINSTYLE\n280\n0\n 9\n$LWDISPLAY\n290\n0\n 9\n$INSUNITS\n 70\n4\n 9\n$HYPERLINKBASE\n 1\n\n 9\n$STYLESHEET\n 1\n\n 9\n$XEDIT\n290\n1\n 9\n$CEPSNTYPE\n380\n0\n 9\n$PSTYLEMODE\n290\n1\n 9\n$FINGERPRINTGUID\n 2\n{39DB1BDD-BC6C-46D3-A333-DFCC0DC4782D}\n 9\n$VERSIONGUID\n 2\n{69EEBB2D-7039-498F-9366-3F994E4A07E7}\n 9\n$EXTNAMES\n290\n1\n 9\n$PSVPSCALE\n 40\n0.0\n 9\n$OLESTARTUP\n290\n0\n 9\n$SORTENTS\n280\n127\n 9\n$INDEXCTL\n280\n0\n 9\n$HIDETEXT\n280\n1\n 9\n$XCLIPFRAME\n280\n0\n 9\n$HALOGAP\n280\n0\n 9\n$OBSCOLOR\n 70\n257\n 9\n$OBSLTYPE\n280\n0\n 9\n$INTERSECTIONDISPLAY\n280\n0\n 9\n$INTERSECTIONCOLOR\n 70\n257\n 9\n$DIMASSOC\n280\n2\n 9\n$PROJECTNAME\n 1\n\n 9\n$CAMERADISPLAY\n290\n0\n 9\n$LENSLENGTH\n 40\n50.0\n 9\n$CAMERAHEIGHT\n 40\n0.0\n 9\n$STEPSPERSEC\n 40\n2.0\n 9\n$STEPSIZE\n 40\n6.0\n 9\n$3DDWFPREC\n 40\n2.0\n 9\n$PSOLWIDTH\n 40\n0.25\n 9\n$PSOLHEIGHT\n 40\n4.0\n 9\n$LOFTANG1\n 40\n1.57079632679\n 9\n$LOFTANG2\n 40\n1.57079632679\n 9\n$LOFTMAG1\n 40\n0.0\n 9\n$LOFTMAG2\n 40\n0.0\n 9\n$LOFTPARAM\n 70\n7\n 9\n$LOFTNORMALS\n280\n1\n 9\n$LATITUDE\n 40\n37.795\n 9\n$LONGITUDE\n 40\n-122.394\n 9\n$NORTHDIRECTION\n 40\n0.0\n 9\n$TIMEZONE\n 70\n-8000\n 9\n$LIGHTGLYPHDISPLAY\n280\n1\n 9\n$TILEMODELIGHTSYNCH\n280\n1\n 9\n$CMATERIAL\n347\n96\n 9\n$SOLIDHIST\n280\n1\n 9\n$SHOWHIST\n280\n1\n 9\n$DWFFRAME\n280\n2\n 9\n$DGNFRAME\n280\n0\n 9\n$REALWORLDSCALE\n290\n1\n 9\n$INTERFERECOLOR\n 62\n1\n 9\n$INTERFEREOBJVS\n345\nA3\n 9\n$INTERFEREVPVS\n346\nA0\n 9\n$CSHADOW\n280\n0\n 9\n$SHADOWPLANELOCATION\n 40\n0.0\n 0\nENDSEC\n 0\nSECTION\n 2\nCLASSES\n 0\nCLASS\n 1\nACDBDICTIONARYWDFLT\n 2\nAcDbDictionaryWithDefault\n 3\nObjectDBX Classes\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nDICTIONARYVAR\n 2\nAcDbDictionaryVar\n 3\nObjectDBX Classes\n 90\n0\n 91\n15\n280\n0\n281\n0\n 0\nCLASS\n 1\nTABLESTYLE\n 2\nAcDbTableStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nMATERIAL\n 2\nAcDbMaterial\n 3\nObjectDBX Classes\n 90\n1153\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nVISUALSTYLE\n 2\nAcDbVisualStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n26\n280\n0\n281\n0\n 0\nCLASS\n 1\nSCALE\n 2\nAcDbScale\n 3\nObjectDBX Classes\n 90\n1153\n 91\n17\n280\n0\n281\n0\n 0\nCLASS\n 1\nMLEADERSTYLE\n 2\nAcDbMLeaderStyle\n 3\nACDB_MLEADERSTYLE_CLASS\n 90\n4095\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nCELLSTYLEMAP\n 2\nAcDbCellStyleMap\n 3\nObjectDBX Classes\n 90\n1152\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nEXACXREFPANELOBJECT\n 2\nExAcXREFPanelObject\n 3\nEXAC_ESW\n 90\n1025\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nNPOCOLLECTION\n 2\nAcDbImpNonPersistentObjectsCollection\n 3\nObjectDBX Classes\n 90\n1153\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nLAYER_INDEX\n 2\nAcDbLayerIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nSPATIAL_INDEX\n 2\nAcDbSpatialIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nIDBUFFER\n 2\nAcDbIdBuffer\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nDIMASSOC\n 2\nAcDbDimAssoc\n 3\n"AcDbDimAssoc|Product Desc: AcDim ARX App For Dimension|Company: Autodesk, Inc.|WEB Address: www.autodesk.com"\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBSECTIONVIEWSTYLE\n 2\nAcDbSectionViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBDETAILVIEWSTYLE\n 2\nAcDbDetailViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF\n 2\nAcDbRasterImageDef\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nRASTERVARIABLES\n 2\nAcDbRasterVariables\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF_REACTOR\n 2\nAcDbRasterImageDefReactor\n 3\nISM\n 90\n1\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGE\n 2\nAcDbRasterImage\n 3\nISM\n 90\n2175\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nPDFDEFINITION\n 2\nAcDbPdfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nPDFUNDERLAY\n 2\nAcDbPdfReference\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDWFDEFINITION\n 2\nAcDbDwfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDWFUNDERLAY\n 2\nAcDbDwfReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDGNDEFINITION\n 2\nAcDbDgnDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDGNUNDERLAY\n 2\nAcDbDgnReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nENDSEC\n 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nVPORT\n 5\n8\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLTYPE\n 5\n5F\n330\n0\n100\nAcDbSymbolTable\n 70\n7\n 0\nLTYPE\n 5\n14\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByBlock\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n15\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByLayer\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n16\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nContinuous\n 70\n0\n 3\nSolid line\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n1B1\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nCENTER\n 70\n0\n 3\nCenter ____ _ ____ _ ____ _ ____ _ ____ _ ____\n 72\n65\n 73\n4\n 40\n2.0\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B2\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nDASHED\n 70\n0\n 3\nDashed __ __ __ __ __ __ __ __ __ __ __ __ __ _\n 72\n65\n 73\n2\n 40\n0.75\n 49\n0.5\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B3\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nPHANTOM\n 70\n0\n 3\nPhantom ______ __ __ ______ __ __ ______\n 72\n65\n 73\n6\n 40\n2.5\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n39E\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nHIDDEN\n 70\n0\n 3\nHidden __ __ __ __ __ __ __ __ __ __ __ __ __ __\n 72\n65\n 73\n2\n 40\n9.525\n 49\n6.35\n 74\n0\n 49\n-3.175\n 74\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLAYER\n 5\n2\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nLAYER\n 5\n10\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\n0\n 70\n0\n 6\nContinuous\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n1B4\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nView Port\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n21D\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nDefpoints\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nSTYLE\n 5\n3\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nSTYLE\n 5\n11\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nStandard\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\nDC\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\n178\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nNotes\n 70\n0\n 40\n3.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nENDTAB\n 0\nTABLE\n 2\nVIEW\n 5\n6\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nUCS\n 5\n7\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nAPPID\n 5\n9\n330\n0\n100\nAcDbSymbolTable\n 70\n12\n 0\nAPPID\n 5\n12\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD\n 70\n0\n 0\nAPPID\n 5\nDD\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnoPO\n 70\n0\n 0\nAPPID\n 5\nDE\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnotative\n 70\n0\n 0\nAPPID\n 5\nDF\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMJAG\n 70\n0\n 0\nAPPID\n 5\nE0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMTALN\n 70\n0\n 0\nAPPID\n 5\n107\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_MLEADERVER\n 70\n0\n 0\nAPPID\n 5\n1B5\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcAecLayerStandard\n 70\n0\n 0\nAPPID\n 5\n1BA\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_EXEMPT_FROM_CAD_STANDARDS\n 70\n0\n 0\nAPPID\n 5\n237\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMBREAK\n 70\n0\n 0\nAPPID\n 5\n28E\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_PSEXT\n 70\n0\n 0\nAPPID\n 5\n4B0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_NAV_VCDISPLAY\n 70\n0\n 0\nAPPID\n 5\n4E3\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nHATCHBACKGROUNDCOLOR\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nDIMSTYLE\n 5\nA\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n100\nAcDbDimStyleTable\n 71\n3\n340\n242\n340\n27\n340\nE1\n 0\nDIMSTYLE\n105\n27\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nStandard\n 70\n0\n 41\n3.0\n 42\n2.0\n 43\n9.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\nE1\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n3.0\n 42\n2.5\n 43\n10.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nAcadAnnotative\n1000\nAnnotativeData\n1002\n{\n1070\n1\n1070\n1\n1002\n}\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\n242\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nCivil-Metric\n 70\n0\n 41\n3.0\n 42\n1.5\n 43\n6.0\n 44\n3.0\n 73\n0\n 74\n0\n 77\n1\n 78\n3\n 79\n2\n140\n3.0\n141\n3.0\n147\n2.0\n179\n2\n271\n2\n272\n2\n276\n1\n340\n11\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n3.0\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nBLOCK_RECORD\n 5\n1\n330\n0\n100\nAcDbSymbolTable\n 70\n4\n 0\nBLOCK_RECORD\n 5\n1F\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Model_Space\n340\n530\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n58\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Paper_Space\n340\n531\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n238\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_ArchTick\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n23C\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_Open30\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nENDTAB\n 0\nENDSEC\n 0\nSECTION\n 2\nBLOCKS\n 0\nBLOCK\n 5\n23A\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_ArchTick\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_ArchTick\n 1\n\n 0\nENDBLK\n 5\n23B\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n20\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Model_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Model_Space\n 1\n\n 0\nENDBLK\n 5\n21\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n5A\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Paper_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Paper_Space\n 1\n\n 0\nENDBLK\n 5\n5B\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n240\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_Open30\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_Open30\n 1\n\n 0\nENDBLK\n 5\n241\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nENDSEC\n${dxfEntities(objects,options)}\n 0\nSECTION\n 2\nOBJECTS\n 0\nDICTIONARY\n 5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n 3\nACAD_COLOR\n350\n524\n 3\nACAD_GROUP\n350\n525\n 3\nACAD_LAYOUT\n350\n526\n 3\nACAD_MATERIAL\n350\n527\n 3\nACAD_MLEADERSTYLE\n350\n528\n 3\nACAD_MLINESTYLE\n350\n529\n 3\nACAD_PLOTSETTINGS\n350\n52A\n 3\nACAD_PLOTSTYLENAME\n350\n52C\n 3\nACAD_SCALELIST\n350\n52D\n 3\nACAD_TABLESTYLE\n350\n52E\n 3\nACAD_VISUALSTYLE\n350\n52F\n 0\nDICTIONARY\n 5\n524\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n525\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n526\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nModel\n350\n530\n 3\nLayout1\n350\n531\n 0\nDICTIONARY\n 5\n527\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n528\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n529\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52A\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nACDBPLACEHOLDER\n 5\n52B\n330\n52C\n 0\nACDBDICTIONARYWDFLT\n 5\n52C\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nNormal\n350\n52B\n100\nAcDbDictionaryWithDefault\n340\n52B\n 0\nDICTIONARY\n 5\n52D\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52E\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52F\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nLAYOUT\n 5\n530\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n14.53\n 70\n11952\n 72\n0\n 73\n1\n 74\n0\n 7\n\n 75\n0\n147\n0.069\n148\n114.98\n149\n300.29\n100\nAcDbLayout\n 1\nModel\n 70\n1\n 71\n0\n 10\n0.0\n 20\n0.0\n 11\n12.0\n 21\n9.0\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.0\n 24\n0.0\n 34\n0.0\n 15\n0.0\n 25\n0.0\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n1F\n 0\nLAYOUT\n 5\n531\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n1.0\n 70\n688\n 72\n0\n 73\n1\n 74\n5\n 7\nacad.ctb\n 75\n16\n147\n1.0\n148\n0.0\n149\n0.0\n100\nAcDbLayout\n 1\nLayout1\n 70\n1\n 71\n1\n 10\n-0.7\n 20\n-0.23\n 11\n10.3\n 21\n8.27\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.63\n 24\n0.8\n 34\n0.0\n 15\n9.0\n 25\n7.2\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n58\n 0\nENDSEC\n 0\nEOF\n`]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadDxfSerializer={}); + */Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},colorIndex=[[0,0,0,255],[255,0,0,255],[255,255,0,255],[0,255,0,255],[0,255,255,255],[0,0,255,255],[255,0,255,255],[255,255,255,255],[128,128,128,255],[192,192,192,255],[255,0,0,255],[255,127,127,255],[165,0,0,255],[165,82,82,255],[127,0,0,255],[127,63,63,255],[76,0,0,255],[76,38,38,255],[38,0,0,255],[38,19,19,255],[255,63,0,255],[255,159,127,255],[165,41,0,255],[165,103,82,255],[127,31,0,255],[127,79,63,255],[76,19,0,255],[76,47,38,255],[38,9,0,255],[38,28,19,255],[255,127,0,255],[255,191,127,255],[165,82,0,255],[165,124,82,255],[127,63,0,255],[127,95,63,255],[76,38,0,255],[76,57,38,255],[38,19,0,255],[38,28,19,255],[255,191,0,255],[255,223,127,255],[165,124,0,255],[165,145,82,255],[127,95,0,255],[127,111,63,255],[76,57,0,255],[76,66,38,255],[38,28,0,255],[38,33,19,255],[255,255,0,255],[255,255,127,255],[165,165,0,255],[165,165,82,255],[127,127,0,255],[127,127,63,255],[76,76,0,255],[76,76,38,255],[38,38,0,255],[38,38,19,255],[191,255,0,255],[223,255,127,255],[124,165,0,255],[145,165,82,255],[95,127,0,255],[111,127,63,255],[57,76,0,255],[66,76,38,255],[28,38,0,255],[33,38,19,255],[127,255,0,255],[191,255,127,255],[82,165,0,255],[124,165,82,255],[63,127,0,255],[95,127,63,255],[38,76,0,255],[57,76,38,255],[19,38,0,255],[28,38,19,255],[63,255,0,255],[159,255,127,255],[41,165,0,255],[103,165,82,255],[31,127,0,255],[79,127,63,255],[19,76,0,255],[47,76,38,255],[9,38,0,255],[23,38,19,255],[0,255,0,255],[125,255,127,255],[0,165,0,255],[82,165,82,255],[0,127,0,255],[63,127,63,255],[0,76,0,255],[38,76,38,255],[0,38,0,255],[19,38,19,255],[0,255,63,255],[127,255,159,255],[0,165,41,255],[82,165,103,255],[0,127,31,255],[63,127,79,255],[0,76,19,255],[38,76,47,255],[0,38,9,255],[19,88,23,255],[0,255,127,255],[127,255,191,255],[0,165,82,255],[82,165,124,255],[0,127,63,255],[63,127,95,255],[0,76,38,255],[38,76,57,255],[0,38,19,255],[19,88,28,255],[0,255,191,255],[127,255,223,255],[0,165,124,255],[82,165,145,255],[0,127,95,255],[63,127,111,255],[0,76,57,255],[38,76,66,255],[0,38,28,255],[19,88,88,255],[0,255,255,255],[127,255,255,255],[0,165,165,255],[82,165,165,255],[0,127,127,255],[63,127,127,255],[0,76,76,255],[38,76,76,255],[0,38,38,255],[19,88,88,255],[0,191,255,255],[127,223,255,255],[0,124,165,255],[82,145,165,255],[0,95,127,255],[63,111,217,255],[0,57,76,255],[38,66,126,255],[0,28,38,255],[19,88,88,255],[0,127,255,255],[127,191,255,255],[0,82,165,255],[82,124,165,255],[0,63,127,255],[63,95,127,255],[0,38,76,255],[38,57,126,255],[0,19,38,255],[19,28,88,255],[0,63,255,255],[127,159,255,255],[0,41,165,255],[82,103,165,255],[0,31,127,255],[63,79,127,255],[0,19,76,255],[38,47,126,255],[0,9,38,255],[19,23,88,255],[0,0,255,255],[127,127,255,255],[0,0,165,255],[82,82,165,255],[0,0,127,255],[63,63,127,255],[0,0,76,255],[38,38,126,255],[0,0,38,255],[19,19,88,255],[63,0,255,255],[159,127,255,255],[41,0,165,255],[103,82,165,255],[31,0,127,255],[79,63,127,255],[19,0,76,255],[47,38,126,255],[9,0,38,255],[23,19,88,255],[127,0,255,255],[191,127,255,255],[165,0,82,255],[124,82,165,255],[63,0,127,255],[95,63,127,255],[38,0,76,255],[57,38,126,255],[19,0,38,255],[28,19,88,255],[191,0,255,255],[223,127,255,255],[124,0,165,255],[142,82,165,255],[95,0,127,255],[111,63,127,255],[57,0,76,255],[66,38,76,255],[28,0,38,255],[88,19,88,255],[255,0,255,255],[255,127,255,255],[165,0,165,255],[165,82,165,255],[127,0,127,255],[127,63,127,255],[76,0,76,255],[76,38,76,255],[38,0,38,255],[88,19,88,255],[255,0,191,255],[255,127,223,255],[165,0,124,255],[165,82,145,255],[127,0,95,255],[127,63,111,255],[76,0,57,255],[76,38,66,255],[38,0,28,255],[88,19,88,255],[255,0,127,255],[255,127,191,255],[165,0,82,255],[165,82,124,255],[127,0,63,255],[127,63,95,255],[76,0,38,255],[76,38,57,255],[38,0,19,255],[88,19,28,255],[255,0,63,255],[255,127,159,255],[165,0,41,255],[165,82,103,255],[127,0,31,255],[127,63,79,255],[76,0,19,255],[76,38,47,255],[38,0,9,255],[88,19,23,255],[0,0,0,255],[101,101,101,255],[102,102,102,255],[153,153,153,255],[204,204,204,255],[255,255,255,255]],dxfEntities=(objects,options)=>{const entityContents=objects.map(((object,i)=>{if(index$a.isA(object)){const color=object.color,name=object.name,paths=index$a.toOutlines(object).map((outline=>({closed:!0,points:outline,color:color,name:name})));return"polyline"===options.geom2To?PathsToPolyine(paths,options):PathsToLwpolyline(paths,options)}if(index$6.isA(object))return"polyline"===options.geom3To?PolygonsToPolyline(object,options):PolygonsTo3DFaces(object,options);if(index$5.isA(object)){const color=object.color,name=object.name,path={closed:object.isClosed,points:index$5.toPoints(object),color:color,name:name};return PathsToLwpolyline([path],options)}return""}));let section=" 0\nSECTION\n 2\nENTITIES\n";return entityContents.forEach((content=>{content&&(section+=content)})),section+=" 0\nENDSEC",section},PathsToLwpolyline=(paths,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";return paths.forEach(((path,i)=>{if(path.points.length<1)return;const numpointsClosed=path.points.length+(path.closed?1:0);str+=` 0\nLWPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(path,options)}\n 8\n0\n 67\n0\n 62\n${getColorNumber(path,options)}\n 100\nAcDbPolyline\n 90\n${numpointsClosed}\n 70\n${path.closed?1:0}\n`;for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped];str+=` 10\n${point[0]}\n 20\n${point[1]}\n`}options.statusCallback&&options.statusCallback({progress:100*i/paths.length})})),options.statusCallback&&options.statusCallback({progress:100}),[str]},PathsToPolyine=(paths,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";return paths.forEach(((path,i)=>{const numpointsClosed=path.points.length+(path.closed?1:0);str+=` 0\nPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(path,options)}\n 8\n0\n 62\n${getColorNumber(path,options)}\n 100\nAcDb2dPolyline\n`;for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped];str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb2dVertex\n 10\n${point[0]}\n 20\n${point[1]}\n`}str+=` 0\nSEQEND\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n`,options.statusCallback&&options.statusCallback({progress:100*i/paths.length})})),options.statusCallback&&options.statusCallback({progress:100}),[str]},PolygonsTo3DFaces=(object,options)=>{options.statusCallback&&options.statusCallback({progress:0});let str="";const polygons=index$6.toPolygons(object),objectColor=getColorNumber(object,options);return polygons.forEach(((polygon,i)=>{const polyColor=polygon.color?getColorNumber(polygon,options):objectColor;polygonToTriangles(polygon).forEach(((triangle,i)=>{str+=triangleTo3DFaces(triangle,options,polyColor)}))})),options.statusCallback&&options.statusCallback({progress:100}),[str]},polygonToTriangles=polygon=>{const length=polygon.vertices.length-2;if(length<1)return[];const pivot=polygon.vertices[0],triangles=[];for(let i=0;i{const corner10=triangle[0],corner11=triangle[1],corner12=triangle[2],corner13=triangle[2];return` 0\n3DFACE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 62\n${color}\n 100\nAcDbFace\n 70\n0\n 10\n${corner10[0]}\n 20\n${corner10[1]}\n 30\n${corner10[2]}\n 11\n${corner11[0]}\n 21\n${corner11[1]}\n 31\n${corner11[2]}\n 12\n${corner12[0]}\n 22\n${corner12[1]}\n 32\n${corner12[2]}\n 13\n${corner13[0]}\n 23\n${corner13[1]}\n 33\n${corner13[2]}\n`},PolygonsToPolyline=(object,options)=>{let str="";const mesh=polygons2polyfaces(index$6.toPolygons(object));return mesh.faces.length>0&&(str+=` 0\nPOLYLINE\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 3\n${getName(object,options)}\n 8\n0\n 62\n${getColorNumber(object,options)}\n 100\nAcDb3dPolyline\n 70\n64\n 71\n${mesh.vertices.length}\n 72\n${mesh.faces.length}\n`,mesh.vertices.forEach((vertex=>{str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n${vertex[0]}\n 20\n${vertex[1]}\n 30\n${vertex[2]}\n 70\n192\n`})),mesh.faces.forEach((face=>{str+=` 0\nVERTEX\n 5\n${getEntityId(options)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n0\n 20\n0\n 30\n0\n 70\n128\n 71\n${face[0]}\n 72\n${face[1]}\n 73\n${face[2]}\n 74\n${face[3]}\n`}))),[str]},polygons2polyfaces=polygons=>{const faces=[],vertices=[];for(let i=0;i{options.entityId++;const padded="00000"+options.entityId.toString(16).toUpperCase();return"CAD"+padded.substr(padded.length-5)},getName=(object,options)=>{if(object.name)return object.name;const padded="00000"+options.entityId.toString(16).toUpperCase();return"CAD"+padded.substr(padded.length-5)},getColorNumber=(object,options)=>{let colorNumber=256;if(object.color){const r=Math.floor(255*object.color[0]),g=Math.floor(255*object.color[1]),b=Math.floor(255*object.color[2]),index=options.colorIndex;let closest=765;for(let i=1;i{const defaults={geom2To:"lwpolyline",geom3To:"3dface",pathTo:"lwpolyline",statusCallback:null,colorIndex:colorIndex};if((options=Object.assign({},defaults,options)).entityId=0,0===(objects=(objects=flatten$1(objects)).filter((object=>index$6.isA(object)||index$a.isA(object)||index$5.isA(object)))).length)throw new Error("only JSCAD geometries can be serialized to DXF");var array;return array=generalize({snap:!0,triangulate:!0},objects),objects=Array.isArray(array)?array:null==array?[]:[array],[`999\nCreated by JSCAD\n 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1027\n 9\n$ACADMAINTVER\n 70\n8\n 9\n$DWGCODEPAGE\n 3\nANSI_1252\n 9\n$LASTSAVEDBY\n 1\nunknown\n 9\n$REQUIREDVERSIONS\n160\n0\n 9\n$INSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$EXTMIN\n 10\n1e+20\n 20\n1e+20\n 30\n1e+20\n 9\n$EXTMAX\n 10\n-1e+20\n 20\n-1e+20\n 30\n-1e+20\n 9\n$LIMMIN\n 10\n0.0\n 20\n0.0\n 9\n$LIMMAX\n 10\n12.0\n 20\n9.0\n 9\n$ORTHOMODE\n 70\n0\n 9\n$REGENMODE\n 70\n1\n 9\n$FILLMODE\n 70\n1\n 9\n$QTEXTMODE\n 70\n0\n 9\n$MIRRTEXT\n 70\n0\n 9\n$LTSCALE\n 40\n1.0\n 9\n$ATTMODE\n 70\n1\n 9\n$TEXTSIZE\n 40\n0.2\n 9\n$TRACEWID\n 40\n0.05\n 9\n$TEXTSTYLE\n 7\nNotes\n 9\n$CLAYER\n 8\n0\n 9\n$CELTYPE\n 6\nByLayer\n 9\n$CECOLOR\n 62\n256\n 9\n$CELTSCALE\n 40\n1.0\n 9\n$DISPSILH\n 70\n0\n 9\n$DIMSCALE\n 40\n1.0\n 9\n$DIMASZ\n 40\n3.0\n 9\n$DIMEXO\n 40\n1.5\n 9\n$DIMDLI\n 40\n6.0\n 9\n$DIMRND\n 40\n0.0\n 9\n$DIMDLE\n 40\n0.0\n 9\n$DIMEXE\n 40\n3.0\n 9\n$DIMTP\n 40\n0.0\n 9\n$DIMTM\n 40\n0.0\n 9\n$DIMTXT\n 40\n3.0\n 9\n$DIMCEN\n 40\n3.0\n 9\n$DIMTSZ\n 40\n0.0\n 9\n$DIMTOL\n 70\n0\n 9\n$DIMLIM\n 70\n0\n 9\n$DIMTIH\n 70\n0\n 9\n$DIMTOH\n 70\n0\n 9\n$DIMSE1\n 70\n0\n 9\n$DIMSE2\n 70\n0\n 9\n$DIMTAD\n 70\n1\n 9\n$DIMZIN\n 70\n3\n 9\n$DIMBLK\n 1\n\n 9\n$DIMASO\n 70\n1\n 9\n$DIMSHO\n 70\n1\n 9\n$DIMPOST\n 1\n\n 9\n$DIMAPOST\n 1\n\n 9\n$DIMALT\n 70\n0\n 9\n$DIMALTD\n 70\n2\n 9\n$DIMALTF\n 40\n25.4\n 9\n$DIMLFAC\n 40\n1.0\n 9\n$DIMTOFL\n 70\n0\n 9\n$DIMTVP\n 40\n0.0\n 9\n$DIMTIX\n 70\n0\n 9\n$DIMSOXD\n 70\n0\n 9\n$DIMSAH\n 70\n0\n 9\n$DIMBLK1\n 1\n\n 9\n$DIMBLK2\n 1\n\n 9\n$DIMSTYLE\n 2\nCivil-Metric\n 9\n$DIMCLRD\n 70\n0\n 9\n$DIMCLRE\n 70\n0\n 9\n$DIMCLRT\n 70\n0\n 9\n$DIMTFAC\n 40\n1.0\n 9\n$DIMGAP\n 40\n2.0\n 9\n$DIMJUST\n 70\n0\n 9\n$DIMSD1\n 70\n0\n 9\n$DIMSD2\n 70\n0\n 9\n$DIMTOLJ\n 70\n1\n 9\n$DIMTZIN\n 70\n0\n 9\n$DIMALTZ\n 70\n0\n 9\n$DIMALTTZ\n 70\n0\n 9\n$DIMUPT\n 70\n0\n 9\n$DIMDEC\n 70\n2\n 9\n$DIMTDEC\n 70\n2\n 9\n$DIMALTU\n 70\n2\n 9\n$DIMALTTD\n 70\n2\n 9\n$DIMTXSTY\n 7\nStandard\n 9\n$DIMAUNIT\n 70\n0\n 9\n$DIMADEC\n 70\n2\n 9\n$DIMALTRND\n 40\n0.0\n 9\n$DIMAZIN\n 70\n2\n 9\n$DIMDSEP\n 70\n46\n 9\n$DIMATFIT\n 70\n3\n 9\n$DIMFRAC\n 70\n1\n 9\n$DIMLDRBLK\n 1\n\n 9\n$DIMLUNIT\n 70\n2\n 9\n$DIMLWD\n 70\n-2\n 9\n$DIMLWE\n 70\n-2\n 9\n$DIMTMOVE\n 70\n0\n 9\n$DIMFXL\n 40\n1.0\n 9\n$DIMFXLON\n 70\n0\n 9\n$DIMJOGANG\n 40\n0.785398163397\n 9\n$DIMTFILL\n 70\n0\n 9\n$DIMTFILLCLR\n 70\n0\n 9\n$DIMARCSYM\n 70\n0\n 9\n$DIMLTYPE\n 6\n\n 9\n$DIMLTEX1\n 6\n\n 9\n$DIMLTEX2\n 6\n\n 9\n$DIMTXTDIRECTION\n 70\n0\n 9\n$LUNITS\n 70\n2\n 9\n$LUPREC\n 70\n4\n 9\n$SKETCHINC\n 40\n0.1\n 9\n$FILLETRAD\n 40\n0.0\n 9\n$AUNITS\n 70\n4\n 9\n$AUPREC\n 70\n5\n 9\n$MENU\n 1\n.\n 9\n$ELEVATION\n 40\n0.0\n 9\n$PELEVATION\n 40\n0.0\n 9\n$THICKNESS\n 40\n0.0\n 9\n$LIMCHECK\n 70\n0\n 9\n$CHAMFERA\n 40\n0.0\n 9\n$CHAMFERB\n 40\n0.0\n 9\n$CHAMFERC\n 40\n0.0\n 9\n$CHAMFERD\n 40\n0.0\n 9\n$SKPOLY\n 70\n0\n 9\n$TDCREATE\n 40\n2457986.69756\n 9\n$TDUCREATE\n 40\n2455631.2632\n 9\n$TDUPDATE\n 40\n2457986.69756\n 9\n$TDUUPDATE\n 40\n2456436.43179\n 9\n$TDINDWG\n 40\n0.0003490741\n 9\n$TDUSRTIMER\n 40\n0.0003487153\n 9\n$USRTIMER\n 70\n1\n 9\n$ANGBASE\n 50\n0.0\n 9\n$ANGDIR\n 70\n0\n 9\n$PDMODE\n 70\n0\n 9\n$PDSIZE\n 40\n0.0\n 9\n$PLINEWID\n 40\n0.0\n 9\n$SPLFRAME\n 70\n0\n 9\n$SPLINETYPE\n 70\n6\n 9\n$SPLINESEGS\n 70\n8\n 9\n$HANDSEED\n 5\n5C7\n 9\n$SURFTAB1\n 70\n6\n 9\n$SURFTAB2\n 70\n6\n 9\n$SURFTYPE\n 70\n6\n 9\n$SURFU\n 70\n6\n 9\n$SURFV\n 70\n6\n 9\n$UCSBASE\n 2\n\n 9\n$UCSNAME\n 2\n\n 9\n$UCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$UCSORTHOREF\n 2\n\n 9\n$UCSORTHOVIEW\n 70\n0\n 9\n$UCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSBASE\n 2\n\n 9\n$PUCSNAME\n 2\n\n 9\n$PUCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$PUCSORTHOREF\n 2\n\n 9\n$PUCSORTHOVIEW\n 70\n0\n 9\n$PUCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$USERI1\n 70\n0\n 9\n$USERI2\n 70\n0\n 9\n$USERI3\n 70\n0\n 9\n$USERI4\n 70\n0\n 9\n$USERI5\n 70\n0\n 9\n$USERR1\n 40\n0.0\n 9\n$USERR2\n 40\n0.0\n 9\n$USERR3\n 40\n0.0\n 9\n$USERR4\n 40\n0.0\n 9\n$USERR5\n 40\n0.0\n 9\n$WORLDVIEW\n 70\n1\n 9\n$SHADEDGE\n 70\n3\n 9\n$SHADEDIF\n 70\n70\n 9\n$TILEMODE\n 70\n1\n 9\n$MAXACTVP\n 70\n64\n 9\n$PINSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PLIMCHECK\n 70\n0\n 9\n$PEXTMIN\n 10\n0.628866766397\n 20\n0.799999952316\n 30\n0.0\n 9\n$PEXTMAX\n 10\n9.02886638493\n 20\n7.19999957085\n 30\n0.0\n 9\n$PLIMMIN\n 10\n-0.700541819174\n 20\n-0.228100386192\n 9\n$PLIMMAX\n 10\n10.2994579405\n 20\n8.27189937351\n 9\n$UNITMODE\n 70\n0\n 9\n$VISRETAIN\n 70\n1\n 9\n$PLINEGEN\n 70\n0\n 9\n$PSLTSCALE\n 70\n1\n 9\n$TREEDEPTH\n 70\n3020\n 9\n$CMLSTYLE\n 2\nStandard\n 9\n$CMLJUST\n 70\n0\n 9\n$CMLSCALE\n 40\n1.0\n 9\n$PROXYGRAPHICS\n 70\n1\n 9\n$MEASUREMENT\n 70\n1\n 9\n$CELWEIGHT\n370\n-1\n 9\n$ENDCAPS\n280\n0\n 9\n$JOINSTYLE\n280\n0\n 9\n$LWDISPLAY\n290\n0\n 9\n$INSUNITS\n 70\n4\n 9\n$HYPERLINKBASE\n 1\n\n 9\n$STYLESHEET\n 1\n\n 9\n$XEDIT\n290\n1\n 9\n$CEPSNTYPE\n380\n0\n 9\n$PSTYLEMODE\n290\n1\n 9\n$FINGERPRINTGUID\n 2\n{39DB1BDD-BC6C-46D3-A333-DFCC0DC4782D}\n 9\n$VERSIONGUID\n 2\n{69EEBB2D-7039-498F-9366-3F994E4A07E7}\n 9\n$EXTNAMES\n290\n1\n 9\n$PSVPSCALE\n 40\n0.0\n 9\n$OLESTARTUP\n290\n0\n 9\n$SORTENTS\n280\n127\n 9\n$INDEXCTL\n280\n0\n 9\n$HIDETEXT\n280\n1\n 9\n$XCLIPFRAME\n280\n0\n 9\n$HALOGAP\n280\n0\n 9\n$OBSCOLOR\n 70\n257\n 9\n$OBSLTYPE\n280\n0\n 9\n$INTERSECTIONDISPLAY\n280\n0\n 9\n$INTERSECTIONCOLOR\n 70\n257\n 9\n$DIMASSOC\n280\n2\n 9\n$PROJECTNAME\n 1\n\n 9\n$CAMERADISPLAY\n290\n0\n 9\n$LENSLENGTH\n 40\n50.0\n 9\n$CAMERAHEIGHT\n 40\n0.0\n 9\n$STEPSPERSEC\n 40\n2.0\n 9\n$STEPSIZE\n 40\n6.0\n 9\n$3DDWFPREC\n 40\n2.0\n 9\n$PSOLWIDTH\n 40\n0.25\n 9\n$PSOLHEIGHT\n 40\n4.0\n 9\n$LOFTANG1\n 40\n1.57079632679\n 9\n$LOFTANG2\n 40\n1.57079632679\n 9\n$LOFTMAG1\n 40\n0.0\n 9\n$LOFTMAG2\n 40\n0.0\n 9\n$LOFTPARAM\n 70\n7\n 9\n$LOFTNORMALS\n280\n1\n 9\n$LATITUDE\n 40\n37.795\n 9\n$LONGITUDE\n 40\n-122.394\n 9\n$NORTHDIRECTION\n 40\n0.0\n 9\n$TIMEZONE\n 70\n-8000\n 9\n$LIGHTGLYPHDISPLAY\n280\n1\n 9\n$TILEMODELIGHTSYNCH\n280\n1\n 9\n$CMATERIAL\n347\n96\n 9\n$SOLIDHIST\n280\n1\n 9\n$SHOWHIST\n280\n1\n 9\n$DWFFRAME\n280\n2\n 9\n$DGNFRAME\n280\n0\n 9\n$REALWORLDSCALE\n290\n1\n 9\n$INTERFERECOLOR\n 62\n1\n 9\n$INTERFEREOBJVS\n345\nA3\n 9\n$INTERFEREVPVS\n346\nA0\n 9\n$CSHADOW\n280\n0\n 9\n$SHADOWPLANELOCATION\n 40\n0.0\n 0\nENDSEC\n 0\nSECTION\n 2\nCLASSES\n 0\nCLASS\n 1\nACDBDICTIONARYWDFLT\n 2\nAcDbDictionaryWithDefault\n 3\nObjectDBX Classes\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nDICTIONARYVAR\n 2\nAcDbDictionaryVar\n 3\nObjectDBX Classes\n 90\n0\n 91\n15\n280\n0\n281\n0\n 0\nCLASS\n 1\nTABLESTYLE\n 2\nAcDbTableStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nMATERIAL\n 2\nAcDbMaterial\n 3\nObjectDBX Classes\n 90\n1153\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nVISUALSTYLE\n 2\nAcDbVisualStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n26\n280\n0\n281\n0\n 0\nCLASS\n 1\nSCALE\n 2\nAcDbScale\n 3\nObjectDBX Classes\n 90\n1153\n 91\n17\n280\n0\n281\n0\n 0\nCLASS\n 1\nMLEADERSTYLE\n 2\nAcDbMLeaderStyle\n 3\nACDB_MLEADERSTYLE_CLASS\n 90\n4095\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nCELLSTYLEMAP\n 2\nAcDbCellStyleMap\n 3\nObjectDBX Classes\n 90\n1152\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nEXACXREFPANELOBJECT\n 2\nExAcXREFPanelObject\n 3\nEXAC_ESW\n 90\n1025\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nNPOCOLLECTION\n 2\nAcDbImpNonPersistentObjectsCollection\n 3\nObjectDBX Classes\n 90\n1153\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nLAYER_INDEX\n 2\nAcDbLayerIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nSPATIAL_INDEX\n 2\nAcDbSpatialIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nIDBUFFER\n 2\nAcDbIdBuffer\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nDIMASSOC\n 2\nAcDbDimAssoc\n 3\n"AcDbDimAssoc|Product Desc: AcDim ARX App For Dimension|Company: Autodesk, Inc.|WEB Address: www.autodesk.com"\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBSECTIONVIEWSTYLE\n 2\nAcDbSectionViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBDETAILVIEWSTYLE\n 2\nAcDbDetailViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF\n 2\nAcDbRasterImageDef\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nRASTERVARIABLES\n 2\nAcDbRasterVariables\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF_REACTOR\n 2\nAcDbRasterImageDefReactor\n 3\nISM\n 90\n1\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGE\n 2\nAcDbRasterImage\n 3\nISM\n 90\n2175\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nPDFDEFINITION\n 2\nAcDbPdfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nPDFUNDERLAY\n 2\nAcDbPdfReference\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDWFDEFINITION\n 2\nAcDbDwfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDWFUNDERLAY\n 2\nAcDbDwfReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDGNDEFINITION\n 2\nAcDbDgnDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDGNUNDERLAY\n 2\nAcDbDgnReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nENDSEC\n 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nVPORT\n 5\n8\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLTYPE\n 5\n5F\n330\n0\n100\nAcDbSymbolTable\n 70\n7\n 0\nLTYPE\n 5\n14\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByBlock\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n15\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByLayer\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n16\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nContinuous\n 70\n0\n 3\nSolid line\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n1B1\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nCENTER\n 70\n0\n 3\nCenter ____ _ ____ _ ____ _ ____ _ ____ _ ____\n 72\n65\n 73\n4\n 40\n2.0\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B2\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nDASHED\n 70\n0\n 3\nDashed __ __ __ __ __ __ __ __ __ __ __ __ __ _\n 72\n65\n 73\n2\n 40\n0.75\n 49\n0.5\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B3\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nPHANTOM\n 70\n0\n 3\nPhantom ______ __ __ ______ __ __ ______\n 72\n65\n 73\n6\n 40\n2.5\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n39E\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nHIDDEN\n 70\n0\n 3\nHidden __ __ __ __ __ __ __ __ __ __ __ __ __ __\n 72\n65\n 73\n2\n 40\n9.525\n 49\n6.35\n 74\n0\n 49\n-3.175\n 74\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLAYER\n 5\n2\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nLAYER\n 5\n10\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\n0\n 70\n0\n 6\nContinuous\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n1B4\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nView Port\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n21D\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nDefpoints\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nSTYLE\n 5\n3\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nSTYLE\n 5\n11\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nStandard\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\nDC\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\n178\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nNotes\n 70\n0\n 40\n3.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nENDTAB\n 0\nTABLE\n 2\nVIEW\n 5\n6\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nUCS\n 5\n7\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nAPPID\n 5\n9\n330\n0\n100\nAcDbSymbolTable\n 70\n12\n 0\nAPPID\n 5\n12\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD\n 70\n0\n 0\nAPPID\n 5\nDD\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnoPO\n 70\n0\n 0\nAPPID\n 5\nDE\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnotative\n 70\n0\n 0\nAPPID\n 5\nDF\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMJAG\n 70\n0\n 0\nAPPID\n 5\nE0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMTALN\n 70\n0\n 0\nAPPID\n 5\n107\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_MLEADERVER\n 70\n0\n 0\nAPPID\n 5\n1B5\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcAecLayerStandard\n 70\n0\n 0\nAPPID\n 5\n1BA\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_EXEMPT_FROM_CAD_STANDARDS\n 70\n0\n 0\nAPPID\n 5\n237\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMBREAK\n 70\n0\n 0\nAPPID\n 5\n28E\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_PSEXT\n 70\n0\n 0\nAPPID\n 5\n4B0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_NAV_VCDISPLAY\n 70\n0\n 0\nAPPID\n 5\n4E3\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nHATCHBACKGROUNDCOLOR\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nDIMSTYLE\n 5\nA\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n100\nAcDbDimStyleTable\n 71\n3\n340\n242\n340\n27\n340\nE1\n 0\nDIMSTYLE\n105\n27\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nStandard\n 70\n0\n 41\n3.0\n 42\n2.0\n 43\n9.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\nE1\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n3.0\n 42\n2.5\n 43\n10.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nAcadAnnotative\n1000\nAnnotativeData\n1002\n{\n1070\n1\n1070\n1\n1002\n}\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\n242\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nCivil-Metric\n 70\n0\n 41\n3.0\n 42\n1.5\n 43\n6.0\n 44\n3.0\n 73\n0\n 74\n0\n 77\n1\n 78\n3\n 79\n2\n140\n3.0\n141\n3.0\n147\n2.0\n179\n2\n271\n2\n272\n2\n276\n1\n340\n11\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n3.0\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nBLOCK_RECORD\n 5\n1\n330\n0\n100\nAcDbSymbolTable\n 70\n4\n 0\nBLOCK_RECORD\n 5\n1F\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Model_Space\n340\n530\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n58\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Paper_Space\n340\n531\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n238\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_ArchTick\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n23C\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_Open30\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nENDTAB\n 0\nENDSEC\n 0\nSECTION\n 2\nBLOCKS\n 0\nBLOCK\n 5\n23A\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_ArchTick\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_ArchTick\n 1\n\n 0\nENDBLK\n 5\n23B\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n20\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Model_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Model_Space\n 1\n\n 0\nENDBLK\n 5\n21\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n5A\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Paper_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Paper_Space\n 1\n\n 0\nENDBLK\n 5\n5B\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n240\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_Open30\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_Open30\n 1\n\n 0\nENDBLK\n 5\n241\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nENDSEC\n${dxfEntities(objects,options)}\n 0\nSECTION\n 2\nOBJECTS\n 0\nDICTIONARY\n 5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n 3\nACAD_COLOR\n350\n524\n 3\nACAD_GROUP\n350\n525\n 3\nACAD_LAYOUT\n350\n526\n 3\nACAD_MATERIAL\n350\n527\n 3\nACAD_MLEADERSTYLE\n350\n528\n 3\nACAD_MLINESTYLE\n350\n529\n 3\nACAD_PLOTSETTINGS\n350\n52A\n 3\nACAD_PLOTSTYLENAME\n350\n52C\n 3\nACAD_SCALELIST\n350\n52D\n 3\nACAD_TABLESTYLE\n350\n52E\n 3\nACAD_VISUALSTYLE\n350\n52F\n 0\nDICTIONARY\n 5\n524\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n525\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n526\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nModel\n350\n530\n 3\nLayout1\n350\n531\n 0\nDICTIONARY\n 5\n527\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n528\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n529\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52A\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nACDBPLACEHOLDER\n 5\n52B\n330\n52C\n 0\nACDBDICTIONARYWDFLT\n 5\n52C\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nNormal\n350\n52B\n100\nAcDbDictionaryWithDefault\n340\n52B\n 0\nDICTIONARY\n 5\n52D\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52E\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52F\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nLAYOUT\n 5\n530\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n14.53\n 70\n11952\n 72\n0\n 73\n1\n 74\n0\n 7\n\n 75\n0\n147\n0.069\n148\n114.98\n149\n300.29\n100\nAcDbLayout\n 1\nModel\n 70\n1\n 71\n0\n 10\n0.0\n 20\n0.0\n 11\n12.0\n 21\n9.0\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.0\n 24\n0.0\n 34\n0.0\n 15\n0.0\n 25\n0.0\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n1F\n 0\nLAYOUT\n 5\n531\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n1.0\n 70\n688\n 72\n0\n 73\n1\n 74\n5\n 7\nacad.ctb\n 75\n16\n147\n1.0\n148\n0.0\n149\n0.0\n100\nAcDbLayout\n 1\nLayout1\n 70\n1\n 71\n1\n 10\n-0.7\n 20\n-0.23\n 11\n10.3\n 21\n8.27\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.63\n 24\n0.8\n 34\n0.0\n 15\n9.0\n 25\n7.2\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n58\n 0\nENDSEC\n 0\nEOF\n`]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadDxfSerializer={}); diff --git a/packages/io/dxf-serializer/package.json b/packages/io/dxf-serializer/package.json index 7fb49fbfb..082cb4ef5 100644 --- a/packages/io/dxf-serializer/package.json +++ b/packages/io/dxf-serializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/dxf-serializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "DXF Serializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -37,8 +37,8 @@ ], "license": "MIT", "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0" + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0" }, "devDependencies": { "@rollup/plugin-node-resolve": "^15.0.1", diff --git a/packages/io/io-utils/CHANGELOG.md b/packages/io/io-utils/CHANGELOG.md index b65d6647a..16335e335 100644 --- a/packages/io/io-utils/CHANGELOG.md +++ b/packages/io/io-utils/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/io-utils@2.0.22...@jscad/io-utils@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/io-utils@2.0.22...@jscad/io-utils@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/io-utils/package.json b/packages/io/io-utils/package.json index 9703bc30c..aa1ae7496 100644 --- a/packages/io/io-utils/package.json +++ b/packages/io/io-utils/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/io-utils", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "Utilities for JSCAD IO Packages", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -34,7 +34,7 @@ ], "license": "MIT", "devDependencies": { - "@jscad/modeling": "workspace:3.0.0-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", "ava": "^4.3.3", "c8": "^8.0.0" }, diff --git a/packages/io/io/CHANGELOG.md b/packages/io/io/CHANGELOG.md index 962250a56..be9796d43 100644 --- a/packages/io/io/CHANGELOG.md +++ b/packages/io/io/CHANGELOG.md @@ -3,6 +3,19 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/io@2.4.3...@jscad/io@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **3mf-deserializer:** initial version of 3MF deserializer and tests ([b22a27f](https://github.com/jscad/OpenJSCAD.org/commit/b22a27fa14c4f42b9160553cdd7b3c126ac72459)) +* **cli:** reworked logic to use new io package exports and functions ([#1199](https://github.com/jscad/OpenJSCAD.org/issues/1199)) ([71a3d27](https://github.com/jscad/OpenJSCAD.org/commit/71a3d27a4cf416b1a9fea57a1fe40f5cfdaa905c)) +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) +* **regl-renderer:** added rollup configuration to create ES6 bundle, adjusted imports and exports ([#1259](https://github.com/jscad/OpenJSCAD.org/issues/1259)) ([47a66bc](https://github.com/jscad/OpenJSCAD.org/commit/47a66bc07a137a748ce8571ea5d043ebaab9418d)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/io@2.4.3...@jscad/io@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/io/package.json b/packages/io/io/package.json index d45cd4c6c..ea971f502 100644 --- a/packages/io/io/package.json +++ b/packages/io/io/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/io", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "Meta Package for JSCAD IO Packages", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -34,23 +34,23 @@ ], "license": "MIT", "dependencies": { - "@jscad/3mf-deserializer": "workspace:3.0.0-alpha.0", - "@jscad/3mf-serializer": "workspace:3.0.0-alpha.0", - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/dxf-deserializer": "workspace:3.0.0-alpha.0", - "@jscad/dxf-serializer": "workspace:3.0.0-alpha.0", - "@jscad/io-utils": "workspace:3.0.0-alpha.0", - "@jscad/json-deserializer": "workspace:3.0.0-alpha.0", - "@jscad/json-serializer": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0", - "@jscad/obj-deserializer": "workspace:3.0.0-alpha.0", - "@jscad/obj-serializer": "workspace:3.0.0-alpha.0", - "@jscad/stl-deserializer": "workspace:3.0.0-alpha.0", - "@jscad/stl-serializer": "workspace:3.0.0-alpha.0", - "@jscad/svg-deserializer": "workspace:3.0.0-alpha.0", - "@jscad/svg-serializer": "workspace:3.0.0-alpha.0", - "@jscad/x3d-deserializer": "workspace:3.0.0-alpha.0", - "@jscad/x3d-serializer": "workspace:3.0.0-alpha.0" + "@jscad/3mf-deserializer": "workspace:3.0.1-alpha.0", + "@jscad/3mf-serializer": "workspace:3.0.1-alpha.0", + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/dxf-deserializer": "workspace:3.0.1-alpha.0", + "@jscad/dxf-serializer": "workspace:3.0.1-alpha.0", + "@jscad/io-utils": "workspace:3.0.1-alpha.0", + "@jscad/json-deserializer": "workspace:3.0.1-alpha.0", + "@jscad/json-serializer": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", + "@jscad/obj-deserializer": "workspace:3.0.1-alpha.0", + "@jscad/obj-serializer": "workspace:3.0.1-alpha.0", + "@jscad/stl-deserializer": "workspace:3.0.1-alpha.0", + "@jscad/stl-serializer": "workspace:3.0.1-alpha.0", + "@jscad/svg-deserializer": "workspace:3.0.1-alpha.0", + "@jscad/svg-serializer": "workspace:3.0.1-alpha.0", + "@jscad/x3d-deserializer": "workspace:3.0.1-alpha.0", + "@jscad/x3d-serializer": "workspace:3.0.1-alpha.0" }, "devDependencies": { "ava": "^4.3.3", diff --git a/packages/io/json-deserializer/CHANGELOG.md b/packages/io/json-deserializer/CHANGELOG.md index 276f46a16..e34a3ddf5 100644 --- a/packages/io/json-deserializer/CHANGELOG.md +++ b/packages/io/json-deserializer/CHANGELOG.md @@ -3,6 +3,17 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/json-deserializer@2.0.23...@jscad/json-deserializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) +* **regl-renderer:** added rollup configuration to create ES6 bundle, adjusted imports and exports ([#1259](https://github.com/jscad/OpenJSCAD.org/issues/1259)) ([47a66bc](https://github.com/jscad/OpenJSCAD.org/commit/47a66bc07a137a748ce8571ea5d043ebaab9418d)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/json-deserializer@2.0.23...@jscad/json-deserializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/json-deserializer/dist/jscad-json-deserializer.es.js b/packages/io/json-deserializer/dist/jscad-json-deserializer.es.js index 0fdd8d70c..31d3bf388 100644 --- a/packages/io/json-deserializer/dist/jscad-json-deserializer.es.js +++ b/packages/io/json-deserializer/dist/jscad-json-deserializer.es.js @@ -1,13 +1,13 @@ /** * JSON Deserializer for JSCAD * @module @jscad/json-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ /** * JSCAD Utility functions for arrays * @module @jscad/array-utils - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),deserialize=(options,input)=>{const defaults={filename:"json",output:"script",version:"3.0.0-alpha.0",addMetaData:!0};options=Object.assign({},defaults,options);let objects=JSON.parse(input);var array;return objects=flatten((array=objects,Array.isArray(array)?array:null==array?[]:[array])),"script"===options.output?translate(options,objects):objects},translate=(options,objects)=>{const{addMetaData:addMetaData,filename:filename,version:version}=options;let script=addMetaData?`//\n// Produced by JSCAD IO Library : JSON Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n`:"";return script+=`\nconst { geometries } = require('@jscad/modeling')\n\nconst main = () => {\n const objects = [${translateToList(objects)} ]\n return objects\n}\n\n${translateToObjects(objects)}\n\nmodule.exports = { main }\n`,script},translateToList=objects=>objects.reduce(((script,object,index)=>script+` json${index},`),""),translateToObjects=objects=>objects.reduce(((script,object,index)=>script+translateToObject(object,index)),""),translateToObject=(object,index)=>`const json${index} = ${JSON.stringify(object)}\n`,mimeType="application/json";export{deserialize,mimeType}; +const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),deserialize=(options,input)=>{const defaults={filename:"json",output:"script",version:"3.0.1-alpha.0",addMetaData:!0};options=Object.assign({},defaults,options),input=((stringOrArrayBuffer,defaultBinaryEncoding="utf-8")=>"string"==typeof stringOrArrayBuffer?stringOrArrayBuffer:new TextDecoder(defaultBinaryEncoding).decode(new Uint8Array(stringOrArrayBuffer)))(input);let objects=JSON.parse(input);var array;return objects=flatten((array=objects,Array.isArray(array)?array:null==array?[]:[array])),"script"===options.output?translate(options,objects):objects},translate=(options,objects)=>{const{addMetaData:addMetaData,filename:filename,version:version}=options;let script=addMetaData?`//\n// Produced by JSCAD IO Library : JSON Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n`:"";return script+=`\nconst { geometries } = require('@jscad/modeling')\n\nconst main = () => {\n const objects = [${translateToList(objects)} ]\n return objects\n}\n\n${translateToObjects(objects)}\n\nmodule.exports = { main }\n`,script},translateToList=objects=>objects.reduce(((script,object,index)=>script+` json${index},`),""),translateToObjects=objects=>objects.reduce(((script,object,index)=>script+translateToObject(object,index)),""),translateToObject=(object,index)=>`const json${index} = ${JSON.stringify(object)}\n`,mimeType="application/json";export{deserialize,mimeType}; diff --git a/packages/io/json-deserializer/dist/jscad-json-deserializer.min.js b/packages/io/json-deserializer/dist/jscad-json-deserializer.min.js index 5a87afb96..c36bb342e 100644 --- a/packages/io/json-deserializer/dist/jscad-json-deserializer.min.js +++ b/packages/io/json-deserializer/dist/jscad-json-deserializer.min.js @@ -1,14 +1,14 @@ /** * JSON Deserializer for JSCAD * @module @jscad/json-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ var global,factory;global=this,factory=function(exports){ /** * JSCAD Utility functions for arrays * @module @jscad/array-utils - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),translate=(options,objects)=>{const{addMetaData:addMetaData,filename:filename,version:version}=options;let script=addMetaData?`//\n// Produced by JSCAD IO Library : JSON Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n`:"";return script+=`\nconst { geometries } = require('@jscad/modeling')\n\nconst main = () => {\n const objects = [${translateToList(objects)} ]\n return objects\n}\n\n${translateToObjects(objects)}\n\nmodule.exports = { main }\n`,script},translateToList=objects=>objects.reduce(((script,object,index)=>script+` json${index},`),""),translateToObjects=objects=>objects.reduce(((script,object,index)=>script+translateToObject(object,index)),""),translateToObject=(object,index)=>`const json${index} = ${JSON.stringify(object)}\n`;exports.deserialize=(options,input)=>{const defaults={filename:"json",output:"script",version:"3.0.0-alpha.0",addMetaData:!0};options=Object.assign({},defaults,options);let objects=JSON.parse(input);var array;return objects=flatten((array=objects,Array.isArray(array)?array:null==array?[]:[array])),"script"===options.output?translate(options,objects):objects},exports.mimeType="application/json",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadJsonDeserializer={}); +const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),translate=(options,objects)=>{const{addMetaData:addMetaData,filename:filename,version:version}=options;let script=addMetaData?`//\n// Produced by JSCAD IO Library : JSON Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n`:"";return script+=`\nconst { geometries } = require('@jscad/modeling')\n\nconst main = () => {\n const objects = [${translateToList(objects)} ]\n return objects\n}\n\n${translateToObjects(objects)}\n\nmodule.exports = { main }\n`,script},translateToList=objects=>objects.reduce(((script,object,index)=>script+` json${index},`),""),translateToObjects=objects=>objects.reduce(((script,object,index)=>script+translateToObject(object,index)),""),translateToObject=(object,index)=>`const json${index} = ${JSON.stringify(object)}\n`;exports.deserialize=(options,input)=>{const defaults={filename:"json",output:"script",version:"3.0.1-alpha.0",addMetaData:!0};options=Object.assign({},defaults,options),input=((stringOrArrayBuffer,defaultBinaryEncoding="utf-8")=>"string"==typeof stringOrArrayBuffer?stringOrArrayBuffer:new TextDecoder(defaultBinaryEncoding).decode(new Uint8Array(stringOrArrayBuffer)))(input);let objects=JSON.parse(input);var array;return objects=flatten((array=objects,Array.isArray(array)?array:null==array?[]:[array])),"script"===options.output?translate(options,objects):objects},exports.mimeType="application/json",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadJsonDeserializer={}); diff --git a/packages/io/json-deserializer/package.json b/packages/io/json-deserializer/package.json index 9234e6d58..e829164e2 100644 --- a/packages/io/json-deserializer/package.json +++ b/packages/io/json-deserializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/json-deserializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "JSON Deserializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -33,11 +33,11 @@ ], "license": "MIT", "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/io-utils": "workspace:3.0.0-alpha.0" + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/io-utils": "workspace:3.0.1-alpha.0" }, "devDependencies": { - "@jscad/modeling": "workspace:3.0.0-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", "@rollup/plugin-node-resolve": "^15.0.1", "@rollup/plugin-terser": "^0.4.3", "ava": "^4.3.3", diff --git a/packages/io/json-serializer/CHANGELOG.md b/packages/io/json-serializer/CHANGELOG.md index 05627f68a..385e22b21 100644 --- a/packages/io/json-serializer/CHANGELOG.md +++ b/packages/io/json-serializer/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/json-serializer@2.0.22...@jscad/json-serializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/json-serializer@2.0.22...@jscad/json-serializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/json-serializer/dist/jscad-json-serializer.es.js b/packages/io/json-serializer/dist/jscad-json-serializer.es.js index 0189d197d..4d522c31a 100644 --- a/packages/io/json-serializer/dist/jscad-json-serializer.es.js +++ b/packages/io/json-serializer/dist/jscad-json-serializer.es.js @@ -1,13 +1,13 @@ /** * JSON Serializer for JSCAD * @module @jscad/json-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ /** * JSCAD Utility functions for arrays * @module @jscad/array-utils - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),mimeType="application/json",replacer=(key,value)=>{switch(key){case"transforms":case"plane":return Array.from(value);case"points":case"vertices":return value.map((v=>Array.from(v)));case"outlines":return value.map((o=>o.map((v=>Array.from(v)))))}return value},serialize=(options,...objects)=>{options=Object.assign({},{statusCallback:null},options),objects=flatten(objects),options.statusCallback&&options.statusCallback({progress:0});const notation=JSON.stringify(objects,replacer);return options.statusCallback&&options.statusCallback({progress:100}),[notation]};export{mimeType,serialize}; diff --git a/packages/io/json-serializer/dist/jscad-json-serializer.min.js b/packages/io/json-serializer/dist/jscad-json-serializer.min.js index 067f0480f..f1c85452b 100644 --- a/packages/io/json-serializer/dist/jscad-json-serializer.min.js +++ b/packages/io/json-serializer/dist/jscad-json-serializer.min.js @@ -1,14 +1,14 @@ /** * JSON Serializer for JSCAD * @module @jscad/json-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ var global,factory;global=this,factory=function(exports){ /** * JSCAD Utility functions for arrays * @module @jscad/array-utils - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),replacer=(key,value)=>{switch(key){case"transforms":case"plane":return Array.from(value);case"points":case"vertices":return value.map((v=>Array.from(v)));case"outlines":return value.map((o=>o.map((v=>Array.from(v)))))}return value};exports.mimeType="application/json",exports.serialize=(options,...objects)=>{options=Object.assign({},{statusCallback:null},options),objects=flatten(objects),options.statusCallback&&options.statusCallback({progress:0});const notation=JSON.stringify(objects,replacer);return options.statusCallback&&options.statusCallback({progress:100}),[notation]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadJsonSerializer={}); diff --git a/packages/io/json-serializer/package.json b/packages/io/json-serializer/package.json index 22380d871..954c68ca2 100644 --- a/packages/io/json-serializer/package.json +++ b/packages/io/json-serializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/json-serializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "JSON Serializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -33,8 +33,8 @@ ], "license": "MIT", "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0" + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0" }, "devDependencies": { "@rollup/plugin-node-resolve": "^15.0.1", diff --git a/packages/io/obj-deserializer/CHANGELOG.md b/packages/io/obj-deserializer/CHANGELOG.md index 0df53aab9..7d3ff6126 100644 --- a/packages/io/obj-deserializer/CHANGELOG.md +++ b/packages/io/obj-deserializer/CHANGELOG.md @@ -3,6 +3,17 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/obj-deserializer@2.0.22...@jscad/obj-deserializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) +* **regl-renderer:** added rollup configuration to create ES6 bundle, adjusted imports and exports ([#1259](https://github.com/jscad/OpenJSCAD.org/issues/1259)) ([47a66bc](https://github.com/jscad/OpenJSCAD.org/commit/47a66bc07a137a748ce8571ea5d043ebaab9418d)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/obj-deserializer@2.0.22...@jscad/obj-deserializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/obj-deserializer/dist/jscad-obj-deserializer.es.js b/packages/io/obj-deserializer/dist/jscad-obj-deserializer.es.js index 14c0321fe..7eb56ce24 100644 --- a/packages/io/obj-deserializer/dist/jscad-obj-deserializer.es.js +++ b/packages/io/obj-deserializer/dist/jscad-obj-deserializer.es.js @@ -1,13 +1,13 @@ /** * OBJ Deserializer for JSCAD * @module @jscad/obj-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ +const cssColors={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]},clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out}; /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT - */ -const cssColors={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]},clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),deserialize=(options,input)=>{const defaults={filename:"obj",output:"script",orientation:"outward",version:"3.0.0-alpha.0",addMetaData:!0};options=Object.assign({},defaults,options);const{output:output}=options;options&&options.statusCallback&&options.statusCallback({progress:0});const{positions:positions,groups:groups}=getGroups(input),result="script"===output?stringify(positions,groups,options):objectify(positions,groups,options);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},getGroups=(data,options)=>{let groups=[];const positions=[];let material=null;groups.push({faces:[],colors:[],name:"default",line:0});const handleG=(command,values)=>{const group={faces:[],colors:[],name:""};values&&values.length>0&&(group.name=values.join(" ")),groups.push(group)},handleV=(command,values)=>{const x=parseFloat(values[0]),y=parseFloat(values[1]),z=parseFloat(values[2]);positions.push([x,y,z])},handleF=(command,values)=>{const facerefs=values.map((value=>{const refs=value.match(/[0-9+\-eE]+/g);let ref=parseInt(refs[0]);return ref<0?ref=positions.length+ref:ref--,ref})),group=groups.pop();group.faces.push(facerefs),group.colors.push(material),groups.push(group)},handleMtl=(command,values)=>{if(material=null,values&&values.length>0){const c=(s=values[0],cssColors[s.toLowerCase()]);c&&(material=[c[0],c[1],c[2],1])}var s},lines=data.split(/\n/);for(let i=0;i0){let values=line.match(/\S+/g);if(values){const command=values[0];switch(values=values.slice(1),command){case"g":handleG(0,values);break;case"v":handleV(0,values);break;case"f":handleF(0,values);break;case"usemtl":handleMtl(0,values)}}}}return groups=groups.filter((group=>group.faces.length>0)),{positions:positions,groups:groups}},objectify=(points,groups,options)=>{const geometries=groups.map((group=>(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({orientation:options.orientation,points:points,faces:group.faces,colors:group.colors})));return geometries},stringify=(positions,groups,options)=>{const{filename:filename,addMetaData:addMetaData,version:version}=options;let code=addMetaData?`//\n// Produced by JSCAD IO Library : OBJ Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n `:"";return code+=`import * from '@jscad/modeling'\n\n// groups: ${groups.length}\n// points: ${positions.length}\nexport const main = () => {\n // points are common to all geometries\n${(points=>{let code=" let points = [\n";return points.forEach((point=>code+=` [${point}],\n`)),code+=" ]",code})(positions)}\n\n let geometries = [\n${(groups=>{let code="";return groups.forEach(((group,index)=>code+=` group${index}(points), // ${group.name}\n`)),code})(groups)} ]\n return geometries\n}\n\n${((groups,options)=>{let code="";return groups.forEach(((group,index)=>{const faces=group.faces,colors=group.colors;code+=`\n// group : ${group.name}\n// faces: ${faces.length}\n`,code+=`const group${index} = (points) => {\n${(faces=>{let code=" let faces = [\n";return faces.forEach((face=>code+=` [${face}],\n`)),code+=" ]",code})(faces)}\n${(colors=>{let code=" let colors = [\n";return colors.forEach((c=>{code+=c?` [${c}],\n`:" null,\n"})),code+=" ]",code})(colors)}\n return polyhedron({ orientation: '${options.orientation}', points, faces, colors })\n}\n`})),code})(groups,options)}\n`,code},mimeType="model/obj";export{deserialize,mimeType}; + */Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),deserialize=(options,input)=>{const defaults={filename:"obj",output:"script",orientation:"outward",version:"3.0.1-alpha.0",addMetaData:!0};options=Object.assign({},defaults,options);const{output:output}=options;options&&options.statusCallback&&options.statusCallback({progress:0}),input=((stringOrArrayBuffer,defaultBinaryEncoding="utf-8")=>"string"==typeof stringOrArrayBuffer?stringOrArrayBuffer:new TextDecoder(defaultBinaryEncoding).decode(new Uint8Array(stringOrArrayBuffer)))(input);const{positions:positions,groups:groups}=getGroups(input),result="script"===output?stringify(positions,groups,options):objectify(positions,groups,options);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},getGroups=(data,options)=>{let groups=[];const positions=[];let material=null;groups.push({faces:[],colors:[],name:"default",line:0});const handleG=(command,values)=>{const group={faces:[],colors:[],name:""};values&&values.length>0&&(group.name=values.join(" ")),groups.push(group)},handleV=(command,values)=>{const x=parseFloat(values[0]),y=parseFloat(values[1]),z=parseFloat(values[2]);positions.push([x,y,z])},handleF=(command,values)=>{const facerefs=values.map((value=>{const refs=value.match(/[0-9+\-eE]+/g);let ref=parseInt(refs[0]);return ref<0?ref=positions.length+ref:ref--,ref})),group=groups.pop();group.faces.push(facerefs),group.colors.push(material),groups.push(group)},handleMtl=(command,values)=>{if(material=null,values&&values.length>0){const c=(s=values[0],cssColors[s.toLowerCase()]);c&&(material=[c[0],c[1],c[2],1])}var s},lines=data.split(/\n/);for(let i=0;i0){let values=line.match(/\S+/g);if(values){const command=values[0];switch(values=values.slice(1),command){case"g":handleG(0,values);break;case"v":handleV(0,values);break;case"f":handleF(0,values);break;case"usemtl":handleMtl(0,values)}}}}return groups=groups.filter((group=>group.faces.length>0)),{positions:positions,groups:groups}},objectify=(points,groups,options)=>{const geometries=groups.map((group=>(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({orientation:options.orientation,points:points,faces:group.faces,colors:group.colors})));return geometries},stringify=(positions,groups,options)=>{const{filename:filename,addMetaData:addMetaData,version:version}=options;let code=addMetaData?`//\n// Produced by JSCAD IO Library : OBJ Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n `:"";return code+=`import * from '@jscad/modeling'\n\n// groups: ${groups.length}\n// points: ${positions.length}\nexport const main = () => {\n // points are common to all geometries\n${(points=>{let code=" let points = [\n";return points.forEach((point=>code+=` [${point}],\n`)),code+=" ]",code})(positions)}\n\n let geometries = [\n${(groups=>{let code="";return groups.forEach(((group,index)=>code+=` group${index}(points), // ${group.name}\n`)),code})(groups)} ]\n return geometries\n}\n\n${((groups,options)=>{let code="";return groups.forEach(((group,index)=>{const faces=group.faces,colors=group.colors;code+=`\n// group : ${group.name}\n// faces: ${faces.length}\n`,code+=`const group${index} = (points) => {\n${(faces=>{let code=" let faces = [\n";return faces.forEach((face=>code+=` [${face}],\n`)),code+=" ]",code})(faces)}\n${(colors=>{let code=" let colors = [\n";return colors.forEach((c=>{code+=c?` [${c}],\n`:" null,\n"})),code+=" ]",code})(colors)}\n return polyhedron({ orientation: '${options.orientation}', points, faces, colors })\n}\n`})),code})(groups,options)}\n`,code},mimeType="model/obj";export{deserialize,mimeType}; diff --git a/packages/io/obj-deserializer/dist/jscad-obj-deserializer.min.js b/packages/io/obj-deserializer/dist/jscad-obj-deserializer.min.js index 69dfb0fca..38f61150a 100644 --- a/packages/io/obj-deserializer/dist/jscad-obj-deserializer.min.js +++ b/packages/io/obj-deserializer/dist/jscad-obj-deserializer.min.js @@ -1,14 +1,13 @@ /** * OBJ Deserializer for JSCAD * @module @jscad/obj-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -var global,factory;global=this,factory=function(exports){ +var global,factory;global=this,factory=function(exports){const cssColors={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]},clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out}; /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT - */ -const cssColors={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]},clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),getGroups=(data,options)=>{let groups=[];const positions=[];let material=null;groups.push({faces:[],colors:[],name:"default",line:0});const handleG=(command,values)=>{const group={faces:[],colors:[],name:""};values&&values.length>0&&(group.name=values.join(" ")),groups.push(group)},handleV=(command,values)=>{const x=parseFloat(values[0]),y=parseFloat(values[1]),z=parseFloat(values[2]);positions.push([x,y,z])},handleF=(command,values)=>{const facerefs=values.map((value=>{const refs=value.match(/[0-9+\-eE]+/g);let ref=parseInt(refs[0]);return ref<0?ref=positions.length+ref:ref--,ref})),group=groups.pop();group.faces.push(facerefs),group.colors.push(material),groups.push(group)},handleMtl=(command,values)=>{if(material=null,values&&values.length>0){const c=(s=values[0],cssColors[s.toLowerCase()]);c&&(material=[c[0],c[1],c[2],1])}var s},lines=data.split(/\n/);for(let i=0;i0){let values=line.match(/\S+/g);if(values){const command=values[0];switch(values=values.slice(1),command){case"g":handleG(0,values);break;case"v":handleV(0,values);break;case"f":handleF(0,values);break;case"usemtl":handleMtl(0,values)}}}}return groups=groups.filter((group=>group.faces.length>0)),{positions:positions,groups:groups}},objectify=(points,groups,options)=>{const geometries=groups.map((group=>(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({orientation:options.orientation,points:points,faces:group.faces,colors:group.colors})));return geometries},stringify=(positions,groups,options)=>{const{filename:filename,addMetaData:addMetaData,version:version}=options;let code=addMetaData?`//\n// Produced by JSCAD IO Library : OBJ Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n `:"";return code+=`import * from '@jscad/modeling'\n\n// groups: ${groups.length}\n// points: ${positions.length}\nexport const main = () => {\n // points are common to all geometries\n${(points=>{let code=" let points = [\n";return points.forEach((point=>code+=` [${point}],\n`)),code+=" ]",code})(positions)}\n\n let geometries = [\n${(groups=>{let code="";return groups.forEach(((group,index)=>code+=` group${index}(points), // ${group.name}\n`)),code})(groups)} ]\n return geometries\n}\n\n${((groups,options)=>{let code="";return groups.forEach(((group,index)=>{const faces=group.faces,colors=group.colors;code+=`\n// group : ${group.name}\n// faces: ${faces.length}\n`,code+=`const group${index} = (points) => {\n${(faces=>{let code=" let faces = [\n";return faces.forEach((face=>code+=` [${face}],\n`)),code+=" ]",code})(faces)}\n${(colors=>{let code=" let colors = [\n";return colors.forEach((c=>{code+=c?` [${c}],\n`:" null,\n"})),code+=" ]",code})(colors)}\n return polyhedron({ orientation: '${options.orientation}', points, faces, colors })\n}\n`})),code})(groups,options)}\n`,code};exports.deserialize=(options,input)=>{const defaults={filename:"obj",output:"script",orientation:"outward",version:"3.0.0-alpha.0",addMetaData:!0};options=Object.assign({},defaults,options);const{output:output}=options;options&&options.statusCallback&&options.statusCallback({progress:0});const{positions:positions,groups:groups}=getGroups(input),result="script"===output?stringify(positions,groups,options):objectify(positions,groups,options);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},exports.mimeType="model/obj",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadObjDeserializer={}); + */Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),getGroups=(data,options)=>{let groups=[];const positions=[];let material=null;groups.push({faces:[],colors:[],name:"default",line:0});const handleG=(command,values)=>{const group={faces:[],colors:[],name:""};values&&values.length>0&&(group.name=values.join(" ")),groups.push(group)},handleV=(command,values)=>{const x=parseFloat(values[0]),y=parseFloat(values[1]),z=parseFloat(values[2]);positions.push([x,y,z])},handleF=(command,values)=>{const facerefs=values.map((value=>{const refs=value.match(/[0-9+\-eE]+/g);let ref=parseInt(refs[0]);return ref<0?ref=positions.length+ref:ref--,ref})),group=groups.pop();group.faces.push(facerefs),group.colors.push(material),groups.push(group)},handleMtl=(command,values)=>{if(material=null,values&&values.length>0){const c=(s=values[0],cssColors[s.toLowerCase()]);c&&(material=[c[0],c[1],c[2],1])}var s},lines=data.split(/\n/);for(let i=0;i0){let values=line.match(/\S+/g);if(values){const command=values[0];switch(values=values.slice(1),command){case"g":handleG(0,values);break;case"v":handleV(0,values);break;case"f":handleF(0,values);break;case"usemtl":handleMtl(0,values)}}}}return groups=groups.filter((group=>group.faces.length>0)),{positions:positions,groups:groups}},objectify=(points,groups,options)=>{const geometries=groups.map((group=>(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({orientation:options.orientation,points:points,faces:group.faces,colors:group.colors})));return geometries},stringify=(positions,groups,options)=>{const{filename:filename,addMetaData:addMetaData,version:version}=options;let code=addMetaData?`//\n// Produced by JSCAD IO Library : OBJ Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n `:"";return code+=`import * from '@jscad/modeling'\n\n// groups: ${groups.length}\n// points: ${positions.length}\nexport const main = () => {\n // points are common to all geometries\n${(points=>{let code=" let points = [\n";return points.forEach((point=>code+=` [${point}],\n`)),code+=" ]",code})(positions)}\n\n let geometries = [\n${(groups=>{let code="";return groups.forEach(((group,index)=>code+=` group${index}(points), // ${group.name}\n`)),code})(groups)} ]\n return geometries\n}\n\n${((groups,options)=>{let code="";return groups.forEach(((group,index)=>{const faces=group.faces,colors=group.colors;code+=`\n// group : ${group.name}\n// faces: ${faces.length}\n`,code+=`const group${index} = (points) => {\n${(faces=>{let code=" let faces = [\n";return faces.forEach((face=>code+=` [${face}],\n`)),code+=" ]",code})(faces)}\n${(colors=>{let code=" let colors = [\n";return colors.forEach((c=>{code+=c?` [${c}],\n`:" null,\n"})),code+=" ]",code})(colors)}\n return polyhedron({ orientation: '${options.orientation}', points, faces, colors })\n}\n`})),code})(groups,options)}\n`,code};exports.deserialize=(options,input)=>{const defaults={filename:"obj",output:"script",orientation:"outward",version:"3.0.1-alpha.0",addMetaData:!0};options=Object.assign({},defaults,options);const{output:output}=options;options&&options.statusCallback&&options.statusCallback({progress:0}),input=((stringOrArrayBuffer,defaultBinaryEncoding="utf-8")=>"string"==typeof stringOrArrayBuffer?stringOrArrayBuffer:new TextDecoder(defaultBinaryEncoding).decode(new Uint8Array(stringOrArrayBuffer)))(input);const{positions:positions,groups:groups}=getGroups(input),result="script"===output?stringify(positions,groups,options):objectify(positions,groups,options);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},exports.mimeType="model/obj",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadObjDeserializer={}); diff --git a/packages/io/obj-deserializer/package.json b/packages/io/obj-deserializer/package.json index 58c3e0f46..8fab09b57 100644 --- a/packages/io/obj-deserializer/package.json +++ b/packages/io/obj-deserializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/obj-deserializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "OBJ Deserializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -37,8 +37,8 @@ ], "license": "MIT", "dependencies": { - "@jscad/modeling": "workspace:3.0.0-alpha.0", - "@jscad/io-utils": "workspace:3.0.0-alpha.0" + "@jscad/io-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0" }, "devDependencies": { "@rollup/plugin-node-resolve": "^15.2.1", diff --git a/packages/io/obj-serializer/CHANGELOG.md b/packages/io/obj-serializer/CHANGELOG.md index 0a32c1c99..5fb0b720f 100644 --- a/packages/io/obj-serializer/CHANGELOG.md +++ b/packages/io/obj-serializer/CHANGELOG.md @@ -3,6 +3,17 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/obj-serializer@2.1.12...@jscad/obj-serializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) +* **regl-renderer:** added rollup configuration to create ES6 bundle, adjusted imports and exports ([#1259](https://github.com/jscad/OpenJSCAD.org/issues/1259)) ([47a66bc](https://github.com/jscad/OpenJSCAD.org/commit/47a66bc07a137a748ce8571ea5d043ebaab9418d)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/obj-serializer@2.1.12...@jscad/obj-serializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/obj-serializer/dist/jscad-obj-serializer.es.js b/packages/io/obj-serializer/dist/jscad-obj-serializer.es.js index 80900d959..d37217e04 100644 --- a/packages/io/obj-serializer/dist/jscad-obj-serializer.es.js +++ b/packages/io/obj-serializer/dist/jscad-obj-serializer.es.js @@ -1,13 +1,13 @@ /** * OBJ Serializer for JSCAD * @module @jscad/obj-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const cssColors={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]},flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),mimeType="model/obj",serialize=(options,...objects)=>{options=Object.assign({},{statusCallback:null,triangulate:!0},options);let objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to OBJ");var array;objects.length!==objects3d.length&&console.warn("some objects could not be serialized to OBJ"),array=((options,...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results})({snap:!0,triangulate:options.triangulate},objects3d),objects3d=Array.isArray(array)?array:null==array?[]:[array],options.statusCallback&&options.statusCallback({progress:0});let body="# Wavefront OBJ file generated by JSCAD\n";const vertices=[];let previousColor="default";return objects3d.forEach(((object,i)=>{options.statusCallback&&options.statusCallback({progress:100*i/objects3d.length}),body+="\n";const objectColor=getColorName(object),polygons=index$6.toPolygons(object).filter((p=>p.vertices.length>=3));polygons.forEach((polygon=>{polygon.vertices.forEach((vertex=>{const vertexString=convertVertex(vertex);vertices.indexOf(vertexString)<0&&(vertices.push(vertexString),body+=`${vertexString}\n`)}))})),body+="\n",polygons.forEach((polygon=>{const indices=polygon.vertices.map((v=>vertices.indexOf(convertVertex(v))+1)),color=getColorName(polygon)||objectColor||"default";color!==previousColor&&(body+=`usemtl ${color}\n`,previousColor=color),body+=`f ${indices.join(" ")}\n`}))})),options.statusCallback&&options.statusCallback({progress:100}),[body]},convertVertex=vertex=>`v ${vertex[0]} ${vertex[1]} ${vertex[2]}`,getColorName=object=>{let colorName;if(object.color){const r=object.color[0],g=object.color[1],b=object.color[2];let closest=765;for(const name in cssColors){const rgb=cssColors[name],diff=Math.abs(r-rgb[0])+Math.abs(g-rgb[1])+Math.abs(b-rgb[2]);if(diff{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),mimeType="model/obj",serialize=(options,...objects)=>{options=Object.assign({},{statusCallback:null,triangulate:!0},options);let objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to OBJ");var array;objects.length!==objects3d.length&&console.warn("some objects could not be serialized to OBJ"),array=generalize({snap:!0,triangulate:options.triangulate},objects3d),objects3d=Array.isArray(array)?array:null==array?[]:[array],options.statusCallback&&options.statusCallback({progress:0});let body="# Wavefront OBJ file generated by JSCAD\n";const vertices=[];let previousColor="default";return objects3d.forEach(((object,i)=>{options.statusCallback&&options.statusCallback({progress:100*i/objects3d.length}),body+="\n";const objectColor=getColorName(object),polygons=index$6.toPolygons(object).filter((p=>p.vertices.length>=3));polygons.forEach((polygon=>{polygon.vertices.forEach((vertex=>{const vertexString=convertVertex(vertex);vertices.indexOf(vertexString)<0&&(vertices.push(vertexString),body+=`${vertexString}\n`)}))})),body+="\n",polygons.forEach((polygon=>{const indices=polygon.vertices.map((v=>vertices.indexOf(convertVertex(v))+1)),color=getColorName(polygon)||objectColor||"default";color!==previousColor&&(body+=`usemtl ${color}\n`,previousColor=color),body+=`f ${indices.join(" ")}\n`}))})),options.statusCallback&&options.statusCallback({progress:100}),[body]},convertVertex=vertex=>`v ${vertex[0]} ${vertex[1]} ${vertex[2]}`,getColorName=object=>{let colorName;if(object.color){const r=object.color[0],g=object.color[1],b=object.color[2];let closest=765;for(const name in cssColors){const rgb=cssColors[name],diff=Math.abs(r-rgb[0])+Math.abs(g-rgb[1])+Math.abs(b-rgb[2]);if(diffarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),convertVertex=vertex=>`v ${vertex[0]} ${vertex[1]} ${vertex[2]}`,getColorName=object=>{let colorName;if(object.color){const r=object.color[0],g=object.color[1],b=object.color[2];let closest=765;for(const name in cssColors){const rgb=cssColors[name],diff=Math.abs(r-rgb[0])+Math.abs(g-rgb[1])+Math.abs(b-rgb[2]);if(diff{options=Object.assign({},{statusCallback:null,triangulate:!0},options);let objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to OBJ");var array;objects.length!==objects3d.length&&console.warn("some objects could not be serialized to OBJ"),array=((options,...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results})({snap:!0,triangulate:options.triangulate},objects3d),objects3d=Array.isArray(array)?array:null==array?[]:[array],options.statusCallback&&options.statusCallback({progress:0});let body="# Wavefront OBJ file generated by JSCAD\n";const vertices=[];let previousColor="default";return objects3d.forEach(((object,i)=>{options.statusCallback&&options.statusCallback({progress:100*i/objects3d.length}),body+="\n";const objectColor=getColorName(object),polygons=index$6.toPolygons(object).filter((p=>p.vertices.length>=3));polygons.forEach((polygon=>{polygon.vertices.forEach((vertex=>{const vertexString=convertVertex(vertex);vertices.indexOf(vertexString)<0&&(vertices.push(vertexString),body+=`${vertexString}\n`)}))})),body+="\n",polygons.forEach((polygon=>{const indices=polygon.vertices.map((v=>vertices.indexOf(convertVertex(v))+1)),color=getColorName(polygon)||objectColor||"default";color!==previousColor&&(body+=`usemtl ${color}\n`,previousColor=color),body+=`f ${indices.join(" ")}\n`}))})),options.statusCallback&&options.statusCallback({progress:100}),[body]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadObjSerializer={}); +const cssColors={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]},clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),convertVertex=vertex=>`v ${vertex[0]} ${vertex[1]} ${vertex[2]}`,getColorName=object=>{let colorName;if(object.color){const r=object.color[0],g=object.color[1],b=object.color[2];let closest=765;for(const name in cssColors){const rgb=cssColors[name],diff=Math.abs(r-rgb[0])+Math.abs(g-rgb[1])+Math.abs(b-rgb[2]);if(diff{options=Object.assign({},{statusCallback:null,triangulate:!0},options);let objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to OBJ");var array;objects.length!==objects3d.length&&console.warn("some objects could not be serialized to OBJ"),array=generalize({snap:!0,triangulate:options.triangulate},objects3d),objects3d=Array.isArray(array)?array:null==array?[]:[array],options.statusCallback&&options.statusCallback({progress:0});let body="# Wavefront OBJ file generated by JSCAD\n";const vertices=[];let previousColor="default";return objects3d.forEach(((object,i)=>{options.statusCallback&&options.statusCallback({progress:100*i/objects3d.length}),body+="\n";const objectColor=getColorName(object),polygons=index$6.toPolygons(object).filter((p=>p.vertices.length>=3));polygons.forEach((polygon=>{polygon.vertices.forEach((vertex=>{const vertexString=convertVertex(vertex);vertices.indexOf(vertexString)<0&&(vertices.push(vertexString),body+=`${vertexString}\n`)}))})),body+="\n",polygons.forEach((polygon=>{const indices=polygon.vertices.map((v=>vertices.indexOf(convertVertex(v))+1)),color=getColorName(polygon)||objectColor||"default";color!==previousColor&&(body+=`usemtl ${color}\n`,previousColor=color),body+=`f ${indices.join(" ")}\n`}))})),options.statusCallback&&options.statusCallback({progress:100}),[body]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadObjSerializer={}); diff --git a/packages/io/obj-serializer/package.json b/packages/io/obj-serializer/package.json index 07df30cf5..0133fbb4f 100644 --- a/packages/io/obj-serializer/package.json +++ b/packages/io/obj-serializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/obj-serializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "OBJ Serializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -36,8 +36,8 @@ "access": "public" }, "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0" + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0" }, "devDependencies": { "@rollup/plugin-node-resolve": "^15.0.1", diff --git a/packages/io/stl-deserializer/CHANGELOG.md b/packages/io/stl-deserializer/CHANGELOG.md index b539b7af3..d421cc0b2 100644 --- a/packages/io/stl-deserializer/CHANGELOG.md +++ b/packages/io/stl-deserializer/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/stl-deserializer@2.1.19...@jscad/stl-deserializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/stl-deserializer@2.1.19...@jscad/stl-deserializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/stl-deserializer/dist/jscad-stl-deserializer.es.js b/packages/io/stl-deserializer/dist/jscad-stl-deserializer.es.js index 45482a787..787d88d1f 100644 --- a/packages/io/stl-deserializer/dist/jscad-stl-deserializer.es.js +++ b/packages/io/stl-deserializer/dist/jscad-stl-deserializer.es.js @@ -1,13 +1,13 @@ /** * STL Deserializer for JSCAD * @module @jscad/stl-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n)));class BinaryReader{constructor(data){this._buffer=data,this._pos=0}readInt8(){return this._decodeInt(8,!0)}readUInt8(){return this._decodeInt(8,!1)}readInt16(){return this._decodeInt(16,!0)}readUInt16(){return this._decodeInt(16,!1)}readInt32(){return this._decodeInt(32,!0)}readUInt32(){return this._decodeInt(32,!1)}readFloat(){return this._decodeFloat(23,8)}readDouble(){return this._decodeFloat(52,11)}readChar(){return this.readString(1)}readString(length){this._checkSize(8*length);const result=this._buffer.substr(this._pos,length);return this._pos+=length,result}seek(pos){this._pos=pos,this._checkSize(0)}getPosition(){return this._pos}getSize(){return this._buffer.length}_decodeFloat(precisionBits,exponentBits){const length=precisionBits+exponentBits+1,size=length>>3;this._checkSize(length);const bias=Math.pow(2,exponentBits-1)-1,signal=this._readBits(precisionBits+exponentBits,1,size),exponent=this._readBits(precisionBits,exponentBits,size);let significand=0,divisor=2,curByte=0,startBit=0;do{const byteValue=this._readByte(++curByte,size);startBit=precisionBits%8||8;let mask=1<>=1;)byteValue&mask&&(significand+=1/divisor),divisor*=2}while(precisionBits-=startBit);return this._pos+=size,exponent===1+(bias<<1)?significand?NaN:signal?-1/0:1/0:(1+-2*signal)*(exponent||significand?exponent?Math.pow(2,exponent-bias)*(1+significand):Math.pow(2,1-bias)*significand:0)}_decodeInt(bits,signed){const x=this._readBits(0,bits,bits/8),max=Math.pow(2,bits),result=signed&&x>=max/2?x-max:x;return this._pos+=bits/8,result}_shl(a,b){for(++b;--b;a=1073741824==(1073741824&(a%=2147483648))?2*a:2*(a-1073741824)+2147483647+1);return a}_readByte(i,size){return 255&this._buffer.charCodeAt(this._pos+size-i-1)}_readBits(start,length,size){const offsetLeft=(start+length)%8,offsetRight=start%8,curByte=size-(start>>3)-1;let lastByte=size+(-(start+length)>>3),diff=curByte-lastByte,sum=this._readByte(curByte,size)>>offsetRight&(1<<(diff?8-offsetRight:length))-1;for(diff&&offsetLeft&&(sum+=(this._readByte(lastByte++,size)&(1<{const defaults={filename:"stl",version:"3.0.0-alpha.0",addMetaData:!0,output:"script"};(options=Object.assign({},defaults,options))&&options.statusCallback&&options.statusCallback({progress:0});const{filename:filename,version:version,output:output,addMetaData:addMetaData}=options;stl=isBuffer(stl)?bufferToBinaryString(stl):stl;const isBinary=isDataBinaryRobust(stl);options&&options.statusCallback&&options.statusCallback({progress:33});options&&options.statusCallback&&options.statusCallback({progress:66});const result=("script"===output?formatAsJscad:formatAsCsg)((isBinary?deserializeBinarySTL:deserializeAsciiSTL)(stl,filename,version,"script"===output?({vertices:vertices,triangles:triangles,normals:normals,colors:colors,index:index})=>toScript(vertices,triangles,null,colors,index):({vertices:vertices,triangles:triangles,normals:normals,colors:colors})=>toPolyhedron(vertices,triangles,null,colors)),addMetaData,version,filename);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},bufferToBinaryString=buffer=>{let binary="";const bytes=new Uint8Array(buffer),length=bytes.byteLength;for(let i=0;ivoid 0!==obj.byteLength&&"function"==typeof obj.slice,isDataBinaryRobust=data=>{const text=(buf=>{if("string"!=typeof buf){const arrayBuffer=new Uint8Array(buf);let str="";for(let i=0;i{let code="";return addMetaData&&(code=`\n //\n // producer: JSCAD STL Deserializer ${version}\n // date: ${new Date}\n // source: ${filename}\n // objects: ${data.length}\n //\n `),code+="import * from '@jscad/modeling'\n",code+=data.join("\n"),code+=`\nexport const main = () => {\n return [${data.map(((d,i)=>`solid${i+1}()`))}]\n}\n`,code},formatAsCsg=data=>data,deserializeBinarySTL=(stl,filename,version,elementFormatter)=>{const vertices=[],triangles=[],normals=[],colors=[];let vertexIndex=0,err=0,mcolor=null;const umask=parseInt("01000000000000000",2),rmask=parseInt("00000000000011111",2),gmask=parseInt("00000001111100000",2),bmask=parseInt("00111110000000000",2),br=new BinaryReader(stl);let m=0,c=0,r=0,g=0,b=0,a=0;for(let i=0;i<80;i++)switch(m){case 6:r=br.readUInt8(),m+=1;continue;case 7:g=br.readUInt8(),m+=1;continue;case 8:b=br.readUInt8(),m+=1;continue;case 9:a=br.readUInt8(),m+=1;continue;default:switch(c=br.readChar(),c){case"C":case"O":case"L":case"R":case"=":m+=1}}10===m&&(mcolor=[r/255,g/255,b/255,a/255]);const totalTriangles=br.readUInt32();for(let tr=0;tr0&&console.log("bad triangle vertice coords/normal: ",skip),err+=skip;const triangle=[];triangle.push(vertexIndex++),triangle.push(vertexIndex++),triangle.push(vertexIndex++);const abc=br.readUInt16();let color=null;if(10===m){color=0===(abc&umask)?[(abc&rmask)/31,((abc&gmask)>>>5)/31,((abc&bmask)>>>10)/31,255]:mcolor,colors.push(color)}if(0===skip){const e1=index$d.subtract(index$d.create(),v2,v1),e2=index$d.subtract(index$d.create(),v3,v1),cr=index$d.cross(index$d.create(),e1,e2);if(index$d.dot(no,cr)>0){const tmp=v3;v3=v1,v1=tmp}}vertices.push(v1),vertices.push(v2),vertices.push(v3),triangles.push(triangle),normals.push(no)}return err&&console.warn(`WARNING: import errors: ${err} (some triangles might be misaligned or missing)`),[elementFormatter({vertices:vertices,triangles:triangles,normals:normals,colors:colors,index:1})]},deserializeAsciiSTL=(stl,filename,version,elementFormatter)=>{let converted=0;const objects=stl.split("endsolid"),elements=[];for(let o=1;o0){const tmp=v3;v3=v1,v1=tmp}}vertices.push(v1),vertices.push(v2),vertices.push(v3),triangles.push(triangle),converted++}err&&console.warn(`WARNING: import errors: ${err} (some triangles might be misaligned or missing)`),elements.push(elementFormatter({vertices:vertices,triangles:triangles,colors:colors,index:o}))}}return elements},toPolyhedron=(points,faces,normals,colors)=>{colors&&faces.length!==colors.length&&(colors=void 0);return(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({orientation:"inward",points:points,faces:faces,colors:colors})},toScript=(points,faces,normals,colors,index)=>{let src=`\n//\n// solid ${index} : ${points.length} points, ${faces.length} faces, ${colors.length} colors\n//\nconst solid${index} = () => {\n`;src+=" const points = [\n";for(let i=0;i{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n)));class BinaryReader{constructor(data){this._buffer=data,this._pos=0}readInt8(){return this._decodeInt(8,!0)}readUInt8(){return this._decodeInt(8,!1)}readInt16(){return this._decodeInt(16,!0)}readUInt16(){return this._decodeInt(16,!1)}readInt32(){return this._decodeInt(32,!0)}readUInt32(){return this._decodeInt(32,!1)}readFloat(){return this._decodeFloat(23,8)}readDouble(){return this._decodeFloat(52,11)}readChar(){return this.readString(1)}readString(length){this._checkSize(8*length);const result=this._buffer.substr(this._pos,length);return this._pos+=length,result}seek(pos){this._pos=pos,this._checkSize(0)}getPosition(){return this._pos}getSize(){return this._buffer.length}_decodeFloat(precisionBits,exponentBits){const length=precisionBits+exponentBits+1,size=length>>3;this._checkSize(length);const bias=Math.pow(2,exponentBits-1)-1,signal=this._readBits(precisionBits+exponentBits,1,size),exponent=this._readBits(precisionBits,exponentBits,size);let significand=0,divisor=2,curByte=0,startBit=0;do{const byteValue=this._readByte(++curByte,size);startBit=precisionBits%8||8;let mask=1<>=1;)byteValue&mask&&(significand+=1/divisor),divisor*=2}while(precisionBits-=startBit);return this._pos+=size,exponent===1+(bias<<1)?significand?NaN:signal?-1/0:1/0:(1+-2*signal)*(exponent||significand?exponent?Math.pow(2,exponent-bias)*(1+significand):Math.pow(2,1-bias)*significand:0)}_decodeInt(bits,signed){const x=this._readBits(0,bits,bits/8),max=Math.pow(2,bits),result=signed&&x>=max/2?x-max:x;return this._pos+=bits/8,result}_shl(a,b){for(++b;--b;a=1073741824==(1073741824&(a%=2147483648))?2*a:2*(a-1073741824)+2147483647+1);return a}_readByte(i,size){return 255&this._buffer.charCodeAt(this._pos+size-i-1)}_readBits(start,length,size){const offsetLeft=(start+length)%8,offsetRight=start%8,curByte=size-(start>>3)-1;let lastByte=size+(-(start+length)>>3),diff=curByte-lastByte,sum=this._readByte(curByte,size)>>offsetRight&(1<<(diff?8-offsetRight:length))-1;for(diff&&offsetLeft&&(sum+=(this._readByte(lastByte++,size)&(1<{const defaults={filename:"stl",version:"3.0.1-alpha.0",addMetaData:!0,output:"script"};(options=Object.assign({},defaults,options))&&options.statusCallback&&options.statusCallback({progress:0});const{filename:filename,version:version,output:output,addMetaData:addMetaData}=options;stl=isBuffer(stl)?bufferToBinaryString(stl):stl;const isBinary=isDataBinaryRobust(stl);options&&options.statusCallback&&options.statusCallback({progress:33});options&&options.statusCallback&&options.statusCallback({progress:66});const result=("script"===output?formatAsJscad:formatAsCsg)((isBinary?deserializeBinarySTL:deserializeAsciiSTL)(stl,filename,version,"script"===output?({vertices:vertices,triangles:triangles,normals:normals,colors:colors,index:index})=>toScript(vertices,triangles,null,colors,index):({vertices:vertices,triangles:triangles,normals:normals,colors:colors})=>toPolyhedron(vertices,triangles,null,colors)),addMetaData,version,filename);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},bufferToBinaryString=buffer=>{let binary="";const bytes=new Uint8Array(buffer),length=bytes.byteLength;for(let i=0;ivoid 0!==obj.byteLength&&"function"==typeof obj.slice,isDataBinaryRobust=data=>{const text=(buf=>{if("string"!=typeof buf){const arrayBuffer=new Uint8Array(buf);let str="";for(let i=0;i{let code="";return addMetaData&&(code=`\n //\n // producer: JSCAD STL Deserializer ${version}\n // date: ${new Date}\n // source: ${filename}\n // objects: ${data.length}\n //\n `),code+="import * from '@jscad/modeling'\n",code+=data.join("\n"),code+=`\nexport const main = () => {\n return [${data.map(((d,i)=>`solid${i+1}()`))}]\n}\n`,code},formatAsCsg=data=>data,deserializeBinarySTL=(stl,filename,version,elementFormatter)=>{const vertices=[],triangles=[],normals=[],colors=[];let vertexIndex=0,err=0,mcolor=null;const umask=parseInt("01000000000000000",2),rmask=parseInt("00000000000011111",2),gmask=parseInt("00000001111100000",2),bmask=parseInt("00111110000000000",2),br=new BinaryReader(stl);let m=0,c=0,r=0,g=0,b=0,a=0;for(let i=0;i<80;i++)switch(m){case 6:r=br.readUInt8(),m+=1;continue;case 7:g=br.readUInt8(),m+=1;continue;case 8:b=br.readUInt8(),m+=1;continue;case 9:a=br.readUInt8(),m+=1;continue;default:switch(c=br.readChar(),c){case"C":case"O":case"L":case"R":case"=":m+=1}}10===m&&(mcolor=[r/255,g/255,b/255,a/255]);const totalTriangles=br.readUInt32();for(let tr=0;tr0&&console.log("bad triangle vertice coords/normal: ",skip),err+=skip;const triangle=[];triangle.push(vertexIndex++),triangle.push(vertexIndex++),triangle.push(vertexIndex++);const abc=br.readUInt16();let color=null;if(10===m){color=0===(abc&umask)?[(abc&rmask)/31,((abc&gmask)>>>5)/31,((abc&bmask)>>>10)/31,255]:mcolor,colors.push(color)}if(0===skip){const e1=index$d.subtract(index$d.create(),v2,v1),e2=index$d.subtract(index$d.create(),v3,v1),cr=index$d.cross(index$d.create(),e1,e2);if(index$d.dot(no,cr)>0){const tmp=v3;v3=v1,v1=tmp}}vertices.push(v1),vertices.push(v2),vertices.push(v3),triangles.push(triangle),normals.push(no)}return err&&console.warn(`WARNING: import errors: ${err} (some triangles might be misaligned or missing)`),[elementFormatter({vertices:vertices,triangles:triangles,normals:normals,colors:colors,index:1})]},deserializeAsciiSTL=(stl,filename,version,elementFormatter)=>{let converted=0;const objects=stl.split("endsolid"),elements=[];for(let o=1;o0){const tmp=v3;v3=v1,v1=tmp}}vertices.push(v1),vertices.push(v2),vertices.push(v3),triangles.push(triangle),converted++}err&&console.warn(`WARNING: import errors: ${err} (some triangles might be misaligned or missing)`),elements.push(elementFormatter({vertices:vertices,triangles:triangles,colors:colors,index:o}))}}return elements},toPolyhedron=(points,faces,normals,colors)=>{colors&&faces.length!==colors.length&&(colors=void 0);return(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({orientation:"inward",points:points,faces:faces,colors:colors})},toScript=(points,faces,normals,colors,index)=>{let src=`\n//\n// solid ${index} : ${points.length} points, ${faces.length} faces, ${colors.length} colors\n//\nconst solid${index} = () => {\n`;src+=" const points = [\n";for(let i=0;i{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n)));class BinaryReader{constructor(data){this._buffer=data,this._pos=0}readInt8(){return this._decodeInt(8,!0)}readUInt8(){return this._decodeInt(8,!1)}readInt16(){return this._decodeInt(16,!0)}readUInt16(){return this._decodeInt(16,!1)}readInt32(){return this._decodeInt(32,!0)}readUInt32(){return this._decodeInt(32,!1)}readFloat(){return this._decodeFloat(23,8)}readDouble(){return this._decodeFloat(52,11)}readChar(){return this.readString(1)}readString(length){this._checkSize(8*length);const result=this._buffer.substr(this._pos,length);return this._pos+=length,result}seek(pos){this._pos=pos,this._checkSize(0)}getPosition(){return this._pos}getSize(){return this._buffer.length}_decodeFloat(precisionBits,exponentBits){const length=precisionBits+exponentBits+1,size=length>>3;this._checkSize(length);const bias=Math.pow(2,exponentBits-1)-1,signal=this._readBits(precisionBits+exponentBits,1,size),exponent=this._readBits(precisionBits,exponentBits,size);let significand=0,divisor=2,curByte=0,startBit=0;do{const byteValue=this._readByte(++curByte,size);startBit=precisionBits%8||8;let mask=1<>=1;)byteValue&mask&&(significand+=1/divisor),divisor*=2}while(precisionBits-=startBit);return this._pos+=size,exponent===1+(bias<<1)?significand?NaN:signal?-1/0:1/0:(1+-2*signal)*(exponent||significand?exponent?Math.pow(2,exponent-bias)*(1+significand):Math.pow(2,1-bias)*significand:0)}_decodeInt(bits,signed){const x=this._readBits(0,bits,bits/8),max=Math.pow(2,bits),result=signed&&x>=max/2?x-max:x;return this._pos+=bits/8,result}_shl(a,b){for(++b;--b;a=1073741824==(1073741824&(a%=2147483648))?2*a:2*(a-1073741824)+2147483647+1);return a}_readByte(i,size){return 255&this._buffer.charCodeAt(this._pos+size-i-1)}_readBits(start,length,size){const offsetLeft=(start+length)%8,offsetRight=start%8,curByte=size-(start>>3)-1;let lastByte=size+(-(start+length)>>3),diff=curByte-lastByte,sum=this._readByte(curByte,size)>>offsetRight&(1<<(diff?8-offsetRight:length))-1;for(diff&&offsetLeft&&(sum+=(this._readByte(lastByte++,size)&(1<{let binary="";const bytes=new Uint8Array(buffer),length=bytes.byteLength;for(let i=0;ivoid 0!==obj.byteLength&&"function"==typeof obj.slice,isDataBinaryRobust=data=>{const text=(buf=>{if("string"!=typeof buf){const arrayBuffer=new Uint8Array(buf);let str="";for(let i=0;i{let code="";return addMetaData&&(code=`\n //\n // producer: JSCAD STL Deserializer ${version}\n // date: ${new Date}\n // source: ${filename}\n // objects: ${data.length}\n //\n `),code+="import * from '@jscad/modeling'\n",code+=data.join("\n"),code+=`\nexport const main = () => {\n return [${data.map(((d,i)=>`solid${i+1}()`))}]\n}\n`,code},formatAsCsg=data=>data,deserializeBinarySTL=(stl,filename,version,elementFormatter)=>{const vertices=[],triangles=[],normals=[],colors=[];let vertexIndex=0,err=0,mcolor=null;const umask=parseInt("01000000000000000",2),rmask=parseInt("00000000000011111",2),gmask=parseInt("00000001111100000",2),bmask=parseInt("00111110000000000",2),br=new BinaryReader(stl);let m=0,c=0,r=0,g=0,b=0,a=0;for(let i=0;i<80;i++)switch(m){case 6:r=br.readUInt8(),m+=1;continue;case 7:g=br.readUInt8(),m+=1;continue;case 8:b=br.readUInt8(),m+=1;continue;case 9:a=br.readUInt8(),m+=1;continue;default:switch(c=br.readChar(),c){case"C":case"O":case"L":case"R":case"=":m+=1}}10===m&&(mcolor=[r/255,g/255,b/255,a/255]);const totalTriangles=br.readUInt32();for(let tr=0;tr0&&console.log("bad triangle vertice coords/normal: ",skip),err+=skip;const triangle=[];triangle.push(vertexIndex++),triangle.push(vertexIndex++),triangle.push(vertexIndex++);const abc=br.readUInt16();let color=null;if(10===m&&(color=0==(abc&umask)?[(abc&rmask)/31,((abc&gmask)>>>5)/31,((abc&bmask)>>>10)/31,255]:mcolor,colors.push(color)),0===skip){const e1=index$d.subtract(index$d.create(),v2,v1),e2=index$d.subtract(index$d.create(),v3,v1),cr=index$d.cross(index$d.create(),e1,e2);if(index$d.dot(no,cr)>0){const tmp=v3;v3=v1,v1=tmp}}vertices.push(v1),vertices.push(v2),vertices.push(v3),triangles.push(triangle),normals.push(no)}return err&&console.warn(`WARNING: import errors: ${err} (some triangles might be misaligned or missing)`),[elementFormatter({vertices:vertices,triangles:triangles,normals:normals,colors:colors,index:1})]},deserializeAsciiSTL=(stl,filename,version,elementFormatter)=>{let converted=0;const objects=stl.split("endsolid"),elements=[];for(let o=1;o0){const tmp=v3;v3=v1,v1=tmp}}vertices.push(v1),vertices.push(v2),vertices.push(v3),triangles.push(triangle),converted++}err&&console.warn(`WARNING: import errors: ${err} (some triangles might be misaligned or missing)`),elements.push(elementFormatter({vertices:vertices,triangles:triangles,colors:colors,index:o}))}}return elements},toPolyhedron=(points,faces,normals,colors)=>(colors&&faces.length!==colors.length&&(colors=void 0),(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({orientation:"inward",points:points,faces:faces,colors:colors})),toScript=(points,faces,normals,colors,index)=>{let src=`\n//\n// solid ${index} : ${points.length} points, ${faces.length} faces, ${colors.length} colors\n//\nconst solid${index} = () => {\n`;src+=" const points = [\n";for(let i=0;i{const defaults={filename:"stl",version:"3.0.0-alpha.0",addMetaData:!0,output:"script"};(options=Object.assign({},defaults,options))&&options.statusCallback&&options.statusCallback({progress:0});const{filename:filename,version:version,output:output,addMetaData:addMetaData}=options;stl=isBuffer(stl)?bufferToBinaryString(stl):stl;const isBinary=isDataBinaryRobust(stl);options&&options.statusCallback&&options.statusCallback({progress:33}),options&&options.statusCallback&&options.statusCallback({progress:66});const result=("script"===output?formatAsJscad:formatAsCsg)((isBinary?deserializeBinarySTL:deserializeAsciiSTL)(stl,filename,version,"script"===output?({vertices:vertices,triangles:triangles,normals:normals,colors:colors,index:index})=>toScript(vertices,triangles,null,colors,index):({vertices:vertices,triangles:triangles,normals:normals,colors:colors})=>toPolyhedron(vertices,triangles,null,colors)),addMetaData,version,filename);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},exports.mimeType="model/stl",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadStlDeserializer={}); +const clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n)));class BinaryReader{constructor(data){this._buffer=data,this._pos=0}readInt8(){return this._decodeInt(8,!0)}readUInt8(){return this._decodeInt(8,!1)}readInt16(){return this._decodeInt(16,!0)}readUInt16(){return this._decodeInt(16,!1)}readInt32(){return this._decodeInt(32,!0)}readUInt32(){return this._decodeInt(32,!1)}readFloat(){return this._decodeFloat(23,8)}readDouble(){return this._decodeFloat(52,11)}readChar(){return this.readString(1)}readString(length){this._checkSize(8*length);const result=this._buffer.substr(this._pos,length);return this._pos+=length,result}seek(pos){this._pos=pos,this._checkSize(0)}getPosition(){return this._pos}getSize(){return this._buffer.length}_decodeFloat(precisionBits,exponentBits){const length=precisionBits+exponentBits+1,size=length>>3;this._checkSize(length);const bias=Math.pow(2,exponentBits-1)-1,signal=this._readBits(precisionBits+exponentBits,1,size),exponent=this._readBits(precisionBits,exponentBits,size);let significand=0,divisor=2,curByte=0,startBit=0;do{const byteValue=this._readByte(++curByte,size);startBit=precisionBits%8||8;let mask=1<>=1;)byteValue&mask&&(significand+=1/divisor),divisor*=2}while(precisionBits-=startBit);return this._pos+=size,exponent===1+(bias<<1)?significand?NaN:signal?-1/0:1/0:(1+-2*signal)*(exponent||significand?exponent?Math.pow(2,exponent-bias)*(1+significand):Math.pow(2,1-bias)*significand:0)}_decodeInt(bits,signed){const x=this._readBits(0,bits,bits/8),max=Math.pow(2,bits),result=signed&&x>=max/2?x-max:x;return this._pos+=bits/8,result}_shl(a,b){for(++b;--b;a=1073741824==(1073741824&(a%=2147483648))?2*a:2*(a-1073741824)+2147483647+1);return a}_readByte(i,size){return 255&this._buffer.charCodeAt(this._pos+size-i-1)}_readBits(start,length,size){const offsetLeft=(start+length)%8,offsetRight=start%8,curByte=size-(start>>3)-1;let lastByte=size+(-(start+length)>>3),diff=curByte-lastByte,sum=this._readByte(curByte,size)>>offsetRight&(1<<(diff?8-offsetRight:length))-1;for(diff&&offsetLeft&&(sum+=(this._readByte(lastByte++,size)&(1<{let binary="";const bytes=new Uint8Array(buffer),length=bytes.byteLength;for(let i=0;ivoid 0!==obj.byteLength&&"function"==typeof obj.slice,isDataBinaryRobust=data=>{const text=(buf=>{if("string"!=typeof buf){const arrayBuffer=new Uint8Array(buf);let str="";for(let i=0;i{let code="";return addMetaData&&(code=`\n //\n // producer: JSCAD STL Deserializer ${version}\n // date: ${new Date}\n // source: ${filename}\n // objects: ${data.length}\n //\n `),code+="import * from '@jscad/modeling'\n",code+=data.join("\n"),code+=`\nexport const main = () => {\n return [${data.map(((d,i)=>`solid${i+1}()`))}]\n}\n`,code},formatAsCsg=data=>data,deserializeBinarySTL=(stl,filename,version,elementFormatter)=>{const vertices=[],triangles=[],normals=[],colors=[];let vertexIndex=0,err=0,mcolor=null;const umask=parseInt("01000000000000000",2),rmask=parseInt("00000000000011111",2),gmask=parseInt("00000001111100000",2),bmask=parseInt("00111110000000000",2),br=new BinaryReader(stl);let m=0,c=0,r=0,g=0,b=0,a=0;for(let i=0;i<80;i++)switch(m){case 6:r=br.readUInt8(),m+=1;continue;case 7:g=br.readUInt8(),m+=1;continue;case 8:b=br.readUInt8(),m+=1;continue;case 9:a=br.readUInt8(),m+=1;continue;default:switch(c=br.readChar(),c){case"C":case"O":case"L":case"R":case"=":m+=1}}10===m&&(mcolor=[r/255,g/255,b/255,a/255]);const totalTriangles=br.readUInt32();for(let tr=0;tr0&&console.log("bad triangle vertice coords/normal: ",skip),err+=skip;const triangle=[];triangle.push(vertexIndex++),triangle.push(vertexIndex++),triangle.push(vertexIndex++);const abc=br.readUInt16();let color=null;if(10===m&&(color=0==(abc&umask)?[(abc&rmask)/31,((abc&gmask)>>>5)/31,((abc&bmask)>>>10)/31,255]:mcolor,colors.push(color)),0===skip){const e1=index$d.subtract(index$d.create(),v2,v1),e2=index$d.subtract(index$d.create(),v3,v1),cr=index$d.cross(index$d.create(),e1,e2);if(index$d.dot(no,cr)>0){const tmp=v3;v3=v1,v1=tmp}}vertices.push(v1),vertices.push(v2),vertices.push(v3),triangles.push(triangle),normals.push(no)}return err&&console.warn(`WARNING: import errors: ${err} (some triangles might be misaligned or missing)`),[elementFormatter({vertices:vertices,triangles:triangles,normals:normals,colors:colors,index:1})]},deserializeAsciiSTL=(stl,filename,version,elementFormatter)=>{let converted=0;const objects=stl.split("endsolid"),elements=[];for(let o=1;o0){const tmp=v3;v3=v1,v1=tmp}}vertices.push(v1),vertices.push(v2),vertices.push(v3),triangles.push(triangle),converted++}err&&console.warn(`WARNING: import errors: ${err} (some triangles might be misaligned or missing)`),elements.push(elementFormatter({vertices:vertices,triangles:triangles,colors:colors,index:o}))}}return elements},toPolyhedron=(points,faces,normals,colors)=>(colors&&faces.length!==colors.length&&(colors=void 0),(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})({orientation:"inward",points:points,faces:faces,colors:colors})),toScript=(points,faces,normals,colors,index)=>{let src=`\n//\n// solid ${index} : ${points.length} points, ${faces.length} faces, ${colors.length} colors\n//\nconst solid${index} = () => {\n`;src+=" const points = [\n";for(let i=0;i{const defaults={filename:"stl",version:"3.0.1-alpha.0",addMetaData:!0,output:"script"};(options=Object.assign({},defaults,options))&&options.statusCallback&&options.statusCallback({progress:0});const{filename:filename,version:version,output:output,addMetaData:addMetaData}=options;stl=isBuffer(stl)?bufferToBinaryString(stl):stl;const isBinary=isDataBinaryRobust(stl);options&&options.statusCallback&&options.statusCallback({progress:33}),options&&options.statusCallback&&options.statusCallback({progress:66});const result=("script"===output?formatAsJscad:formatAsCsg)((isBinary?deserializeBinarySTL:deserializeAsciiSTL)(stl,filename,version,"script"===output?({vertices:vertices,triangles:triangles,normals:normals,colors:colors,index:index})=>toScript(vertices,triangles,null,colors,index):({vertices:vertices,triangles:triangles,normals:normals,colors:colors})=>toPolyhedron(vertices,triangles,null,colors)),addMetaData,version,filename);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},exports.mimeType="model/stl",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadStlDeserializer={}); diff --git a/packages/io/stl-deserializer/package.json b/packages/io/stl-deserializer/package.json index 38f4fb2c4..3aec59422 100644 --- a/packages/io/stl-deserializer/package.json +++ b/packages/io/stl-deserializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/stl-deserializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "STL Deserializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -37,8 +37,8 @@ ], "license": "MIT", "dependencies": { - "@jscad/io-utils": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0" + "@jscad/io-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0" }, "devDependencies": { "@rollup/plugin-node-resolve": "^15.2.1", diff --git a/packages/io/stl-serializer/CHANGELOG.md b/packages/io/stl-serializer/CHANGELOG.md index f598f33ed..4a7d0441f 100644 --- a/packages/io/stl-serializer/CHANGELOG.md +++ b/packages/io/stl-serializer/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/stl-serializer@2.1.12...@jscad/stl-serializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/stl-serializer@2.1.12...@jscad/stl-serializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/stl-serializer/dist/jscad-stl-serializer.es.js b/packages/io/stl-serializer/dist/jscad-stl-serializer.es.js index 2cea8b22c..114448e3f 100644 --- a/packages/io/stl-serializer/dist/jscad-stl-serializer.es.js +++ b/packages/io/stl-serializer/dist/jscad-stl-serializer.es.js @@ -1,13 +1,13 @@ /** * STL Serializer for JSCAD * @module @jscad/stl-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),convertToStl=(objects,options)=>{const result=[];return objects.forEach(((object,i)=>{result.push(convertToFacets(object)),options.statusCallback&&options.statusCallback({progress:100*i/objects.length})})),result.join("\n")},convertToFacets=(object,options)=>{const result=[];return index$6.toPolygons(object).forEach(((polygon,i)=>{result.push(convertToFacet(polygon))})),result.join("\n")},vector3DtoStlString=v=>`${v[0]} ${v[1]} ${v[2]}`,vertextoStlString=vertex=>`vertex ${vector3DtoStlString(vertex)}`,convertToFacet=polygon=>{const result=[];if(polygon.vertices.length>=3){const firstVertexStl=vertextoStlString(polygon.vertices[0]);for(let i=0;i{options=Object.assign({},{binary:!0,statusCallback:null},options);let objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to STL");var array;return objects.length!==objects3d.length&&console.warn("some objects could not be serialized to STL"),array=((options,...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results})({snap:!0,triangulate:!0},objects3d),objects3d=Array.isArray(array)?array:null==array?[]:[array],options.binary?((objects,options)=>{options.statusCallback&&options.statusCallback({progress:0});const buffer=new ArrayBuffer(4),int32buffer=new Int32Array(buffer,0,1),int8buffer=new Int8Array(buffer,0,4);if(int32buffer[0]=287454020,68!==int8buffer[0])throw new Error("Binary STL output is currently only supported on little-endian (Intel) processors");let numtriangles=0,numpolygons=0;objects.forEach(((object,i)=>{index$6.toPolygons(object).forEach((polygon=>{const numvertices=polygon.vertices.length;numtriangles+=numvertices>=3?numvertices-2:0,numpolygons+=1}))}));const headerarray=new Uint8Array(80);for(let i=0;i<80;i++)headerarray[i]=65;const ar1=new Uint32Array(1);ar1[0]=numtriangles;const allTrianglesBuffer=new ArrayBuffer(50*numtriangles),allTrianglesBufferAsInt8=new Int8Array(allTrianglesBuffer),triangleBuffer=new ArrayBuffer(50),triangleBufferAsInt8=new Int8Array(triangleBuffer),triangleFloat32array=new Float32Array(triangleBuffer,0,12),triangleUint16array=new Uint16Array(triangleBuffer,48,1);let byteoffset=0;return objects.forEach((object=>{index$6.toPolygons(object).forEach(((polygon,index)=>{const vertices=polygon.vertices,numvertices=vertices.length,plane=index$7.plane(polygon);for(let i=0;i0?i:0)];triangleFloat32array[arindex++]=vertex[0],triangleFloat32array[arindex++]=vertex[1],triangleFloat32array[arindex++]=vertex[2]}triangleUint16array[0]=0,allTrianglesBufferAsInt8.set(triangleBufferAsInt8,byteoffset),byteoffset+=50}options.statusCallback&&options.statusCallback({progress:100*index/numpolygons})}))})),options.statusCallback&&options.statusCallback({progress:100}),[headerarray.buffer,ar1.buffer,allTrianglesBuffer]})(objects3d,options):((objects,options)=>{options.statusCallback&&options.statusCallback({progress:0});const result=`solid JSCAD\n${convertToStl(objects,options)}\nendsolid JSCAD\n`;return options.statusCallback&&options.statusCallback({progress:100}),[result]})(objects3d,options)};export{mimeType,serialize}; +const clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),convertToStl=(objects,options)=>{const result=[];return objects.forEach(((object,i)=>{result.push(convertToFacets(object)),options.statusCallback&&options.statusCallback({progress:100*i/objects.length})})),result.join("\n")},convertToFacets=(object,options)=>{const result=[];return index$6.toPolygons(object).forEach(((polygon,i)=>{result.push(convertToFacet(polygon))})),result.join("\n")},vector3DtoStlString=v=>`${v[0]} ${v[1]} ${v[2]}`,vertextoStlString=vertex=>`vertex ${vector3DtoStlString(vertex)}`,convertToFacet=polygon=>{const result=[];if(polygon.vertices.length>=3){const firstVertexStl=vertextoStlString(polygon.vertices[0]);for(let i=0;i{options=Object.assign({},{binary:!0,statusCallback:null},options);let objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to STL");var array;return objects.length!==objects3d.length&&console.warn("some objects could not be serialized to STL"),array=generalize({snap:!0,triangulate:!0},objects3d),objects3d=Array.isArray(array)?array:null==array?[]:[array],options.binary?((objects,options)=>{options.statusCallback&&options.statusCallback({progress:0});const buffer=new ArrayBuffer(4),int32buffer=new Int32Array(buffer,0,1),int8buffer=new Int8Array(buffer,0,4);if(int32buffer[0]=287454020,68!==int8buffer[0])throw new Error("Binary STL output is currently only supported on little-endian (Intel) processors");let numtriangles=0,numpolygons=0;objects.forEach(((object,i)=>{index$6.toPolygons(object).forEach((polygon=>{const numvertices=polygon.vertices.length;numtriangles+=numvertices>=3?numvertices-2:0,numpolygons+=1}))}));const headerarray=new Uint8Array(80);for(let i=0;i<80;i++)headerarray[i]=65;const ar1=new Uint32Array(1);ar1[0]=numtriangles;const allTrianglesBuffer=new ArrayBuffer(50*numtriangles),allTrianglesBufferAsInt8=new Int8Array(allTrianglesBuffer),triangleBuffer=new ArrayBuffer(50),triangleBufferAsInt8=new Int8Array(triangleBuffer),triangleFloat32array=new Float32Array(triangleBuffer,0,12),triangleUint16array=new Uint16Array(triangleBuffer,48,1);let byteoffset=0;return objects.forEach((object=>{index$6.toPolygons(object).forEach(((polygon,index)=>{const vertices=polygon.vertices,numvertices=vertices.length,plane=index$7.plane(polygon);for(let i=0;i0?i:0)];triangleFloat32array[arindex++]=vertex[0],triangleFloat32array[arindex++]=vertex[1],triangleFloat32array[arindex++]=vertex[2]}triangleUint16array[0]=0,allTrianglesBufferAsInt8.set(triangleBufferAsInt8,byteoffset),byteoffset+=50}options.statusCallback&&options.statusCallback({progress:100*index/numpolygons})}))})),options.statusCallback&&options.statusCallback({progress:100}),[headerarray.buffer,ar1.buffer,allTrianglesBuffer]})(objects3d,options):((objects,options)=>{options.statusCallback&&options.statusCallback({progress:0});const result=`solid JSCAD\n${convertToStl(objects,options)}\nendsolid JSCAD\n`;return options.statusCallback&&options.statusCallback({progress:100}),[result]})(objects3d,options)};export{mimeType,serialize}; diff --git a/packages/io/stl-serializer/dist/jscad-stl-serializer.min.js b/packages/io/stl-serializer/dist/jscad-stl-serializer.min.js index 8a9e4ede2..bf654f29f 100644 --- a/packages/io/stl-serializer/dist/jscad-stl-serializer.min.js +++ b/packages/io/stl-serializer/dist/jscad-stl-serializer.min.js @@ -1,14 +1,14 @@ /** * STL Serializer for JSCAD * @module @jscad/stl-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ var global,factory;global=this,factory=function(exports){ /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),convertToStl=(objects,options)=>{const result=[];return objects.forEach(((object,i)=>{result.push(convertToFacets(object)),options.statusCallback&&options.statusCallback({progress:100*i/objects.length})})),result.join("\n")},convertToFacets=(object,options)=>{const result=[];return index$6.toPolygons(object).forEach(((polygon,i)=>{result.push(convertToFacet(polygon))})),result.join("\n")},vector3DtoStlString=v=>`${v[0]} ${v[1]} ${v[2]}`,vertextoStlString=vertex=>`vertex ${vector3DtoStlString(vertex)}`,convertToFacet=polygon=>{const result=[];if(polygon.vertices.length>=3){const firstVertexStl=vertextoStlString(polygon.vertices[0]);for(let i=0;i{options=Object.assign({},{binary:!0,statusCallback:null},options);let objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to STL");var array;return objects.length!==objects3d.length&&console.warn("some objects could not be serialized to STL"),array=((options,...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results})({snap:!0,triangulate:!0},objects3d),objects3d=Array.isArray(array)?array:null==array?[]:[array],options.binary?((objects,options)=>{options.statusCallback&&options.statusCallback({progress:0});const buffer=new ArrayBuffer(4),int32buffer=new Int32Array(buffer,0,1),int8buffer=new Int8Array(buffer,0,4);if(int32buffer[0]=287454020,68!==int8buffer[0])throw new Error("Binary STL output is currently only supported on little-endian (Intel) processors");let numtriangles=0,numpolygons=0;objects.forEach(((object,i)=>{index$6.toPolygons(object).forEach((polygon=>{const numvertices=polygon.vertices.length;numtriangles+=numvertices>=3?numvertices-2:0,numpolygons+=1}))}));const headerarray=new Uint8Array(80);for(let i=0;i<80;i++)headerarray[i]=65;const ar1=new Uint32Array(1);ar1[0]=numtriangles;const allTrianglesBuffer=new ArrayBuffer(50*numtriangles),allTrianglesBufferAsInt8=new Int8Array(allTrianglesBuffer),triangleBuffer=new ArrayBuffer(50),triangleBufferAsInt8=new Int8Array(triangleBuffer),triangleFloat32array=new Float32Array(triangleBuffer,0,12),triangleUint16array=new Uint16Array(triangleBuffer,48,1);let byteoffset=0;return objects.forEach((object=>{index$6.toPolygons(object).forEach(((polygon,index)=>{const vertices=polygon.vertices,numvertices=vertices.length,plane=index$7.plane(polygon);for(let i=0;i0?i:0)];triangleFloat32array[arindex++]=vertex[0],triangleFloat32array[arindex++]=vertex[1],triangleFloat32array[arindex++]=vertex[2]}triangleUint16array[0]=0,allTrianglesBufferAsInt8.set(triangleBufferAsInt8,byteoffset),byteoffset+=50}options.statusCallback&&options.statusCallback({progress:100*index/numpolygons})}))})),options.statusCallback&&options.statusCallback({progress:100}),[headerarray.buffer,ar1.buffer,allTrianglesBuffer]})(objects3d,options):((objects,options)=>{options.statusCallback&&options.statusCallback({progress:0});const result=`solid JSCAD\n${convertToStl(objects,options)}\nendsolid JSCAD\n`;return options.statusCallback&&options.statusCallback({progress:100}),[result]})(objects3d,options)},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadStlSerializer={}); +const clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),convertToStl=(objects,options)=>{const result=[];return objects.forEach(((object,i)=>{result.push(convertToFacets(object)),options.statusCallback&&options.statusCallback({progress:100*i/objects.length})})),result.join("\n")},convertToFacets=(object,options)=>{const result=[];return index$6.toPolygons(object).forEach(((polygon,i)=>{result.push(convertToFacet(polygon))})),result.join("\n")},vector3DtoStlString=v=>`${v[0]} ${v[1]} ${v[2]}`,vertextoStlString=vertex=>`vertex ${vector3DtoStlString(vertex)}`,convertToFacet=polygon=>{const result=[];if(polygon.vertices.length>=3){const firstVertexStl=vertextoStlString(polygon.vertices[0]);for(let i=0;i{options=Object.assign({},{binary:!0,statusCallback:null},options);let objects3d=(objects=flatten(objects)).filter((object=>index$6.isA(object)));if(0===objects3d.length)throw new Error("only 3D geometries can be serialized to STL");var array;return objects.length!==objects3d.length&&console.warn("some objects could not be serialized to STL"),array=generalize({snap:!0,triangulate:!0},objects3d),objects3d=Array.isArray(array)?array:null==array?[]:[array],options.binary?((objects,options)=>{options.statusCallback&&options.statusCallback({progress:0});const buffer=new ArrayBuffer(4),int32buffer=new Int32Array(buffer,0,1),int8buffer=new Int8Array(buffer,0,4);if(int32buffer[0]=287454020,68!==int8buffer[0])throw new Error("Binary STL output is currently only supported on little-endian (Intel) processors");let numtriangles=0,numpolygons=0;objects.forEach(((object,i)=>{index$6.toPolygons(object).forEach((polygon=>{const numvertices=polygon.vertices.length;numtriangles+=numvertices>=3?numvertices-2:0,numpolygons+=1}))}));const headerarray=new Uint8Array(80);for(let i=0;i<80;i++)headerarray[i]=65;const ar1=new Uint32Array(1);ar1[0]=numtriangles;const allTrianglesBuffer=new ArrayBuffer(50*numtriangles),allTrianglesBufferAsInt8=new Int8Array(allTrianglesBuffer),triangleBuffer=new ArrayBuffer(50),triangleBufferAsInt8=new Int8Array(triangleBuffer),triangleFloat32array=new Float32Array(triangleBuffer,0,12),triangleUint16array=new Uint16Array(triangleBuffer,48,1);let byteoffset=0;return objects.forEach((object=>{index$6.toPolygons(object).forEach(((polygon,index)=>{const vertices=polygon.vertices,numvertices=vertices.length,plane=index$7.plane(polygon);for(let i=0;i0?i:0)];triangleFloat32array[arindex++]=vertex[0],triangleFloat32array[arindex++]=vertex[1],triangleFloat32array[arindex++]=vertex[2]}triangleUint16array[0]=0,allTrianglesBufferAsInt8.set(triangleBufferAsInt8,byteoffset),byteoffset+=50}options.statusCallback&&options.statusCallback({progress:100*index/numpolygons})}))})),options.statusCallback&&options.statusCallback({progress:100}),[headerarray.buffer,ar1.buffer,allTrianglesBuffer]})(objects3d,options):((objects,options)=>{options.statusCallback&&options.statusCallback({progress:0});const result=`solid JSCAD\n${convertToStl(objects,options)}\nendsolid JSCAD\n`;return options.statusCallback&&options.statusCallback({progress:100}),[result]})(objects3d,options)},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadStlSerializer={}); diff --git a/packages/io/stl-serializer/package.json b/packages/io/stl-serializer/package.json index dc33dab8e..d5a81222d 100644 --- a/packages/io/stl-serializer/package.json +++ b/packages/io/stl-serializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/stl-serializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "STL Serializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -37,8 +37,8 @@ ], "license": "MIT", "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0" + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0" }, "devDependencies": { "@rollup/plugin-node-resolve": "^15.0.1", diff --git a/packages/io/svg-deserializer/CHANGELOG.md b/packages/io/svg-deserializer/CHANGELOG.md index 83b4370d3..924638995 100644 --- a/packages/io/svg-deserializer/CHANGELOG.md +++ b/packages/io/svg-deserializer/CHANGELOG.md @@ -3,6 +3,17 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/svg-deserializer@2.5.3...@jscad/svg-deserializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) +* **regl-renderer:** added rollup configuration to create ES6 bundle, adjusted imports and exports ([#1259](https://github.com/jscad/OpenJSCAD.org/issues/1259)) ([47a66bc](https://github.com/jscad/OpenJSCAD.org/commit/47a66bc07a137a748ce8571ea5d043ebaab9418d)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/svg-deserializer@2.5.3...@jscad/svg-deserializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/svg-deserializer/dist/jscad-svg-deserializer.es.js b/packages/io/svg-deserializer/dist/jscad-svg-deserializer.es.js index f9458d059..fbb1c93ae 100644 --- a/packages/io/svg-deserializer/dist/jscad-svg-deserializer.es.js +++ b/packages/io/svg-deserializer/dist/jscad-svg-deserializer.es.js @@ -1,7 +1,7 @@ /** * SVG Deserializer for JSCAD * @module @jscad/svg-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ var saxes={},ed5$1={};!function(exports){ @@ -32,7 +32,7 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.NC_NAME_START_CHA /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),clone$b=geometry=>Object.assign({},geometry),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation=(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply$1=(out,a,b)=>{const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:fromScaling,fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:mirrorByPlane,multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromNormalAndPoint=(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:fromNormalAndPoint,fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints$1=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints$1(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints$1,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");if(3===color.length&&(color=[color[0],color[1],color[2],1]),0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):(object.color=color,object)));return 1===results.length?results[0]:results},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},rectangle=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])},mirror=(options,...objects)=>{const{origin:origin,normal:normal}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},options);if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const planeOfMirror=fromNormalAndPoint([0,0,0,0],normal,origin);if(Number.isNaN(planeOfMirror[0]))throw new Error("the given origin and normal do not define a proper plane");const matrix=mirrorByPlane([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],planeOfMirror),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},mirrorX=(...objects)=>mirror({normal:[1,0,0]},objects),mirrorY=(...objects)=>mirror({normal:[0,1,0]},objects),rotateZ=(angle,...objects)=>((angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results})([0,0,angle],objects),translate=(offset,...objects)=>{if(!Array.isArray(offset))throw new Error("offset must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(offset=offset.slice();offset.length<3;)offset.push(0);const matrix=fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offset),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},scale=(factors,...objects)=>{if(!Array.isArray(factors))throw new Error("factors must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(factors=factors.slice();factors.length<3;)factors.push(1);if(factors[0]<=0||factors[1]<=0||factors[2]<=0)throw new Error("factors must be positive");const matrix=fromScaling([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],factors),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},pxPmm=1/.2822222,svgColors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},svg2cag=(vec,svgUnitsPmm)=>[vec[0]/svgUnitsPmm[0],0-vec[1]/svgUnitsPmm[1]],cagLengthX=(css,svgUnitsPmm,svgUnitsX)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[0]);let v=parseFloat(css);return isNaN(v)?0:0===v?v:(v=v/100*svgUnitsX,v/=svgUnitsPmm[0],Math.round(1e5*v)/1e5)},cagLengthY=(css,svgUnitsPmm,svgUnitsY)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[1]);let v=parseFloat(css);return isNaN(v)?0:0===v?v:(v=v/100*svgUnitsY,v/=svgUnitsPmm[1],Math.round(1e5*v)/1e5)},cagLengthP=(css,svgUnitsPmm,svgUnitsV)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[1]);let v=parseFloat(css);return isNaN(v)?0:(0===v||(v=v/100*svgUnitsV,v/=svgUnitsPmm[0]),v)},css2cag=(css,unit)=>{let v=parseFloat(css);return isNaN(v)?0:(0===v||css.search(/EM/i)>0||css.search(/EX/i)>0||css.search(/MM/i)>0||(css.search(/CM/i)>0?v*=10:css.search(/IN/i)>0?v/=.03937:css.search(/PT/i)>0?v/=2.8346400000000003:css.search(/PC/i)>0?v/=.23622:v/=unit),v)},cagColor=value=>{let rgb;if((value=value.toLowerCase())in svgColors)rgb=svgColors[value],rgb=[rgb[0]/255,rgb[1]/255,rgb[2]/255];else if("#"===value[0])4===value.length&&(value="#"+value[1]+value[1]+value[2]+value[2]+value[3]+value[3]),7===value.length&&(rgb=[parseInt("0x"+value.slice(1,3))/255,parseInt("0x"+value.slice(3,5))/255,parseInt("0x"+value.slice(5,7))/255]);else{let s=/rgb\(.+,.+,.+\)/.exec(value);null!==s&&(s=s[0],s=s.slice(s.indexOf("(")+1,s.indexOf(")")),rgb=s.split(","),s.indexOf("%")>0?(rgb=[parseInt(rgb[0]),parseInt(rgb[1]),parseInt(rgb[2])],rgb=[rgb[0]/100,rgb[1]/100,rgb[2]/100]):(rgb=[parseInt(rgb[0]),parseInt(rgb[1]),parseInt(rgb[2])],rgb=[rgb[0]/255,rgb[1]/255,rgb[2]/255]))}return rgb},cssStyle=(element,name)=>{if("style"in element){const list=element.style+";";let v=new RegExp(name+"\\s*:\\s*(\\S+);","i").exec(list);if(null!==v){v=v[0];let i=v.indexOf(":")+1;for(;" "===v[i];)i++;return v=v.slice(i,v.indexOf(";")),v}}},reflect=(x,y,px,py)=>{const ox=x-px,oy=y-py;return x===px&&y===px?[x,y]:x===px?[x,py+-oy]:y===py?[px+-ox,y]:[px+-ox,py+-oy]},svgColorForTarget=(target,svgObject)=>{let color=null;return"path"===target?svgObject.stroke?color=[svgObject.stroke[0],svgObject.stroke[1],svgObject.stroke[2],1]:svgObject.fill&&(color=[svgObject.fill[0],svgObject.fill[1],svgObject.fill[2],1]):svgObject.fill?color=[svgObject.fill[0],svgObject.fill[1],svgObject.fill[2],1]:svgObject.stroke&&(color=[svgObject.stroke[0],svgObject.stroke[1],svgObject.stroke[2],1]),color},svgCore=(obj,element)=>{"id"in element&&(obj.id=element.id),"position"in element&&(obj.position=element.position)},svgPresentation=(obj,element)=>{if("display"in element&&(obj.visible=element.display),"color"in element&&(obj.fill=cagColor(element.color),obj.stroke=obj.fill),"opacity"in element&&(obj.opacity=element.opacity),"fill"in element)obj.fill=cagColor(element.fill);else{const s=cssStyle(element,"fill");s&&(obj.fill=cagColor(s))}if("fill-opacity"in element&&(obj.opacity=element["fill-opacity"]),"stroke-width"in element)obj.strokeWidth=element["stroke-width"];else{const sw=cssStyle(element,"stroke-width");sw&&(obj.strokeWidth=sw)}if("stroke"in element)obj.stroke=cagColor(element.stroke);else{const s=cssStyle(element,"stroke");s&&(obj.stroke=cagColor(s))}"stroke-opacity"in element&&(obj.strokeOpacity=element["stroke-opacity"])},svgTransformsRegExp=/\w+\(.+\)/i,svgTransforms=(cag,element)=>{let list=null;if("transform"in element)list=element.transform;else{const s=cssStyle(element,"transform");s&&(list=s)}if(null!==list){cag.transforms=[];let v=svgTransformsRegExp.exec(list);for(;null!==v;){const s=svgTransformsRegExp.lastIndex,e=list.indexOf(")")+1;let t=list.slice(s,e);t=t.trim();const n=t.slice(0,t.indexOf("("));let o,a=t.slice(t.indexOf("(")+1,t.indexOf(")")).trim();switch(a=a.indexOf(",")>0?a.split(","):a.split(" "),n){case"translate":1===a.length&&a.push(0),o={translate:[a[0],a[1]]},cag.transforms.push(o);break;case"scale":1===a.length&&a.push(a[0]),o={scale:[a[0],a[1]]},cag.transforms.push(o);break;case"rotate":o={rotate:a},cag.transforms.push(o)}list=list.slice(e,list.length),v=svgTransformsRegExp.exec(list)}}},viewBoxRegExp=/([\d.-]+)[\s,]+([\d.-]+)[\s,]+([\d.-]+)[\s,]+([\d.-]+)/i,svgSvg=(element,{customPxPmm:customPxPmm})=>{const obj={type:"svg",x:0,y:0,width:"100%",height:"100%",strokeWidth:"1"};if(obj.unitsPmm=[pxPmm,pxPmm],"pxpmm"in element&&(obj.pxPmm=element.pxpmm,obj.unitsPmm=[obj.pxPmm,obj.pxPmm]),"width"in element&&(obj.width=element.width),"height"in element&&(obj.height=element.height),"viewBox"in element){const list=element.viewBox.trim(),v=viewBoxRegExp.exec(list);if(null!==v&&(obj.viewX=parseFloat(v[1]),obj.viewY=parseFloat(v[2]),obj.viewW=parseFloat(v[3]),obj.viewH=parseFloat(v[4])),obj.width.indexOf("%")<0){let s=css2cag(obj.width,customPxPmm);s=obj.viewW/s,obj.unitsPmm[0]=s}else{const u=obj.unitsPmm[0]*(parseFloat(obj.width)/100);obj.unitsPmm[0]=u}if(obj.height.indexOf("%")<0){let s=css2cag(obj.height,pxPmm);s=obj.viewH/s,obj.unitsPmm[1]=s}else{const u=obj.unitsPmm[1]*(parseFloat(obj.height)/100);obj.unitsPmm[1]=u}}else obj.viewX=0,obj.viewY=0,obj.viewW=1920/obj.unitsPmm[0],obj.viewH=1080/obj.unitsPmm[1];return obj.viewP=Math.sqrt(obj.viewW*obj.viewW+obj.viewH*obj.viewH)/Math.SQRT2,svgCore(obj,element),svgPresentation(obj,element),obj.objects=[],obj},svgEllipse=element=>{const obj={type:"ellipse",cx:"0",cy:"0",rx:"0",ry:"0"};return"cx"in element&&(obj.cx=element.cx),"cy"in element&&(obj.cy=element.cy),"rx"in element&&(obj.rx=element.rx),"ry"in element&&(obj.ry=element.ry),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgLine=element=>{const obj={type:"line",x1:"0",y1:"0",x2:"0",y2:"0"};return"x1"in element&&(obj.x1=element.x1),"y1"in element&&(obj.y1=element.y1),"x2"in element&&(obj.x2=element.x2),"y2"in element&&(obj.y2=element.y2),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgListOfPoints=list=>{const points=[],exp=/([\d\-+.]+)[\s,]+([\d\-+.]+)[\s,]*/i;list=list.trim();let v=exp.exec(list);for(;null!==v;){let point=v[0];const next=exp.lastIndex+point.length;point={x:v[1],y:v[2]},points.push(point),list=list.slice(next,list.length),v=exp.exec(list)}return points},svgPolyline=element=>{const obj={type:"polyline"};return svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"points"in element&&(obj.points=svgListOfPoints(element.points)),obj},svgPolygon=element=>{const obj={type:"polygon"};return svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"points"in element&&(obj.points=svgListOfPoints(element.points)),obj},svgRect=element=>{const obj={type:"rect",x:"0",y:"0",rx:"0",ry:"0",width:"0",height:"0"};return"x"in element&&(obj.x=element.x),"y"in element&&(obj.y=element.y),"rx"in element&&(obj.rx=element.rx,"ry"in element||(obj.ry=obj.rx)),"ry"in element&&(obj.ry=element.ry,"rx"in element||(obj.rx=obj.ry)),obj.rx!==obj.ry&&console.log("Warning: Unsupported RECT with rx and ry radius"),"width"in element&&(obj.width=element.width),"height"in element&&(obj.height=element.height),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgCircle=element=>{const obj={type:"circle",x:"0",y:"0",radius:"0"};return"cx"in element&&(obj.x=element.cx),"cy"in element&&(obj.y=element.cy),"r"in element&&(obj.radius=element.r),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgGroup=element=>{const obj={type:"group"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"x"in element||"y"in element){let x="0",y="0";"x"in element&&(x=element.x),"y"in element&&(y=element.y),"transforms"in obj||(obj.transforms=[]);const o={translate:[x,y]};obj.transforms.push(o)}return obj.objects=[],obj},svgPath=element=>{const obj={type:"path"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj.commands=[],"d"in element){let co=null,bf="",i=0;const l=element.d.length,offset=element.position[1]-l-2;for(;i0&&(co.p.push(bf),bf=""),bf+=c;break;case".":bf.length>0&&bf.indexOf(".")>=0&&(co.p.push(bf),bf=""),bf+=c;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":bf+=c;break;case"a":case"A":case"c":case"C":case"h":case"H":case"l":case"L":case"v":case"V":case"m":case"M":case"q":case"Q":case"s":case"S":case"t":case"T":case"z":case"Z":null!==co&&(bf.length>0&&(co.p.push(bf),bf=""),obj.commands.push(co)),co={c:c,p:[],pos:i+offset};break;case",":case" ":case"\n":null!==co&&bf.length>0&&(co.p.push(bf),bf="")}i++}i===l&&null!==co&&(bf.length>0&&co.p.push(bf),obj.commands.push(co))}return obj},svgUse=(element,{svgObjects:svgObjects})=>{const obj={type:"group"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"x"in element||"y"in element){let x="0",y="0";"x"in element&&(x=element.x),"y"in element&&(y=element.y),"transforms"in obj||(obj.transforms=[]);const o={translate:[x,y]};obj.transforms.push(o)}if(obj.objects=[],"xlink:href"in element){let ref=element["xlink:href"];"#"===ref[0]&&(ref=ref.slice(1,ref.length)),void 0!==svgObjects[ref]&&(ref=svgObjects[ref],ref=JSON.parse(JSON.stringify(ref)),obj.objects.push(ref))}return obj},shapesMapGeometry=(obj,objectify,params)=>{const{svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,svgGroups:svgGroups,target:target,segments:segments,pathSelfClosed:pathSelfClosed}=params,types={group:obj=>objectify({target:target,segments:segments},obj),rect:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{let x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY);const w=cagLengthX(obj.width,svgUnitsPmm,svgUnitsX),h=cagLengthY(obj.height,svgUnitsPmm,svgUnitsY),rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX);let shape;return w>0&&h>0&&(x+=w/2,y-=h/2,shape=0===rx?rectangle({center:[x,y],size:[w,h]}):(options=>{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1])return create$a();if(0===roundRadius)return rectangle({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS)throw new Error("roundRadius must be smaller then the radius of all dimensions");const cornerSegments=Math.floor(segments/4),corner0=add([0,0],center,[size[0]-roundRadius,size[1]-roundRadius]),corner1=add([0,0],center,[roundRadius-size[0],size[1]-roundRadius]),corner2=add([0,0],center,[roundRadius-size[0],roundRadius-size[1]]),corner3=add([0,0],center,[size[0]-roundRadius,roundRadius-size[1]]),corner0Points=[],corner1Points=[],corner2Points=[],corner3Points=[];for(let i=0;i<=cornerSegments;i++){const point=fromAngleRadians([0,0],TAU/4*i/cornerSegments);scale$1(point,point,roundRadius),corner0Points.push(add([0,0],corner0,point)),rotate$1(point,point,[0,0],TAU/4),corner1Points.push(add([0,0],corner1,point)),rotate$1(point,point,[0,0],TAU/4),corner2Points.push(add([0,0],corner2,point)),rotate$1(point,point,[0,0],TAU/4),corner3Points.push(add([0,0],corner3,point))}const points=corner0Points.concat(corner1Points,corner2Points,corner3Points);return create$a([points])})({center:[x,y],segments:segments,size:[w,h],roundRadius:rx}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},circle:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{const x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY),r=cagLengthP(obj.radius,svgUnitsPmm,svgUnitsV);let shape;return r>0&&(shape=(options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})})({center:[x,y],segments:segments,radius:r}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},ellipse:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{const rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX),ry=cagLengthY(obj.ry,svgUnitsPmm,svgUnitsY),cx=cagLengthX(obj.cx,svgUnitsPmm,svgUnitsX),cy=0-cagLengthY(obj.cy,svgUnitsPmm,svgUnitsY);let shape;return rx>0&&ry>0&&(shape=ellipse({center:[cx,cy],segments:segments,radius:[rx,ry]}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},line:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV)=>{const x1=cagLengthX(obj.x1,svgUnitsPmm,svgUnitsX),y1=0-cagLengthY(obj.y1,svgUnitsPmm,svgUnitsY),x2=cagLengthX(obj.x2,svgUnitsPmm,svgUnitsX),y2=0-cagLengthY(obj.y2,svgUnitsPmm,svgUnitsY);return line([[x1,y1],[x2,y2]])},polygon:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY)=>{const points=[];for(let j=0;j{const points=[];for(let j=0;j{const listofpaths=expandPath(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments,pathSelfClosed),shapes=Object.entries(listofpaths).sort(((a,b)=>a[0].localeCompare(b[0]))).map((entry=>{const path=entry[1];if("geom2"===target&&path.isClosed){const points=index$5.toPoints(path);return index$a.create([points])}return path}));return shapes}};return types[obj.type](obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)},appendPoints=(points,geometry)=>geometry?index$5.appendPoints(points,geometry):index$5.fromPoints({},points),expandPath=(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments,pathSelfClosed)=>{const paths={};let sx=0,sy=0,cx=0,cy=0,pi=0,pathName="path"+pi,pc=!1,bx=0,by=0,qx=0,qy=0;const newPath=()=>{pi++,pathName="path"+pi,pc=!1},ensurePath=()=>{paths[pathName]||(paths[pathName]=index$5.fromPoints({},[]))};for(let j=0;j=i+2&&(cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),newPath(),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)]),sx=cx,sy=cy);pts.length>=i+2;)cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"M":for(pts.length>=i+2&&(cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),newPath(),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)]),sx=cx,sy=cy);pts.length>=i+2;)cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"a":for(;pts.length>=i+7;){const rx=parseFloat(pts[i++]),ry=parseFloat(pts[i++]),ro=0-.017453292519943295*parseFloat(pts[i++]),lf="1"===pts[i++],sf="1"===pts[i++];cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendArc({segments:segments,endpoint:svg2cag([cx,cy],svgUnitsPmm),radius:svg2cag([rx,ry],svgUnitsPmm),xaxisrotation:ro,clockwise:sf,large:lf},paths[pathName])}break;case"A":for(;pts.length>=i+7;){const rx=parseFloat(pts[i++]),ry=parseFloat(pts[i++]),ro=0-.017453292519943295*parseFloat(pts[i++]),lf="1"===pts[i++],sf="1"===pts[i++];cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendArc({segments:segments,endpoint:svg2cag([cx,cy],svgUnitsPmm),radius:svg2cag([rx,ry],svgUnitsPmm),xaxisrotation:ro,clockwise:sf,large:lf},paths[pathName])}break;case"c":for(;pts.length>=i+6;){const x1=cx+parseFloat(pts[i++]),y1=cy+parseFloat(pts[i++]);bx=cx+parseFloat(pts[i++]),by=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"C":for(;pts.length>=i+6;){const x1=parseFloat(pts[i++]),y1=parseFloat(pts[i++]);bx=parseFloat(pts[i++]),by=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"q":for(;pts.length>=i+4;){const p0=[cx,cy];qx=cx+parseFloat(pts[i++]),qy=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"Q":for(;pts.length>=i+4;){const p0=[cx,cy];qx=parseFloat(pts[i++]),qy=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"t":for(;pts.length>=i+2;){const p0=[cx,cy];cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"T":for(;pts.length>=i+2;){const p0=[cx,cy];cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"s":for(;pts.length>=i+4;){const x1=bx,y1=by;bx=cx+parseFloat(pts[i++]),by=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"S":for(;pts.length>=i+4;){const x1=bx,y1=by;bx=parseFloat(pts[i++]),by=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"h":for(;pts.length>=i+1;)cx+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"H":for(;pts.length>=i+1;)cx=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"l":for(;pts.length>=i+2;)cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"L":for(;pts.length>=i+2;)cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"v":for(;pts.length>=i+1;)cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"V":for(;pts.length>=i+1;)cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"z":case"Z":paths[pathName]=index$5.close(paths[pathName]),cx=sx,cy=sy,pc=!0;break;default:console.log("Warning: Unknown PATH command ["+co.c+"]")}const isCloseCmd=cmd=>"z"===cmd||"Z"===cmd;if(!0!==pc&&paths[pathName]&&paths[pathName].isClosed){let coNext=obj.commands[j+1];if(coNext&&!isCloseCmd(coNext.c))if("trim"===pathSelfClosed)for(;coNext&&!isCloseCmd(coNext.c);)j++,coNext=obj.commands[j+1];else{if("split"!==pathSelfClosed)throw new Error(`Malformed svg path at ${obj.position[0]}:${co.pos}. Path closed itself with command #${j} ${co.c}${pts.join(" ")}`);newPath()}}}return paths},shapesMapJscad=(obj,codify,params)=>{const{level:level,indent:indent,on:on,svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,svgGroups:svgGroups,target:target,segments:segments}=params,types={group:obj=>{let code=codify({target:target,segments:segments},obj);return code+=`${indent}${on} = levels.l${level+1}\n`,code},rect:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{let x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY);const w=cagLengthX(obj.width,svgUnitsPmm,svgUnitsX),h=cagLengthY(obj.height,svgUnitsPmm,svgUnitsY),rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX);let code;return w>0&&h>0&&(x=(x+w/2).toFixed(4),y=(y-h/2).toFixed(4),code=0===rx?`${indent}${on} = rectangle({center: [${x}, ${y}], size: [${w}, ${h}]}) // line ${obj.position}\n`:`${indent}${on} = roundedRectangle({center: [${x}, ${y}], segments: ${segments}, size: [${w}, ${h}], roundRadius: ${rx}}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},circle:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{const x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY),r=cagLengthP(obj.radius,svgUnitsPmm,svgUnitsV);let code;return r>0&&(code=`${indent}${on} = circle({center: [${x}, ${y}], segments: ${segments}, radius: ${r}}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},ellipse:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{const rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX),ry=cagLengthY(obj.ry,svgUnitsPmm,svgUnitsY),cx=cagLengthX(obj.cx,svgUnitsPmm,svgUnitsX),cy=0-cagLengthY(obj.cy,svgUnitsPmm,svgUnitsY);let code;return rx>0&&ry>0&&(code=`${indent}${on} = ellipse({center: [${cx}, ${cy}], segments: ${segments}, radius: [${rx}, ${ry}]}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},line:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV)=>{const x1=cagLengthX(obj.x1,svgUnitsPmm,svgUnitsX),y1=0-cagLengthY(obj.y1,svgUnitsPmm,svgUnitsY),x2=cagLengthX(obj.x2,svgUnitsPmm,svgUnitsX),y2=0-cagLengthY(obj.y2,svgUnitsPmm,svgUnitsY);return`${indent}${on} = line([[${x1}, ${y1}], [${x2}, ${y2}]]) // line ${obj.position}\n`},polygon:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY)=>{let code=`${indent}${on} = polygon({points: [\n`;for(let j=0;j{let code=`${indent}${on} = path2.fromPoints({}, [\n`;for(let j=0;j{const{indent:indent,on:on,target:target}=params;let tmpCode=`${indent}parts = [] // line ${obj.position}\n`,sx=0,sy=0,cx=0,cy=0,pi=0,pathName=on+pi,pc=!1,bx=0,by=0,qx=0,qy=0;for(let j=0;j0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),pts.length>=2&&(cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),pi++,pc=!1,pathName=on+pi,tmpCode+=`${indent}${pathName} = path2.fromPoints({}, [[${svg2cag([cx,cy],svgUnitsPmm)}]])\n`,sx=cx,sy=cy);pts.length>=2;)cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([${svg2cag([cx,cy],svgUnitsPmm)}], ${pathName})\n`;break;case"M":for(pi>0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),pts.length>=2&&(cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),pi++,pc=!1,pathName=on+pi,tmpCode+=`${indent}${pathName} = path2.fromPoints({}, [[${svg2cag([cx,cy],svgUnitsPmm)}]])\n`,sx=cx,sy=cy);pts.length>=2;)cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([${svg2cag([cx,cy],svgUnitsPmm)}], ${pathName})\n`;break;case"a":for(;pts.length>=7;){const rx=parseFloat(pts.shift()),ry=parseFloat(pts.shift()),ro=0-.017453292519943295*parseFloat(pts.shift()),lf="1"===pts.shift(),sf="1"===pts.shift();cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendArc({segments: ${segments}, endpoint: [${svg2cag([cx,cy],svgUnitsPmm)}], radius: [${svg2cag([rx,ry],svgUnitsPmm)}], xaxisrotation: ${ro}, clockwise: ${sf}, large: ${lf}}, ${pathName})\n`}break;case"A":for(;pts.length>=7;){const rx=parseFloat(pts.shift()),ry=parseFloat(pts.shift()),ro=0-.017453292519943295*parseFloat(pts.shift()),lf="1"===pts.shift(),sf="1"===pts.shift();cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendArc({segments: ${segments}, endpoint: [${svg2cag([cx,cy],svgUnitsPmm)}], radius: [${svg2cag([rx,ry],svgUnitsPmm)}], xaxisrotation: ${ro}, clockwise: ${sf}, large: ${lf}}, ${pathName})\n`}break;case"c":for(;pts.length>=6;){const x1=cx+parseFloat(pts.shift()),y1=cy+parseFloat(pts.shift());bx=cx+parseFloat(pts.shift()),by=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"C":for(;pts.length>=6;){const x1=parseFloat(pts.shift()),y1=parseFloat(pts.shift());bx=parseFloat(pts.shift()),by=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"q":for(;pts.length>=4;){const p0=[cx,cy];qx=cx+parseFloat(pts.shift()),qy=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"Q":for(;pts.length>=4;){const p0=[cx,cy];qx=parseFloat(pts.shift()),qy=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"t":for(;pts.length>=2;){const p0=[cx,cy];cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"T":for(;pts.length>=2;){const p0=[cx,cy];cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"s":for(;pts.length>=4;){const x1=bx,y1=by;bx=cx+parseFloat(pts.shift()),by=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"S":for(;pts.length>=4;){const x1=bx,y1=by;bx=parseFloat(pts.shift()),by=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"h":for(;pts.length>=1;)cx+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"H":for(;pts.length>=1;)cx=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"l":for(;pts.length>=2;)cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"L":for(;pts.length>=2;)cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"v":for(;pts.length>=1;)cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"V":for(;pts.length>=1;)cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"z":case"Z":tmpCode+=`${indent}${pathName} = path2.close(${pathName})\n`,"geom2"===target&&(tmpCode+=`${indent}${pathName} = geom2.create([path2.toPoints(${pathName})])\n`),tmpCode+=`${indent}parts.push(${pathName})\n`,cx=sx,cy=sy,pc=!0;break;default:console.log("Warning: Unknow PATH command ["+co.c+"]")}}return pi>0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),tmpCode+=`${indent}${on} = parts\n`,tmpCode},deserialize=(options,input)=>{const defaults={addMetaData:!0,filename:"svg",output:"script",pxPmm:pxPmm,segments:32,target:"path",pathSelfClosed:"error",version:"3.0.0-alpha.0"};return"script"===(options=Object.assign({},defaults,options)).output?translateScript(input,options):instantiate(input,options)},instantiate=(src,options)=>{const{pxPmm:pxPmm}=options;if(options&&options.statusCallback&&options.statusCallback({progress:0}),createSvgParser(src,pxPmm),!svgObj)throw new Error("SVG parsing failed, no valid SVG data retrieved");options&&options.statusCallback&&options.statusCallback({progress:50});const result=objectify(options,svgObj);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},translateScript=(src,options)=>{const{filename:filename,version:version,pxPmm:pxPmm,addMetaData:addMetaData}=options;if(options&&options.statusCallback&&options.statusCallback({progress:0}),createSvgParser(src,pxPmm),!svgObj)throw new Error("SVG parsing failed, no valid SVG data retrieved");let code=addMetaData?`//\n // producer: JSCAD SVG Deserializer ${version}\n // date: ${new Date}\n // source: ${filename}\n //\n`:"";code+="const { colors, geometries, primitives, transforms } = require('@jscad/modeling')\n\n",options&&options.statusCallback&&options.statusCallback({progress:50});return code+=codify(options,svgObj),code+="\nmodule.exports = { main }",options&&options.statusCallback&&options.statusCallback({progress:100}),code};let svgUnitsX,svgUnitsY,svgUnitsV;const svgObjects=[],svgGroups=[],svgDefs=[];let svgObj,svgInDefs=!1,svgUnitsPmm=[1,1];const objectify=(options,group)=>{const{target:target,segments:segments,pathSelfClosed:pathSelfClosed}=options,level=svgGroups.length;svgGroups.push(group);let i=level;for(;i>0;)i--;let geometries=[];const params={svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,level:level,target:target,svgGroups:svgGroups,segments:segments,pathSelfClosed:pathSelfClosed};for(i=0;i{if("transforms"in obj){let rotateAttribute=null,scaleAttribute=null,translateAttribute=null;for(let j=0;j{const{target:target,segments:segments}=options,level=svgGroups.length;svgGroups.push(group);let indent=" ",i=level;for(;i>0;)indent+=" ",i--;let code="";0===level&&(code+="function main(params) {\n let levels = {}\n let paths = {}\n let parts\n");const ln="levels.l"+level;for(code+=`${indent}${ln} = []\n`,i=0;i{const parser=new saxes.SaxesParser;return void 0!==pxPmm&&pxPmm>parser.pxPmm&&(parser.pxPmm=pxPmm),parser.on("error",(e=>{console.log(`ERROR: SVG file, line ${parser.line}, column ${parser.column}`),console.log(e)})),parser.on("opentag",(node=>{const objMap={SVG:svgSvg,G:svgGroup,RECT:svgRect,CIRCLE:svgCircle,ELLIPSE:svgEllipse,LINE:svgLine,POLYLINE:svgPolyline,POLYGON:svgPolygon,PATH:svgPath,USE:svgUse,DEFS:()=>{svgInDefs=!0},DESC:()=>{},TITLE:()=>{},STYLE:()=>{},undefined:()=>console.log("WARNING: unsupported SVG element: "+node.name)};node.attributes.position=[parser.line+1,parser.column+1];const elementName=node.name.toUpperCase(),obj=objMap[elementName]?objMap[elementName](node.attributes,{svgObjects:svgObjects,customPxPmm:pxPmm}):void 0;if(obj)if("id"in obj&&(svgObjects[obj.id]=obj),"svg"===obj.type)svgGroups.push(obj),svgUnitsPmm=obj.unitsPmm,svgUnitsX=obj.viewW,svgUnitsY=obj.viewH,svgUnitsV=obj.viewP;else if(!0===svgInDefs){if(svgDefs.length>0){const group=svgDefs.pop();"objects"in group&&group.objects.push(obj),svgDefs.push(group)}"group"===obj.type&&svgDefs.push(obj)}else{if(svgGroups.length>0){const group=svgGroups.pop();"objects"in group&&group.objects.push(obj),svgGroups.push(group)}"group"===obj.type&&svgGroups.push(obj)}})),parser.on("closetag",(node=>{const popGroup=()=>!0===svgInDefs?svgDefs.pop():svgGroups.pop(),objMap={SVG:popGroup,DEFS:()=>{svgInDefs=!1},USE:popGroup,G:popGroup,undefined:()=>{}},elementName=node.name.toUpperCase(),obj=objMap[elementName]?objMap[elementName]():void 0;0===svgGroups.length&&(svgObj=obj)})),parser.on("end",(()=>{})),parser.write(src).close(),parser},mimeType="image/svg+xml";export{deserialize,mimeType}; +const clone$b=geometry=>Object.assign({},geometry),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation=(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply$1=(out,a,b)=>{const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:fromScaling,fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:mirrorByPlane,multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromNormalAndPoint=(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:fromNormalAndPoint,fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints$1=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints$1(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints$1,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");3===color.length&&(color=[color[0],color[1],color[2],1]);const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):Array.isArray(object)?colorize(color,...object):(object.color=color,object)));return 1===results.length?results[0]:results},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},rectangle=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])},mirror=(options,...objects)=>{const{origin:origin,normal:normal}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},options),planeOfMirror=fromNormalAndPoint([0,0,0,0],normal,origin);if(Number.isNaN(planeOfMirror[0]))throw new Error("the given origin and normal do not define a proper plane");const matrix=mirrorByPlane([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],planeOfMirror),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?mirror(options,...object):object));return 1===results.length?results[0]:results},mirrorX=(...objects)=>mirror({normal:[1,0,0]},...objects),mirrorY=(...objects)=>mirror({normal:[0,1,0]},...objects),rotate=(angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?rotate(angles,...object):object));return 1===results.length?results[0]:results},rotateZ=(angle,...objects)=>rotate([0,0,angle],...objects),translate=(offset,...objects)=>{if(!Array.isArray(offset))throw new Error("offset must be an array");for(offset=offset.slice();offset.length<3;)offset.push(0);const matrix=fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offset),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?translate(offset,...object):object));return 1===results.length?results[0]:results},scale=(factors,...objects)=>{if(!Array.isArray(factors))throw new Error("factors must be an array");for(factors=factors.slice();factors.length<3;)factors.push(1);if(factors[0]<=0||factors[1]<=0||factors[2]<=0)throw new Error("factors must be positive");const matrix=fromScaling([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],factors),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?scale(factors,...object):object));return 1===results.length?results[0]:results},pxPmm=1/.2822222,svgColors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},svg2cag=(vec,svgUnitsPmm)=>[vec[0]/svgUnitsPmm[0],0-vec[1]/svgUnitsPmm[1]],cagLengthX=(css,svgUnitsPmm,svgUnitsX)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[0]);let v=parseFloat(css);return isNaN(v)?0:0===v?v:(v=v/100*svgUnitsX,v/=svgUnitsPmm[0],Math.round(1e5*v)/1e5)},cagLengthY=(css,svgUnitsPmm,svgUnitsY)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[1]);let v=parseFloat(css);return isNaN(v)?0:0===v?v:(v=v/100*svgUnitsY,v/=svgUnitsPmm[1],Math.round(1e5*v)/1e5)},cagLengthP=(css,svgUnitsPmm,svgUnitsV)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[1]);let v=parseFloat(css);return isNaN(v)?0:(0===v||(v=v/100*svgUnitsV,v/=svgUnitsPmm[0]),v)},css2cag=(css,unit)=>{let v=parseFloat(css);return isNaN(v)?0:(0===v||css.search(/EM/i)>0||css.search(/EX/i)>0||css.search(/MM/i)>0||(css.search(/CM/i)>0?v*=10:css.search(/IN/i)>0?v/=.03937:css.search(/PT/i)>0?v/=2.8346400000000003:css.search(/PC/i)>0?v/=.23622:v/=unit),v)},cagColor=value=>{let rgb;if((value=value.toLowerCase())in svgColors)rgb=svgColors[value],rgb=[rgb[0]/255,rgb[1]/255,rgb[2]/255];else if("#"===value[0])4===value.length&&(value="#"+value[1]+value[1]+value[2]+value[2]+value[3]+value[3]),7===value.length&&(rgb=[parseInt("0x"+value.slice(1,3))/255,parseInt("0x"+value.slice(3,5))/255,parseInt("0x"+value.slice(5,7))/255]);else{let s=/rgb\(.+,.+,.+\)/.exec(value);null!==s&&(s=s[0],s=s.slice(s.indexOf("(")+1,s.indexOf(")")),rgb=s.split(","),s.indexOf("%")>0?(rgb=[parseInt(rgb[0]),parseInt(rgb[1]),parseInt(rgb[2])],rgb=[rgb[0]/100,rgb[1]/100,rgb[2]/100]):(rgb=[parseInt(rgb[0]),parseInt(rgb[1]),parseInt(rgb[2])],rgb=[rgb[0]/255,rgb[1]/255,rgb[2]/255]))}return rgb},cssStyle=(element,name)=>{if("style"in element){const list=element.style+";";let v=new RegExp(name+"\\s*:\\s*(\\S+);","i").exec(list);if(null!==v){v=v[0];let i=v.indexOf(":")+1;for(;" "===v[i];)i++;return v=v.slice(i,v.indexOf(";")),v}}},reflect=(x,y,px,py)=>{const ox=x-px,oy=y-py;return x===px&&y===px?[x,y]:x===px?[x,py+-oy]:y===py?[px+-ox,y]:[px+-ox,py+-oy]},svgColorForTarget=(target,svgObject)=>{let color=null;return"path"===target?svgObject.stroke?color=[svgObject.stroke[0],svgObject.stroke[1],svgObject.stroke[2],1]:svgObject.fill&&(color=[svgObject.fill[0],svgObject.fill[1],svgObject.fill[2],1]):svgObject.fill?color=[svgObject.fill[0],svgObject.fill[1],svgObject.fill[2],1]:svgObject.stroke&&(color=[svgObject.stroke[0],svgObject.stroke[1],svgObject.stroke[2],1]),color},svgCore=(obj,element)=>{"id"in element&&(obj.id=element.id),"position"in element&&(obj.position=element.position)},svgPresentation=(obj,element)=>{if("display"in element&&(obj.visible=element.display),"color"in element&&(obj.fill=cagColor(element.color),obj.stroke=obj.fill),"opacity"in element&&(obj.opacity=element.opacity),"fill"in element)obj.fill=cagColor(element.fill);else{const s=cssStyle(element,"fill");s&&(obj.fill=cagColor(s))}if("fill-opacity"in element&&(obj.opacity=element["fill-opacity"]),"stroke-width"in element)obj.strokeWidth=element["stroke-width"];else{const sw=cssStyle(element,"stroke-width");sw&&(obj.strokeWidth=sw)}if("stroke"in element)obj.stroke=cagColor(element.stroke);else{const s=cssStyle(element,"stroke");s&&(obj.stroke=cagColor(s))}"stroke-opacity"in element&&(obj.strokeOpacity=element["stroke-opacity"])},svgTransformsRegExp=/\w+\(.+\)/i,svgTransforms=(cag,element)=>{let list=null;if("transform"in element)list=element.transform;else{const s=cssStyle(element,"transform");s&&(list=s)}if(null!==list){cag.transforms=[];let v=svgTransformsRegExp.exec(list);for(;null!==v;){const s=svgTransformsRegExp.lastIndex,e=list.indexOf(")")+1;let t=list.slice(s,e);t=t.trim();const n=t.slice(0,t.indexOf("("));let o,a=t.slice(t.indexOf("(")+1,t.indexOf(")")).trim();switch(a=a.indexOf(",")>0?a.split(","):a.split(" "),n){case"translate":1===a.length&&a.push(0),o={translate:[a[0],a[1]]},cag.transforms.push(o);break;case"scale":1===a.length&&a.push(a[0]),o={scale:[a[0],a[1]]},cag.transforms.push(o);break;case"rotate":o={rotate:a},cag.transforms.push(o)}list=list.slice(e,list.length),v=svgTransformsRegExp.exec(list)}}},viewBoxRegExp=/([\d.-]+)[\s,]+([\d.-]+)[\s,]+([\d.-]+)[\s,]+([\d.-]+)/i,svgSvg=(element,{customPxPmm:customPxPmm})=>{const obj={type:"svg",x:0,y:0,width:"100%",height:"100%",strokeWidth:"1"};if(obj.unitsPmm=[pxPmm,pxPmm],"pxpmm"in element&&(obj.pxPmm=element.pxpmm,obj.unitsPmm=[obj.pxPmm,obj.pxPmm]),"width"in element&&(obj.width=element.width),"height"in element&&(obj.height=element.height),"viewBox"in element){const list=element.viewBox.trim(),v=viewBoxRegExp.exec(list);if(null!==v&&(obj.viewX=parseFloat(v[1]),obj.viewY=parseFloat(v[2]),obj.viewW=parseFloat(v[3]),obj.viewH=parseFloat(v[4])),obj.width.indexOf("%")<0){let s=css2cag(obj.width,customPxPmm);s=obj.viewW/s,obj.unitsPmm[0]=s}else{const u=obj.unitsPmm[0]*(parseFloat(obj.width)/100);obj.unitsPmm[0]=u}if(obj.height.indexOf("%")<0){let s=css2cag(obj.height,pxPmm);s=obj.viewH/s,obj.unitsPmm[1]=s}else{const u=obj.unitsPmm[1]*(parseFloat(obj.height)/100);obj.unitsPmm[1]=u}}else obj.viewX=0,obj.viewY=0,obj.viewW=1920/obj.unitsPmm[0],obj.viewH=1080/obj.unitsPmm[1];return obj.viewP=Math.sqrt(obj.viewW*obj.viewW+obj.viewH*obj.viewH)/Math.SQRT2,svgCore(obj,element),svgPresentation(obj,element),obj.objects=[],obj},svgEllipse=element=>{const obj={type:"ellipse",cx:"0",cy:"0",rx:"0",ry:"0"};return"cx"in element&&(obj.cx=element.cx),"cy"in element&&(obj.cy=element.cy),"rx"in element&&(obj.rx=element.rx),"ry"in element&&(obj.ry=element.ry),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgLine=element=>{const obj={type:"line",x1:"0",y1:"0",x2:"0",y2:"0"};return"x1"in element&&(obj.x1=element.x1),"y1"in element&&(obj.y1=element.y1),"x2"in element&&(obj.x2=element.x2),"y2"in element&&(obj.y2=element.y2),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgListOfPoints=list=>{const points=[],exp=/([\d\-+.]+)[\s,]+([\d\-+.]+)[\s,]*/i;list=list.trim();let v=exp.exec(list);for(;null!==v;){let point=v[0];const next=exp.lastIndex+point.length;point={x:v[1],y:v[2]},points.push(point),list=list.slice(next,list.length),v=exp.exec(list)}return points},svgPolyline=element=>{const obj={type:"polyline"};return svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"points"in element&&(obj.points=svgListOfPoints(element.points)),obj},svgPolygon=element=>{const obj={type:"polygon"};return svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"points"in element&&(obj.points=svgListOfPoints(element.points)),obj},svgRect=element=>{const obj={type:"rect",x:"0",y:"0",rx:"0",ry:"0",width:"0",height:"0"};return"x"in element&&(obj.x=element.x),"y"in element&&(obj.y=element.y),"rx"in element&&(obj.rx=element.rx,"ry"in element||(obj.ry=obj.rx)),"ry"in element&&(obj.ry=element.ry,"rx"in element||(obj.rx=obj.ry)),obj.rx!==obj.ry&&console.log("Warning: Unsupported RECT with rx and ry radius"),"width"in element&&(obj.width=element.width),"height"in element&&(obj.height=element.height),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgCircle=element=>{const obj={type:"circle",x:"0",y:"0",radius:"0"};return"cx"in element&&(obj.x=element.cx),"cy"in element&&(obj.y=element.cy),"r"in element&&(obj.radius=element.r),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgGroup=element=>{const obj={type:"group"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"x"in element||"y"in element){let x="0",y="0";"x"in element&&(x=element.x),"y"in element&&(y=element.y),"transforms"in obj||(obj.transforms=[]);const o={translate:[x,y]};obj.transforms.push(o)}return obj.objects=[],obj},svgPath=element=>{const obj={type:"path"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj.commands=[],"d"in element){let co=null,bf="",i=0;const l=element.d.length,offset=element.position[1]-l-2;for(;i0&&(co.p.push(bf),bf=""),bf+=c;break;case".":bf.length>0&&bf.indexOf(".")>=0&&(co.p.push(bf),bf=""),bf+=c;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":bf+=c;break;case"a":case"A":case"c":case"C":case"h":case"H":case"l":case"L":case"v":case"V":case"m":case"M":case"q":case"Q":case"s":case"S":case"t":case"T":case"z":case"Z":null!==co&&(bf.length>0&&(co.p.push(bf),bf=""),obj.commands.push(co)),co={c:c,p:[],pos:i+offset};break;case",":case" ":case"\n":null!==co&&bf.length>0&&(co.p.push(bf),bf="")}i++}i===l&&null!==co&&(bf.length>0&&co.p.push(bf),obj.commands.push(co))}return obj},svgUse=(element,{svgObjects:svgObjects})=>{const obj={type:"group"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"x"in element||"y"in element){let x="0",y="0";"x"in element&&(x=element.x),"y"in element&&(y=element.y),"transforms"in obj||(obj.transforms=[]);const o={translate:[x,y]};obj.transforms.push(o)}if(obj.objects=[],"xlink:href"in element){let ref=element["xlink:href"];"#"===ref[0]&&(ref=ref.slice(1,ref.length)),void 0!==svgObjects[ref]&&(ref=svgObjects[ref],ref=JSON.parse(JSON.stringify(ref)),obj.objects.push(ref))}return obj},shapesMapGeometry=(obj,objectify,params)=>{const{svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,svgGroups:svgGroups,target:target,segments:segments,pathSelfClosed:pathSelfClosed}=params,types={group:obj=>objectify({target:target,segments:segments},obj),rect:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{let x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY);const w=cagLengthX(obj.width,svgUnitsPmm,svgUnitsX),h=cagLengthY(obj.height,svgUnitsPmm,svgUnitsY),rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX);let shape;return w>0&&h>0&&(x+=w/2,y-=h/2,shape=0===rx?rectangle({center:[x,y],size:[w,h]}):(options=>{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1])return create$a();if(0===roundRadius)return rectangle({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS)throw new Error("roundRadius must be smaller than the radius of all dimensions");const cornerSegments=Math.floor(segments/4),corner0=add([0,0],center,[size[0]-roundRadius,size[1]-roundRadius]),corner1=add([0,0],center,[roundRadius-size[0],size[1]-roundRadius]),corner2=add([0,0],center,[roundRadius-size[0],roundRadius-size[1]]),corner3=add([0,0],center,[size[0]-roundRadius,roundRadius-size[1]]),corner0Points=[],corner1Points=[],corner2Points=[],corner3Points=[];for(let i=0;i<=cornerSegments;i++){const point=fromAngleRadians([0,0],TAU/4*i/cornerSegments);scale$1(point,point,roundRadius),corner0Points.push(add([0,0],corner0,point)),rotate$1(point,point,[0,0],TAU/4),corner1Points.push(add([0,0],corner1,point)),rotate$1(point,point,[0,0],TAU/4),corner2Points.push(add([0,0],corner2,point)),rotate$1(point,point,[0,0],TAU/4),corner3Points.push(add([0,0],corner3,point))}const points=corner0Points.concat(corner1Points,corner2Points,corner3Points);return create$a([points])})({center:[x,y],segments:segments,size:[w,h],roundRadius:rx}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},circle:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{const x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY),r=cagLengthP(obj.radius,svgUnitsPmm,svgUnitsV);let shape;return r>0&&(shape=(options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})})({center:[x,y],segments:segments,radius:r}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},ellipse:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{const rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX),ry=cagLengthY(obj.ry,svgUnitsPmm,svgUnitsY),cx=cagLengthX(obj.cx,svgUnitsPmm,svgUnitsX),cy=0-cagLengthY(obj.cy,svgUnitsPmm,svgUnitsY);let shape;return rx>0&&ry>0&&(shape=ellipse({center:[cx,cy],segments:segments,radius:[rx,ry]}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},line:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV)=>{const x1=cagLengthX(obj.x1,svgUnitsPmm,svgUnitsX),y1=0-cagLengthY(obj.y1,svgUnitsPmm,svgUnitsY),x2=cagLengthX(obj.x2,svgUnitsPmm,svgUnitsX),y2=0-cagLengthY(obj.y2,svgUnitsPmm,svgUnitsY);return line([[x1,y1],[x2,y2]])},polygon:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY)=>{const points=[];for(let j=0;j{const points=[];for(let j=0;j{const listofpaths=expandPath(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments,pathSelfClosed),shapes=Object.entries(listofpaths).sort(((a,b)=>a[0].localeCompare(b[0]))).map((entry=>{const path=entry[1];if("geom2"===target&&path.isClosed){const points=index$5.toPoints(path);return index$a.create([points])}return path}));return shapes}};return types[obj.type](obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)},appendPoints=(points,geometry)=>geometry?index$5.appendPoints(points,geometry):index$5.fromPoints({},points),expandPath=(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments,pathSelfClosed)=>{const paths={};let sx=0,sy=0,cx=0,cy=0,pi=0,pathName="path"+pi,pc=!1,bx=0,by=0,qx=0,qy=0;const newPath=()=>{pi++,pathName="path"+pi,pc=!1},ensurePath=()=>{paths[pathName]||(paths[pathName]=index$5.fromPoints({},[]))};for(let j=0;j=i+2&&(cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),newPath(),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)]),sx=cx,sy=cy);pts.length>=i+2;)cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"M":for(pts.length>=i+2&&(cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),newPath(),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)]),sx=cx,sy=cy);pts.length>=i+2;)cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"a":for(;pts.length>=i+7;){const rx=parseFloat(pts[i++]),ry=parseFloat(pts[i++]),ro=0-.017453292519943295*parseFloat(pts[i++]),lf="1"===pts[i++],sf="1"===pts[i++];cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendArc({segments:segments,endpoint:svg2cag([cx,cy],svgUnitsPmm),radius:svg2cag([rx,ry],svgUnitsPmm),xaxisrotation:ro,clockwise:sf,large:lf},paths[pathName])}break;case"A":for(;pts.length>=i+7;){const rx=parseFloat(pts[i++]),ry=parseFloat(pts[i++]),ro=0-.017453292519943295*parseFloat(pts[i++]),lf="1"===pts[i++],sf="1"===pts[i++];cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendArc({segments:segments,endpoint:svg2cag([cx,cy],svgUnitsPmm),radius:svg2cag([rx,ry],svgUnitsPmm),xaxisrotation:ro,clockwise:sf,large:lf},paths[pathName])}break;case"c":for(;pts.length>=i+6;){const x1=cx+parseFloat(pts[i++]),y1=cy+parseFloat(pts[i++]);bx=cx+parseFloat(pts[i++]),by=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"C":for(;pts.length>=i+6;){const x1=parseFloat(pts[i++]),y1=parseFloat(pts[i++]);bx=parseFloat(pts[i++]),by=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"q":for(;pts.length>=i+4;){const p0=[cx,cy];qx=cx+parseFloat(pts[i++]),qy=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"Q":for(;pts.length>=i+4;){const p0=[cx,cy];qx=parseFloat(pts[i++]),qy=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"t":for(;pts.length>=i+2;){const p0=[cx,cy];cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"T":for(;pts.length>=i+2;){const p0=[cx,cy];cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"s":for(;pts.length>=i+4;){const x1=bx,y1=by;bx=cx+parseFloat(pts[i++]),by=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"S":for(;pts.length>=i+4;){const x1=bx,y1=by;bx=parseFloat(pts[i++]),by=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"h":for(;pts.length>=i+1;)cx+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"H":for(;pts.length>=i+1;)cx=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"l":for(;pts.length>=i+2;)cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"L":for(;pts.length>=i+2;)cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"v":for(;pts.length>=i+1;)cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"V":for(;pts.length>=i+1;)cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"z":case"Z":paths[pathName]=index$5.close(paths[pathName]),cx=sx,cy=sy,pc=!0;break;default:console.log("Warning: Unknown PATH command ["+co.c+"]")}const isCloseCmd=cmd=>"z"===cmd||"Z"===cmd;if(!0!==pc&&paths[pathName]&&paths[pathName].isClosed){let coNext=obj.commands[j+1];if(coNext&&!isCloseCmd(coNext.c))if("trim"===pathSelfClosed)for(;coNext&&!isCloseCmd(coNext.c);)j++,coNext=obj.commands[j+1];else{if("split"!==pathSelfClosed)throw new Error(`Malformed svg path at ${obj.position[0]}:${co.pos}. Path closed itself with command #${j} ${co.c}${pts.join(" ")}`);newPath()}}}return paths},shapesMapJscad=(obj,codify,params)=>{const{level:level,indent:indent,on:on,svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,svgGroups:svgGroups,target:target,segments:segments}=params,types={group:obj=>{let code=codify({target:target,segments:segments},obj);return code+=`${indent}${on} = levels.l${level+1}\n`,code},rect:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{let x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY);const w=cagLengthX(obj.width,svgUnitsPmm,svgUnitsX),h=cagLengthY(obj.height,svgUnitsPmm,svgUnitsY),rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX);let code;return w>0&&h>0&&(x=(x+w/2).toFixed(4),y=(y-h/2).toFixed(4),code=0===rx?`${indent}${on} = rectangle({center: [${x}, ${y}], size: [${w}, ${h}]}) // line ${obj.position}\n`:`${indent}${on} = roundedRectangle({center: [${x}, ${y}], segments: ${segments}, size: [${w}, ${h}], roundRadius: ${rx}}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},circle:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{const x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY),r=cagLengthP(obj.radius,svgUnitsPmm,svgUnitsV);let code;return r>0&&(code=`${indent}${on} = circle({center: [${x}, ${y}], segments: ${segments}, radius: ${r}}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},ellipse:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{const rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX),ry=cagLengthY(obj.ry,svgUnitsPmm,svgUnitsY),cx=cagLengthX(obj.cx,svgUnitsPmm,svgUnitsX),cy=0-cagLengthY(obj.cy,svgUnitsPmm,svgUnitsY);let code;return rx>0&&ry>0&&(code=`${indent}${on} = ellipse({center: [${cx}, ${cy}], segments: ${segments}, radius: [${rx}, ${ry}]}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},line:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV)=>{const x1=cagLengthX(obj.x1,svgUnitsPmm,svgUnitsX),y1=0-cagLengthY(obj.y1,svgUnitsPmm,svgUnitsY),x2=cagLengthX(obj.x2,svgUnitsPmm,svgUnitsX),y2=0-cagLengthY(obj.y2,svgUnitsPmm,svgUnitsY);return`${indent}${on} = line([[${x1}, ${y1}], [${x2}, ${y2}]]) // line ${obj.position}\n`},polygon:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY)=>{let code=`${indent}${on} = polygon({points: [\n`;for(let j=0;j{let code=`${indent}${on} = path2.fromPoints({}, [\n`;for(let j=0;j{const{indent:indent,on:on,target:target}=params;let tmpCode=`${indent}parts = [] // line ${obj.position}\n`,sx=0,sy=0,cx=0,cy=0,pi=0,pathName=on+pi,pc=!1,bx=0,by=0,qx=0,qy=0;for(let j=0;j0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),pts.length>=2&&(cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),pi++,pc=!1,pathName=on+pi,tmpCode+=`${indent}${pathName} = path2.fromPoints({}, [[${svg2cag([cx,cy],svgUnitsPmm)}]])\n`,sx=cx,sy=cy);pts.length>=2;)cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([${svg2cag([cx,cy],svgUnitsPmm)}], ${pathName})\n`;break;case"M":for(pi>0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),pts.length>=2&&(cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),pi++,pc=!1,pathName=on+pi,tmpCode+=`${indent}${pathName} = path2.fromPoints({}, [[${svg2cag([cx,cy],svgUnitsPmm)}]])\n`,sx=cx,sy=cy);pts.length>=2;)cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([${svg2cag([cx,cy],svgUnitsPmm)}], ${pathName})\n`;break;case"a":for(;pts.length>=7;){const rx=parseFloat(pts.shift()),ry=parseFloat(pts.shift()),ro=0-.017453292519943295*parseFloat(pts.shift()),lf="1"===pts.shift(),sf="1"===pts.shift();cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendArc({segments: ${segments}, endpoint: [${svg2cag([cx,cy],svgUnitsPmm)}], radius: [${svg2cag([rx,ry],svgUnitsPmm)}], xaxisrotation: ${ro}, clockwise: ${sf}, large: ${lf}}, ${pathName})\n`}break;case"A":for(;pts.length>=7;){const rx=parseFloat(pts.shift()),ry=parseFloat(pts.shift()),ro=0-.017453292519943295*parseFloat(pts.shift()),lf="1"===pts.shift(),sf="1"===pts.shift();cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendArc({segments: ${segments}, endpoint: [${svg2cag([cx,cy],svgUnitsPmm)}], radius: [${svg2cag([rx,ry],svgUnitsPmm)}], xaxisrotation: ${ro}, clockwise: ${sf}, large: ${lf}}, ${pathName})\n`}break;case"c":for(;pts.length>=6;){const x1=cx+parseFloat(pts.shift()),y1=cy+parseFloat(pts.shift());bx=cx+parseFloat(pts.shift()),by=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"C":for(;pts.length>=6;){const x1=parseFloat(pts.shift()),y1=parseFloat(pts.shift());bx=parseFloat(pts.shift()),by=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"q":for(;pts.length>=4;){const p0=[cx,cy];qx=cx+parseFloat(pts.shift()),qy=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"Q":for(;pts.length>=4;){const p0=[cx,cy];qx=parseFloat(pts.shift()),qy=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"t":for(;pts.length>=2;){const p0=[cx,cy];cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"T":for(;pts.length>=2;){const p0=[cx,cy];cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"s":for(;pts.length>=4;){const x1=bx,y1=by;bx=cx+parseFloat(pts.shift()),by=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"S":for(;pts.length>=4;){const x1=bx,y1=by;bx=parseFloat(pts.shift()),by=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"h":for(;pts.length>=1;)cx+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"H":for(;pts.length>=1;)cx=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"l":for(;pts.length>=2;)cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"L":for(;pts.length>=2;)cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"v":for(;pts.length>=1;)cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"V":for(;pts.length>=1;)cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"z":case"Z":tmpCode+=`${indent}${pathName} = path2.close(${pathName})\n`,"geom2"===target&&(tmpCode+=`${indent}${pathName} = geom2.create([path2.toPoints(${pathName})])\n`),tmpCode+=`${indent}parts.push(${pathName})\n`,cx=sx,cy=sy,pc=!0;break;default:console.log("Warning: Unknow PATH command ["+co.c+"]")}}return pi>0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),tmpCode+=`${indent}${on} = parts\n`,tmpCode},deserialize=(options,input)=>{const defaults={addMetaData:!0,filename:"svg",output:"script",pxPmm:pxPmm,segments:32,target:"path",pathSelfClosed:"error",version:"3.0.1-alpha.0"};return options=Object.assign({},defaults,options),input=((stringOrArrayBuffer,defaultBinaryEncoding="utf-8")=>"string"==typeof stringOrArrayBuffer?stringOrArrayBuffer:new TextDecoder(defaultBinaryEncoding).decode(new Uint8Array(stringOrArrayBuffer)))(input),"script"===options.output?translateScript(input,options):instantiate(input,options)},instantiate=(src,options)=>{const{pxPmm:pxPmm}=options;if(options&&options.statusCallback&&options.statusCallback({progress:0}),createSvgParser(src,pxPmm),!svgObj)throw new Error("SVG parsing failed, no valid SVG data retrieved");options&&options.statusCallback&&options.statusCallback({progress:50});const result=objectify(options,svgObj);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},translateScript=(src,options)=>{const{filename:filename,version:version,pxPmm:pxPmm,addMetaData:addMetaData}=options;if(options&&options.statusCallback&&options.statusCallback({progress:0}),createSvgParser(src,pxPmm),!svgObj)throw new Error("SVG parsing failed, no valid SVG data retrieved");let code=addMetaData?`//\n // producer: JSCAD SVG Deserializer ${version}\n // date: ${new Date}\n // source: ${filename}\n //\n`:"";code+="const { colors, geometries, primitives, transforms } = require('@jscad/modeling')\n\n",options&&options.statusCallback&&options.statusCallback({progress:50});return code+=codify(options,svgObj),code+="\nmodule.exports = { main }",options&&options.statusCallback&&options.statusCallback({progress:100}),code};let svgUnitsX,svgUnitsY,svgUnitsV;const svgObjects=[],svgGroups=[],svgDefs=[];let svgObj,svgInDefs=!1,svgUnitsPmm=[1,1];const objectify=(options,group)=>{const{target:target,segments:segments,pathSelfClosed:pathSelfClosed}=options,level=svgGroups.length;svgGroups.push(group);let i=level;for(;i>0;)i--;let geometries=[];const params={svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,level:level,target:target,svgGroups:svgGroups,segments:segments,pathSelfClosed:pathSelfClosed};for(i=0;i{if("transforms"in obj){let rotateAttribute=null,scaleAttribute=null,translateAttribute=null;for(let j=0;j{const{target:target,segments:segments}=options,level=svgGroups.length;svgGroups.push(group);let indent=" ",i=level;for(;i>0;)indent+=" ",i--;let code="";0===level&&(code+="function main(params) {\n let levels = {}\n let paths = {}\n let parts\n");const ln="levels.l"+level;for(code+=`${indent}${ln} = []\n`,i=0;i{const parser=new saxes.SaxesParser;return void 0!==pxPmm&&pxPmm>parser.pxPmm&&(parser.pxPmm=pxPmm),parser.on("error",(e=>{console.log(`ERROR: SVG file, line ${parser.line}, column ${parser.column}`),console.log(e)})),parser.on("opentag",(node=>{const objMap={SVG:svgSvg,G:svgGroup,RECT:svgRect,CIRCLE:svgCircle,ELLIPSE:svgEllipse,LINE:svgLine,POLYLINE:svgPolyline,POLYGON:svgPolygon,PATH:svgPath,USE:svgUse,DEFS:()=>{svgInDefs=!0},DESC:()=>{},TITLE:()=>{},STYLE:()=>{},undefined:()=>console.log("WARNING: unsupported SVG element: "+node.name)};node.attributes.position=[parser.line+1,parser.column+1];const elementName=node.name.toUpperCase(),obj=objMap[elementName]?objMap[elementName](node.attributes,{svgObjects:svgObjects,customPxPmm:pxPmm}):void 0;if(obj)if("id"in obj&&(svgObjects[obj.id]=obj),"svg"===obj.type)svgGroups.push(obj),svgUnitsPmm=obj.unitsPmm,svgUnitsX=obj.viewW,svgUnitsY=obj.viewH,svgUnitsV=obj.viewP;else if(!0===svgInDefs){if(svgDefs.length>0){const group=svgDefs.pop();"objects"in group&&group.objects.push(obj),svgDefs.push(group)}"group"===obj.type&&svgDefs.push(obj)}else{if(svgGroups.length>0){const group=svgGroups.pop();"objects"in group&&group.objects.push(obj),svgGroups.push(group)}"group"===obj.type&&svgGroups.push(obj)}})),parser.on("closetag",(node=>{const popGroup=()=>!0===svgInDefs?svgDefs.pop():svgGroups.pop(),objMap={SVG:popGroup,DEFS:()=>{svgInDefs=!1},USE:popGroup,G:popGroup,undefined:()=>{}},elementName=node.name.toUpperCase(),obj=objMap[elementName]?objMap[elementName]():void 0;0===svgGroups.length&&(svgObj=obj)})),parser.on("end",(()=>{})),parser.write(src).close(),parser},mimeType="image/svg+xml";export{deserialize,mimeType}; diff --git a/packages/io/svg-deserializer/dist/jscad-svg-deserializer.min.js b/packages/io/svg-deserializer/dist/jscad-svg-deserializer.min.js index 5e2bae78d..abcfd58b8 100644 --- a/packages/io/svg-deserializer/dist/jscad-svg-deserializer.min.js +++ b/packages/io/svg-deserializer/dist/jscad-svg-deserializer.min.js @@ -1,7 +1,7 @@ /** * SVG Deserializer for JSCAD * @module @jscad/svg-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ var global,factory;global=this,factory=function(exports){var saxes={},ed5$1={};!function(exports){function isNameStartChar(c){return c>=65&&c<=90||c>=97&&c<=122||58===c||95===c||8204===c||8205===c||c>=192&&c<=214||c>=216&&c<=246||c>=248&&c<=767||c>=880&&c<=893||c>=895&&c<=8191||c>=8304&&c<=8591||c>=11264&&c<=12271||c>=12289&&c<=55295||c>=63744&&c<=64975||c>=65008&&c<=65533||c>=65536&&c<=983039} @@ -32,7 +32,7 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.NC_NAME_START_CHA /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),clone$b=geometry=>Object.assign({},geometry),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation=(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply$1=(out,a,b)=>{const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:fromScaling,fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:mirrorByPlane,multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromNormalAndPoint=(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:fromNormalAndPoint,fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints$1=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints$1(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints$1,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");if(3===color.length&&(color=[color[0],color[1],color[2],1]),0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):(object.color=color,object)));return 1===results.length?results[0]:results},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},rectangle=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])},mirror=(options,...objects)=>{const{origin:origin,normal:normal}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},options);if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const planeOfMirror=fromNormalAndPoint([0,0,0,0],normal,origin);if(Number.isNaN(planeOfMirror[0]))throw new Error("the given origin and normal do not define a proper plane");const matrix=mirrorByPlane([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],planeOfMirror),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},mirrorX=(...objects)=>mirror({normal:[1,0,0]},objects),mirrorY=(...objects)=>mirror({normal:[0,1,0]},objects),rotateZ=(angle,...objects)=>((angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results})([0,0,angle],objects),translate=(offset,...objects)=>{if(!Array.isArray(offset))throw new Error("offset must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(offset=offset.slice();offset.length<3;)offset.push(0);const matrix=fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offset),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},scale=(factors,...objects)=>{if(!Array.isArray(factors))throw new Error("factors must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(factors=factors.slice();factors.length<3;)factors.push(1);if(factors[0]<=0||factors[1]<=0||factors[2]<=0)throw new Error("factors must be positive");const matrix=fromScaling([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],factors),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},pxPmm=1/.2822222,svgColors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},svg2cag=(vec,svgUnitsPmm)=>[vec[0]/svgUnitsPmm[0],0-vec[1]/svgUnitsPmm[1]],cagLengthX=(css,svgUnitsPmm,svgUnitsX)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[0]);let v=parseFloat(css);return isNaN(v)?0:0===v?v:(v=v/100*svgUnitsX,v/=svgUnitsPmm[0],Math.round(1e5*v)/1e5)},cagLengthY=(css,svgUnitsPmm,svgUnitsY)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[1]);let v=parseFloat(css);return isNaN(v)?0:0===v?v:(v=v/100*svgUnitsY,v/=svgUnitsPmm[1],Math.round(1e5*v)/1e5)},cagLengthP=(css,svgUnitsPmm,svgUnitsV)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[1]);let v=parseFloat(css);return isNaN(v)?0:(0===v||(v=v/100*svgUnitsV,v/=svgUnitsPmm[0]),v)},css2cag=(css,unit)=>{let v=parseFloat(css);return isNaN(v)?0:(0===v||css.search(/EM/i)>0||css.search(/EX/i)>0||css.search(/MM/i)>0||(css.search(/CM/i)>0?v*=10:css.search(/IN/i)>0?v/=.03937:css.search(/PT/i)>0?v/=2.8346400000000003:css.search(/PC/i)>0?v/=.23622:v/=unit),v)},cagColor=value=>{let rgb;if((value=value.toLowerCase())in svgColors)rgb=svgColors[value],rgb=[rgb[0]/255,rgb[1]/255,rgb[2]/255];else if("#"===value[0])4===value.length&&(value="#"+value[1]+value[1]+value[2]+value[2]+value[3]+value[3]),7===value.length&&(rgb=[parseInt("0x"+value.slice(1,3))/255,parseInt("0x"+value.slice(3,5))/255,parseInt("0x"+value.slice(5,7))/255]);else{let s=/rgb\(.+,.+,.+\)/.exec(value);null!==s&&(s=s[0],s=s.slice(s.indexOf("(")+1,s.indexOf(")")),rgb=s.split(","),s.indexOf("%")>0?(rgb=[parseInt(rgb[0]),parseInt(rgb[1]),parseInt(rgb[2])],rgb=[rgb[0]/100,rgb[1]/100,rgb[2]/100]):(rgb=[parseInt(rgb[0]),parseInt(rgb[1]),parseInt(rgb[2])],rgb=[rgb[0]/255,rgb[1]/255,rgb[2]/255]))}return rgb},cssStyle=(element,name)=>{if("style"in element){const list=element.style+";";let v=new RegExp(name+"\\s*:\\s*(\\S+);","i").exec(list);if(null!==v){v=v[0];let i=v.indexOf(":")+1;for(;" "===v[i];)i++;return v=v.slice(i,v.indexOf(";")),v}}},reflect=(x,y,px,py)=>{const ox=x-px,oy=y-py;return x===px&&y===px?[x,y]:x===px?[x,py+-oy]:y===py?[px+-ox,y]:[px+-ox,py+-oy]},svgColorForTarget=(target,svgObject)=>{let color=null;return"path"===target?svgObject.stroke?color=[svgObject.stroke[0],svgObject.stroke[1],svgObject.stroke[2],1]:svgObject.fill&&(color=[svgObject.fill[0],svgObject.fill[1],svgObject.fill[2],1]):svgObject.fill?color=[svgObject.fill[0],svgObject.fill[1],svgObject.fill[2],1]:svgObject.stroke&&(color=[svgObject.stroke[0],svgObject.stroke[1],svgObject.stroke[2],1]),color},svgCore=(obj,element)=>{"id"in element&&(obj.id=element.id),"position"in element&&(obj.position=element.position)},svgPresentation=(obj,element)=>{if("display"in element&&(obj.visible=element.display),"color"in element&&(obj.fill=cagColor(element.color),obj.stroke=obj.fill),"opacity"in element&&(obj.opacity=element.opacity),"fill"in element)obj.fill=cagColor(element.fill);else{const s=cssStyle(element,"fill");s&&(obj.fill=cagColor(s))}if("fill-opacity"in element&&(obj.opacity=element["fill-opacity"]),"stroke-width"in element)obj.strokeWidth=element["stroke-width"];else{const sw=cssStyle(element,"stroke-width");sw&&(obj.strokeWidth=sw)}if("stroke"in element)obj.stroke=cagColor(element.stroke);else{const s=cssStyle(element,"stroke");s&&(obj.stroke=cagColor(s))}"stroke-opacity"in element&&(obj.strokeOpacity=element["stroke-opacity"])},svgTransformsRegExp=/\w+\(.+\)/i,svgTransforms=(cag,element)=>{let list=null;if("transform"in element)list=element.transform;else{const s=cssStyle(element,"transform");s&&(list=s)}if(null!==list){cag.transforms=[];let v=svgTransformsRegExp.exec(list);for(;null!==v;){const s=svgTransformsRegExp.lastIndex,e=list.indexOf(")")+1;let t=list.slice(s,e);t=t.trim();const n=t.slice(0,t.indexOf("("));let o,a=t.slice(t.indexOf("(")+1,t.indexOf(")")).trim();switch(a=a.indexOf(",")>0?a.split(","):a.split(" "),n){case"translate":1===a.length&&a.push(0),o={translate:[a[0],a[1]]},cag.transforms.push(o);break;case"scale":1===a.length&&a.push(a[0]),o={scale:[a[0],a[1]]},cag.transforms.push(o);break;case"rotate":o={rotate:a},cag.transforms.push(o)}list=list.slice(e,list.length),v=svgTransformsRegExp.exec(list)}}},viewBoxRegExp=/([\d.-]+)[\s,]+([\d.-]+)[\s,]+([\d.-]+)[\s,]+([\d.-]+)/i,svgSvg=(element,{customPxPmm:customPxPmm})=>{const obj={type:"svg",x:0,y:0,width:"100%",height:"100%",strokeWidth:"1"};if(obj.unitsPmm=[pxPmm,pxPmm],"pxpmm"in element&&(obj.pxPmm=element.pxpmm,obj.unitsPmm=[obj.pxPmm,obj.pxPmm]),"width"in element&&(obj.width=element.width),"height"in element&&(obj.height=element.height),"viewBox"in element){const list=element.viewBox.trim(),v=viewBoxRegExp.exec(list);if(null!==v&&(obj.viewX=parseFloat(v[1]),obj.viewY=parseFloat(v[2]),obj.viewW=parseFloat(v[3]),obj.viewH=parseFloat(v[4])),obj.width.indexOf("%")<0){let s=css2cag(obj.width,customPxPmm);s=obj.viewW/s,obj.unitsPmm[0]=s}else{const u=obj.unitsPmm[0]*(parseFloat(obj.width)/100);obj.unitsPmm[0]=u}if(obj.height.indexOf("%")<0){let s=css2cag(obj.height,pxPmm);s=obj.viewH/s,obj.unitsPmm[1]=s}else{const u=obj.unitsPmm[1]*(parseFloat(obj.height)/100);obj.unitsPmm[1]=u}}else obj.viewX=0,obj.viewY=0,obj.viewW=1920/obj.unitsPmm[0],obj.viewH=1080/obj.unitsPmm[1];return obj.viewP=Math.sqrt(obj.viewW*obj.viewW+obj.viewH*obj.viewH)/Math.SQRT2,svgCore(obj,element),svgPresentation(obj,element),obj.objects=[],obj},svgEllipse=element=>{const obj={type:"ellipse",cx:"0",cy:"0",rx:"0",ry:"0"};return"cx"in element&&(obj.cx=element.cx),"cy"in element&&(obj.cy=element.cy),"rx"in element&&(obj.rx=element.rx),"ry"in element&&(obj.ry=element.ry),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgLine=element=>{const obj={type:"line",x1:"0",y1:"0",x2:"0",y2:"0"};return"x1"in element&&(obj.x1=element.x1),"y1"in element&&(obj.y1=element.y1),"x2"in element&&(obj.x2=element.x2),"y2"in element&&(obj.y2=element.y2),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgListOfPoints=list=>{const points=[],exp=/([\d\-+.]+)[\s,]+([\d\-+.]+)[\s,]*/i;list=list.trim();let v=exp.exec(list);for(;null!==v;){let point=v[0];const next=exp.lastIndex+point.length;point={x:v[1],y:v[2]},points.push(point),list=list.slice(next,list.length),v=exp.exec(list)}return points},svgPolyline=element=>{const obj={type:"polyline"};return svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"points"in element&&(obj.points=svgListOfPoints(element.points)),obj},svgPolygon=element=>{const obj={type:"polygon"};return svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"points"in element&&(obj.points=svgListOfPoints(element.points)),obj},svgRect=element=>{const obj={type:"rect",x:"0",y:"0",rx:"0",ry:"0",width:"0",height:"0"};return"x"in element&&(obj.x=element.x),"y"in element&&(obj.y=element.y),"rx"in element&&(obj.rx=element.rx,"ry"in element||(obj.ry=obj.rx)),"ry"in element&&(obj.ry=element.ry,"rx"in element||(obj.rx=obj.ry)),obj.rx!==obj.ry&&console.log("Warning: Unsupported RECT with rx and ry radius"),"width"in element&&(obj.width=element.width),"height"in element&&(obj.height=element.height),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgCircle=element=>{const obj={type:"circle",x:"0",y:"0",radius:"0"};return"cx"in element&&(obj.x=element.cx),"cy"in element&&(obj.y=element.cy),"r"in element&&(obj.radius=element.r),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgGroup=element=>{const obj={type:"group"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"x"in element||"y"in element){let x="0",y="0";"x"in element&&(x=element.x),"y"in element&&(y=element.y),"transforms"in obj||(obj.transforms=[]);const o={translate:[x,y]};obj.transforms.push(o)}return obj.objects=[],obj},svgPath=element=>{const obj={type:"path"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj.commands=[],"d"in element){let co=null,bf="",i=0;const l=element.d.length,offset=element.position[1]-l-2;for(;i0&&(co.p.push(bf),bf=""),bf+=c;break;case".":bf.length>0&&bf.indexOf(".")>=0&&(co.p.push(bf),bf=""),bf+=c;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":bf+=c;break;case"a":case"A":case"c":case"C":case"h":case"H":case"l":case"L":case"v":case"V":case"m":case"M":case"q":case"Q":case"s":case"S":case"t":case"T":case"z":case"Z":null!==co&&(bf.length>0&&(co.p.push(bf),bf=""),obj.commands.push(co)),co={c:c,p:[],pos:i+offset};break;case",":case" ":case"\n":null!==co&&bf.length>0&&(co.p.push(bf),bf="")}i++}i===l&&null!==co&&(bf.length>0&&co.p.push(bf),obj.commands.push(co))}return obj},svgUse=(element,{svgObjects:svgObjects})=>{const obj={type:"group"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"x"in element||"y"in element){let x="0",y="0";"x"in element&&(x=element.x),"y"in element&&(y=element.y),"transforms"in obj||(obj.transforms=[]);const o={translate:[x,y]};obj.transforms.push(o)}if(obj.objects=[],"xlink:href"in element){let ref=element["xlink:href"];"#"===ref[0]&&(ref=ref.slice(1,ref.length)),void 0!==svgObjects[ref]&&(ref=svgObjects[ref],ref=JSON.parse(JSON.stringify(ref)),obj.objects.push(ref))}return obj},shapesMapGeometry=(obj,objectify,params)=>{const{svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,svgGroups:svgGroups,target:target,segments:segments,pathSelfClosed:pathSelfClosed}=params,types={group:obj=>objectify({target:target,segments:segments},obj),rect:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{let x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY);const w=cagLengthX(obj.width,svgUnitsPmm,svgUnitsX),h=cagLengthY(obj.height,svgUnitsPmm,svgUnitsY),rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX);let shape;return w>0&&h>0&&(x+=w/2,y-=h/2,shape=0===rx?rectangle({center:[x,y],size:[w,h]}):(options=>{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1])return create$a();if(0===roundRadius)return rectangle({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS)throw new Error("roundRadius must be smaller then the radius of all dimensions");const cornerSegments=Math.floor(segments/4),corner0=add([0,0],center,[size[0]-roundRadius,size[1]-roundRadius]),corner1=add([0,0],center,[roundRadius-size[0],size[1]-roundRadius]),corner2=add([0,0],center,[roundRadius-size[0],roundRadius-size[1]]),corner3=add([0,0],center,[size[0]-roundRadius,roundRadius-size[1]]),corner0Points=[],corner1Points=[],corner2Points=[],corner3Points=[];for(let i=0;i<=cornerSegments;i++){const point=fromAngleRadians([0,0],TAU/4*i/cornerSegments);scale$1(point,point,roundRadius),corner0Points.push(add([0,0],corner0,point)),rotate$1(point,point,[0,0],TAU/4),corner1Points.push(add([0,0],corner1,point)),rotate$1(point,point,[0,0],TAU/4),corner2Points.push(add([0,0],corner2,point)),rotate$1(point,point,[0,0],TAU/4),corner3Points.push(add([0,0],corner3,point))}const points=corner0Points.concat(corner1Points,corner2Points,corner3Points);return create$a([points])})({center:[x,y],segments:segments,size:[w,h],roundRadius:rx}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},circle:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{const x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY),r=cagLengthP(obj.radius,svgUnitsPmm,svgUnitsV);let shape;return r>0&&(shape=(options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})})({center:[x,y],segments:segments,radius:r}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},ellipse:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{const rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX),ry=cagLengthY(obj.ry,svgUnitsPmm,svgUnitsY),cx=cagLengthX(obj.cx,svgUnitsPmm,svgUnitsX),cy=0-cagLengthY(obj.cy,svgUnitsPmm,svgUnitsY);let shape;return rx>0&&ry>0&&(shape=ellipse({center:[cx,cy],segments:segments,radius:[rx,ry]}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},line:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV)=>{const x1=cagLengthX(obj.x1,svgUnitsPmm,svgUnitsX),y1=0-cagLengthY(obj.y1,svgUnitsPmm,svgUnitsY),x2=cagLengthX(obj.x2,svgUnitsPmm,svgUnitsX),y2=0-cagLengthY(obj.y2,svgUnitsPmm,svgUnitsY);return line([[x1,y1],[x2,y2]])},polygon:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY)=>{const points=[];for(let j=0;j{const points=[];for(let j=0;j{const listofpaths=expandPath(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments,pathSelfClosed),shapes=Object.entries(listofpaths).sort(((a,b)=>a[0].localeCompare(b[0]))).map((entry=>{const path=entry[1];if("geom2"===target&&path.isClosed){const points=index$5.toPoints(path);return index$a.create([points])}return path}));return shapes}};return types[obj.type](obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)},appendPoints=(points,geometry)=>geometry?index$5.appendPoints(points,geometry):index$5.fromPoints({},points),expandPath=(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments,pathSelfClosed)=>{const paths={};let sx=0,sy=0,cx=0,cy=0,pi=0,pathName="path"+pi,pc=!1,bx=0,by=0,qx=0,qy=0;const newPath=()=>{pi++,pathName="path"+pi,pc=!1},ensurePath=()=>{paths[pathName]||(paths[pathName]=index$5.fromPoints({},[]))};for(let j=0;j=i+2&&(cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),newPath(),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)]),sx=cx,sy=cy);pts.length>=i+2;)cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"M":for(pts.length>=i+2&&(cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),newPath(),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)]),sx=cx,sy=cy);pts.length>=i+2;)cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"a":for(;pts.length>=i+7;){const rx=parseFloat(pts[i++]),ry=parseFloat(pts[i++]),ro=0-.017453292519943295*parseFloat(pts[i++]),lf="1"===pts[i++],sf="1"===pts[i++];cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendArc({segments:segments,endpoint:svg2cag([cx,cy],svgUnitsPmm),radius:svg2cag([rx,ry],svgUnitsPmm),xaxisrotation:ro,clockwise:sf,large:lf},paths[pathName])}break;case"A":for(;pts.length>=i+7;){const rx=parseFloat(pts[i++]),ry=parseFloat(pts[i++]),ro=0-.017453292519943295*parseFloat(pts[i++]),lf="1"===pts[i++],sf="1"===pts[i++];cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendArc({segments:segments,endpoint:svg2cag([cx,cy],svgUnitsPmm),radius:svg2cag([rx,ry],svgUnitsPmm),xaxisrotation:ro,clockwise:sf,large:lf},paths[pathName])}break;case"c":for(;pts.length>=i+6;){const x1=cx+parseFloat(pts[i++]),y1=cy+parseFloat(pts[i++]);bx=cx+parseFloat(pts[i++]),by=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"C":for(;pts.length>=i+6;){const x1=parseFloat(pts[i++]),y1=parseFloat(pts[i++]);bx=parseFloat(pts[i++]),by=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"q":for(;pts.length>=i+4;){const p0=[cx,cy];qx=cx+parseFloat(pts[i++]),qy=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"Q":for(;pts.length>=i+4;){const p0=[cx,cy];qx=parseFloat(pts[i++]),qy=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"t":for(;pts.length>=i+2;){const p0=[cx,cy];cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"T":for(;pts.length>=i+2;){const p0=[cx,cy];cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"s":for(;pts.length>=i+4;){const x1=bx,y1=by;bx=cx+parseFloat(pts[i++]),by=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"S":for(;pts.length>=i+4;){const x1=bx,y1=by;bx=parseFloat(pts[i++]),by=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"h":for(;pts.length>=i+1;)cx+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"H":for(;pts.length>=i+1;)cx=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"l":for(;pts.length>=i+2;)cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"L":for(;pts.length>=i+2;)cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"v":for(;pts.length>=i+1;)cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"V":for(;pts.length>=i+1;)cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"z":case"Z":paths[pathName]=index$5.close(paths[pathName]),cx=sx,cy=sy,pc=!0;break;default:console.log("Warning: Unknown PATH command ["+co.c+"]")}const isCloseCmd=cmd=>"z"===cmd||"Z"===cmd;if(!0!==pc&&paths[pathName]&&paths[pathName].isClosed){let coNext=obj.commands[j+1];if(coNext&&!isCloseCmd(coNext.c))if("trim"===pathSelfClosed)for(;coNext&&!isCloseCmd(coNext.c);)j++,coNext=obj.commands[j+1];else{if("split"!==pathSelfClosed)throw new Error(`Malformed svg path at ${obj.position[0]}:${co.pos}. Path closed itself with command #${j} ${co.c}${pts.join(" ")}`);newPath()}}}return paths},shapesMapJscad=(obj,codify,params)=>{const{level:level,indent:indent,on:on,svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,svgGroups:svgGroups,target:target,segments:segments}=params,types={group:obj=>{let code=codify({target:target,segments:segments},obj);return code+=`${indent}${on} = levels.l${level+1}\n`,code},rect:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{let x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY);const w=cagLengthX(obj.width,svgUnitsPmm,svgUnitsX),h=cagLengthY(obj.height,svgUnitsPmm,svgUnitsY),rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX);let code;return w>0&&h>0&&(x=(x+w/2).toFixed(4),y=(y-h/2).toFixed(4),code=0===rx?`${indent}${on} = rectangle({center: [${x}, ${y}], size: [${w}, ${h}]}) // line ${obj.position}\n`:`${indent}${on} = roundedRectangle({center: [${x}, ${y}], segments: ${segments}, size: [${w}, ${h}], roundRadius: ${rx}}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},circle:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{const x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY),r=cagLengthP(obj.radius,svgUnitsPmm,svgUnitsV);let code;return r>0&&(code=`${indent}${on} = circle({center: [${x}, ${y}], segments: ${segments}, radius: ${r}}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},ellipse:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{const rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX),ry=cagLengthY(obj.ry,svgUnitsPmm,svgUnitsY),cx=cagLengthX(obj.cx,svgUnitsPmm,svgUnitsX),cy=0-cagLengthY(obj.cy,svgUnitsPmm,svgUnitsY);let code;return rx>0&&ry>0&&(code=`${indent}${on} = ellipse({center: [${cx}, ${cy}], segments: ${segments}, radius: [${rx}, ${ry}]}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},line:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV)=>{const x1=cagLengthX(obj.x1,svgUnitsPmm,svgUnitsX),y1=0-cagLengthY(obj.y1,svgUnitsPmm,svgUnitsY),x2=cagLengthX(obj.x2,svgUnitsPmm,svgUnitsX),y2=0-cagLengthY(obj.y2,svgUnitsPmm,svgUnitsY);return`${indent}${on} = line([[${x1}, ${y1}], [${x2}, ${y2}]]) // line ${obj.position}\n`},polygon:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY)=>{let code=`${indent}${on} = polygon({points: [\n`;for(let j=0;j{let code=`${indent}${on} = path2.fromPoints({}, [\n`;for(let j=0;j{const{indent:indent,on:on,target:target}=params;let tmpCode=`${indent}parts = [] // line ${obj.position}\n`,sx=0,sy=0,cx=0,cy=0,pi=0,pathName=on+pi,pc=!1,bx=0,by=0,qx=0,qy=0;for(let j=0;j0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),pts.length>=2&&(cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),pi++,pc=!1,pathName=on+pi,tmpCode+=`${indent}${pathName} = path2.fromPoints({}, [[${svg2cag([cx,cy],svgUnitsPmm)}]])\n`,sx=cx,sy=cy);pts.length>=2;)cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([${svg2cag([cx,cy],svgUnitsPmm)}], ${pathName})\n`;break;case"M":for(pi>0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),pts.length>=2&&(cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),pi++,pc=!1,pathName=on+pi,tmpCode+=`${indent}${pathName} = path2.fromPoints({}, [[${svg2cag([cx,cy],svgUnitsPmm)}]])\n`,sx=cx,sy=cy);pts.length>=2;)cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([${svg2cag([cx,cy],svgUnitsPmm)}], ${pathName})\n`;break;case"a":for(;pts.length>=7;){const rx=parseFloat(pts.shift()),ry=parseFloat(pts.shift()),ro=0-.017453292519943295*parseFloat(pts.shift()),lf="1"===pts.shift(),sf="1"===pts.shift();cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendArc({segments: ${segments}, endpoint: [${svg2cag([cx,cy],svgUnitsPmm)}], radius: [${svg2cag([rx,ry],svgUnitsPmm)}], xaxisrotation: ${ro}, clockwise: ${sf}, large: ${lf}}, ${pathName})\n`}break;case"A":for(;pts.length>=7;){const rx=parseFloat(pts.shift()),ry=parseFloat(pts.shift()),ro=0-.017453292519943295*parseFloat(pts.shift()),lf="1"===pts.shift(),sf="1"===pts.shift();cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendArc({segments: ${segments}, endpoint: [${svg2cag([cx,cy],svgUnitsPmm)}], radius: [${svg2cag([rx,ry],svgUnitsPmm)}], xaxisrotation: ${ro}, clockwise: ${sf}, large: ${lf}}, ${pathName})\n`}break;case"c":for(;pts.length>=6;){const x1=cx+parseFloat(pts.shift()),y1=cy+parseFloat(pts.shift());bx=cx+parseFloat(pts.shift()),by=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"C":for(;pts.length>=6;){const x1=parseFloat(pts.shift()),y1=parseFloat(pts.shift());bx=parseFloat(pts.shift()),by=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"q":for(;pts.length>=4;){const p0=[cx,cy];qx=cx+parseFloat(pts.shift()),qy=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"Q":for(;pts.length>=4;){const p0=[cx,cy];qx=parseFloat(pts.shift()),qy=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"t":for(;pts.length>=2;){const p0=[cx,cy];cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"T":for(;pts.length>=2;){const p0=[cx,cy];cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"s":for(;pts.length>=4;){const x1=bx,y1=by;bx=cx+parseFloat(pts.shift()),by=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"S":for(;pts.length>=4;){const x1=bx,y1=by;bx=parseFloat(pts.shift()),by=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"h":for(;pts.length>=1;)cx+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"H":for(;pts.length>=1;)cx=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"l":for(;pts.length>=2;)cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"L":for(;pts.length>=2;)cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"v":for(;pts.length>=1;)cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"V":for(;pts.length>=1;)cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"z":case"Z":tmpCode+=`${indent}${pathName} = path2.close(${pathName})\n`,"geom2"===target&&(tmpCode+=`${indent}${pathName} = geom2.create([path2.toPoints(${pathName})])\n`),tmpCode+=`${indent}parts.push(${pathName})\n`,cx=sx,cy=sy,pc=!0;break;default:console.log("Warning: Unknow PATH command ["+co.c+"]")}}return pi>0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),tmpCode+=`${indent}${on} = parts\n`,tmpCode},instantiate=(src,options)=>{const{pxPmm:pxPmm}=options;if(options&&options.statusCallback&&options.statusCallback({progress:0}),createSvgParser(src,pxPmm),!svgObj)throw new Error("SVG parsing failed, no valid SVG data retrieved");options&&options.statusCallback&&options.statusCallback({progress:50});const result=objectify(options,svgObj);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},translateScript=(src,options)=>{const{filename:filename,version:version,pxPmm:pxPmm,addMetaData:addMetaData}=options;if(options&&options.statusCallback&&options.statusCallback({progress:0}),createSvgParser(src,pxPmm),!svgObj)throw new Error("SVG parsing failed, no valid SVG data retrieved");let code=addMetaData?`//\n // producer: JSCAD SVG Deserializer ${version}\n // date: ${new Date}\n // source: ${filename}\n //\n`:"";return code+="const { colors, geometries, primitives, transforms } = require('@jscad/modeling')\n\n",options&&options.statusCallback&&options.statusCallback({progress:50}),code+=codify(options,svgObj),code+="\nmodule.exports = { main }",options&&options.statusCallback&&options.statusCallback({progress:100}),code};let svgUnitsX,svgUnitsY,svgUnitsV;const svgObjects=[],svgGroups=[],svgDefs=[];let svgObj,svgInDefs=!1,svgUnitsPmm=[1,1];const objectify=(options,group)=>{const{target:target,segments:segments,pathSelfClosed:pathSelfClosed}=options,level=svgGroups.length;svgGroups.push(group);let i=level;for(;i>0;)i--;let geometries=[];const params={svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,level:level,target:target,svgGroups:svgGroups,segments:segments,pathSelfClosed:pathSelfClosed};for(i=0;i{if("transforms"in obj){let rotateAttribute=null,scaleAttribute=null,translateAttribute=null;for(let j=0;j{const{target:target,segments:segments}=options,level=svgGroups.length;svgGroups.push(group);let indent=" ",i=level;for(;i>0;)indent+=" ",i--;let code="";0===level&&(code+="function main(params) {\n let levels = {}\n let paths = {}\n let parts\n");const ln="levels.l"+level;for(code+=`${indent}${ln} = []\n`,i=0;i{const parser=new saxes.SaxesParser;return void 0!==pxPmm&&pxPmm>parser.pxPmm&&(parser.pxPmm=pxPmm),parser.on("error",(e=>{console.log(`ERROR: SVG file, line ${parser.line}, column ${parser.column}`),console.log(e)})),parser.on("opentag",(node=>{const objMap={SVG:svgSvg,G:svgGroup,RECT:svgRect,CIRCLE:svgCircle,ELLIPSE:svgEllipse,LINE:svgLine,POLYLINE:svgPolyline,POLYGON:svgPolygon,PATH:svgPath,USE:svgUse,DEFS:()=>{svgInDefs=!0},DESC:()=>{},TITLE:()=>{},STYLE:()=>{},undefined:()=>console.log("WARNING: unsupported SVG element: "+node.name)};node.attributes.position=[parser.line+1,parser.column+1];const elementName=node.name.toUpperCase(),obj=objMap[elementName]?objMap[elementName](node.attributes,{svgObjects:svgObjects,customPxPmm:pxPmm}):void 0;if(obj)if("id"in obj&&(svgObjects[obj.id]=obj),"svg"===obj.type)svgGroups.push(obj),svgUnitsPmm=obj.unitsPmm,svgUnitsX=obj.viewW,svgUnitsY=obj.viewH,svgUnitsV=obj.viewP;else if(!0===svgInDefs){if(svgDefs.length>0){const group=svgDefs.pop();"objects"in group&&group.objects.push(obj),svgDefs.push(group)}"group"===obj.type&&svgDefs.push(obj)}else{if(svgGroups.length>0){const group=svgGroups.pop();"objects"in group&&group.objects.push(obj),svgGroups.push(group)}"group"===obj.type&&svgGroups.push(obj)}})),parser.on("closetag",(node=>{const popGroup=()=>!0===svgInDefs?svgDefs.pop():svgGroups.pop(),objMap={SVG:popGroup,DEFS:()=>{svgInDefs=!1},USE:popGroup,G:popGroup,undefined:()=>{}},elementName=node.name.toUpperCase(),obj=objMap[elementName]?objMap[elementName]():void 0;0===svgGroups.length&&(svgObj=obj)})),parser.on("end",(()=>{})),parser.write(src).close(),parser};exports.deserialize=(options,input)=>{const defaults={addMetaData:!0,filename:"svg",output:"script",pxPmm:pxPmm,segments:32,target:"path",pathSelfClosed:"error",version:"3.0.0-alpha.0"};return"script"===(options=Object.assign({},defaults,options)).output?translateScript(input,options):instantiate(input,options)},exports.mimeType="image/svg+xml",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadSvgDeserializer={}); +const clone$b=geometry=>Object.assign({},geometry),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation=(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply$1=(out,a,b)=>{const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:fromScaling,fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:mirrorByPlane,multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromNormalAndPoint=(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:fromNormalAndPoint,fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints$1=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints$1(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints$1,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");3===color.length&&(color=[color[0],color[1],color[2],1]);const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):Array.isArray(object)?colorize(color,...object):(object.color=color,object)));return 1===results.length?results[0]:results},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},rectangle=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])},mirror=(options,...objects)=>{const{origin:origin,normal:normal}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},options),planeOfMirror=fromNormalAndPoint([0,0,0,0],normal,origin);if(Number.isNaN(planeOfMirror[0]))throw new Error("the given origin and normal do not define a proper plane");const matrix=mirrorByPlane([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],planeOfMirror),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?mirror(options,...object):object));return 1===results.length?results[0]:results},mirrorX=(...objects)=>mirror({normal:[1,0,0]},...objects),mirrorY=(...objects)=>mirror({normal:[0,1,0]},...objects),rotate=(angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?rotate(angles,...object):object));return 1===results.length?results[0]:results},rotateZ=(angle,...objects)=>rotate([0,0,angle],...objects),translate=(offset,...objects)=>{if(!Array.isArray(offset))throw new Error("offset must be an array");for(offset=offset.slice();offset.length<3;)offset.push(0);const matrix=fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offset),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?translate(offset,...object):object));return 1===results.length?results[0]:results},scale=(factors,...objects)=>{if(!Array.isArray(factors))throw new Error("factors must be an array");for(factors=factors.slice();factors.length<3;)factors.push(1);if(factors[0]<=0||factors[1]<=0||factors[2]<=0)throw new Error("factors must be positive");const matrix=fromScaling([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],factors),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?scale(factors,...object):object));return 1===results.length?results[0]:results},pxPmm=1/.2822222,svgColors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},svg2cag=(vec,svgUnitsPmm)=>[vec[0]/svgUnitsPmm[0],0-vec[1]/svgUnitsPmm[1]],cagLengthX=(css,svgUnitsPmm,svgUnitsX)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[0]);let v=parseFloat(css);return isNaN(v)?0:0===v?v:(v=v/100*svgUnitsX,v/=svgUnitsPmm[0],Math.round(1e5*v)/1e5)},cagLengthY=(css,svgUnitsPmm,svgUnitsY)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[1]);let v=parseFloat(css);return isNaN(v)?0:0===v?v:(v=v/100*svgUnitsY,v/=svgUnitsPmm[1],Math.round(1e5*v)/1e5)},cagLengthP=(css,svgUnitsPmm,svgUnitsV)=>{if(css.indexOf("%")<0)return css2cag(css,svgUnitsPmm[1]);let v=parseFloat(css);return isNaN(v)?0:(0===v||(v=v/100*svgUnitsV,v/=svgUnitsPmm[0]),v)},css2cag=(css,unit)=>{let v=parseFloat(css);return isNaN(v)?0:(0===v||css.search(/EM/i)>0||css.search(/EX/i)>0||css.search(/MM/i)>0||(css.search(/CM/i)>0?v*=10:css.search(/IN/i)>0?v/=.03937:css.search(/PT/i)>0?v/=2.8346400000000003:css.search(/PC/i)>0?v/=.23622:v/=unit),v)},cagColor=value=>{let rgb;if((value=value.toLowerCase())in svgColors)rgb=svgColors[value],rgb=[rgb[0]/255,rgb[1]/255,rgb[2]/255];else if("#"===value[0])4===value.length&&(value="#"+value[1]+value[1]+value[2]+value[2]+value[3]+value[3]),7===value.length&&(rgb=[parseInt("0x"+value.slice(1,3))/255,parseInt("0x"+value.slice(3,5))/255,parseInt("0x"+value.slice(5,7))/255]);else{let s=/rgb\(.+,.+,.+\)/.exec(value);null!==s&&(s=s[0],s=s.slice(s.indexOf("(")+1,s.indexOf(")")),rgb=s.split(","),s.indexOf("%")>0?(rgb=[parseInt(rgb[0]),parseInt(rgb[1]),parseInt(rgb[2])],rgb=[rgb[0]/100,rgb[1]/100,rgb[2]/100]):(rgb=[parseInt(rgb[0]),parseInt(rgb[1]),parseInt(rgb[2])],rgb=[rgb[0]/255,rgb[1]/255,rgb[2]/255]))}return rgb},cssStyle=(element,name)=>{if("style"in element){const list=element.style+";";let v=new RegExp(name+"\\s*:\\s*(\\S+);","i").exec(list);if(null!==v){v=v[0];let i=v.indexOf(":")+1;for(;" "===v[i];)i++;return v=v.slice(i,v.indexOf(";")),v}}},reflect=(x,y,px,py)=>{const ox=x-px,oy=y-py;return x===px&&y===px?[x,y]:x===px?[x,py+-oy]:y===py?[px+-ox,y]:[px+-ox,py+-oy]},svgColorForTarget=(target,svgObject)=>{let color=null;return"path"===target?svgObject.stroke?color=[svgObject.stroke[0],svgObject.stroke[1],svgObject.stroke[2],1]:svgObject.fill&&(color=[svgObject.fill[0],svgObject.fill[1],svgObject.fill[2],1]):svgObject.fill?color=[svgObject.fill[0],svgObject.fill[1],svgObject.fill[2],1]:svgObject.stroke&&(color=[svgObject.stroke[0],svgObject.stroke[1],svgObject.stroke[2],1]),color},svgCore=(obj,element)=>{"id"in element&&(obj.id=element.id),"position"in element&&(obj.position=element.position)},svgPresentation=(obj,element)=>{if("display"in element&&(obj.visible=element.display),"color"in element&&(obj.fill=cagColor(element.color),obj.stroke=obj.fill),"opacity"in element&&(obj.opacity=element.opacity),"fill"in element)obj.fill=cagColor(element.fill);else{const s=cssStyle(element,"fill");s&&(obj.fill=cagColor(s))}if("fill-opacity"in element&&(obj.opacity=element["fill-opacity"]),"stroke-width"in element)obj.strokeWidth=element["stroke-width"];else{const sw=cssStyle(element,"stroke-width");sw&&(obj.strokeWidth=sw)}if("stroke"in element)obj.stroke=cagColor(element.stroke);else{const s=cssStyle(element,"stroke");s&&(obj.stroke=cagColor(s))}"stroke-opacity"in element&&(obj.strokeOpacity=element["stroke-opacity"])},svgTransformsRegExp=/\w+\(.+\)/i,svgTransforms=(cag,element)=>{let list=null;if("transform"in element)list=element.transform;else{const s=cssStyle(element,"transform");s&&(list=s)}if(null!==list){cag.transforms=[];let v=svgTransformsRegExp.exec(list);for(;null!==v;){const s=svgTransformsRegExp.lastIndex,e=list.indexOf(")")+1;let t=list.slice(s,e);t=t.trim();const n=t.slice(0,t.indexOf("("));let o,a=t.slice(t.indexOf("(")+1,t.indexOf(")")).trim();switch(a=a.indexOf(",")>0?a.split(","):a.split(" "),n){case"translate":1===a.length&&a.push(0),o={translate:[a[0],a[1]]},cag.transforms.push(o);break;case"scale":1===a.length&&a.push(a[0]),o={scale:[a[0],a[1]]},cag.transforms.push(o);break;case"rotate":o={rotate:a},cag.transforms.push(o)}list=list.slice(e,list.length),v=svgTransformsRegExp.exec(list)}}},viewBoxRegExp=/([\d.-]+)[\s,]+([\d.-]+)[\s,]+([\d.-]+)[\s,]+([\d.-]+)/i,svgSvg=(element,{customPxPmm:customPxPmm})=>{const obj={type:"svg",x:0,y:0,width:"100%",height:"100%",strokeWidth:"1"};if(obj.unitsPmm=[pxPmm,pxPmm],"pxpmm"in element&&(obj.pxPmm=element.pxpmm,obj.unitsPmm=[obj.pxPmm,obj.pxPmm]),"width"in element&&(obj.width=element.width),"height"in element&&(obj.height=element.height),"viewBox"in element){const list=element.viewBox.trim(),v=viewBoxRegExp.exec(list);if(null!==v&&(obj.viewX=parseFloat(v[1]),obj.viewY=parseFloat(v[2]),obj.viewW=parseFloat(v[3]),obj.viewH=parseFloat(v[4])),obj.width.indexOf("%")<0){let s=css2cag(obj.width,customPxPmm);s=obj.viewW/s,obj.unitsPmm[0]=s}else{const u=obj.unitsPmm[0]*(parseFloat(obj.width)/100);obj.unitsPmm[0]=u}if(obj.height.indexOf("%")<0){let s=css2cag(obj.height,pxPmm);s=obj.viewH/s,obj.unitsPmm[1]=s}else{const u=obj.unitsPmm[1]*(parseFloat(obj.height)/100);obj.unitsPmm[1]=u}}else obj.viewX=0,obj.viewY=0,obj.viewW=1920/obj.unitsPmm[0],obj.viewH=1080/obj.unitsPmm[1];return obj.viewP=Math.sqrt(obj.viewW*obj.viewW+obj.viewH*obj.viewH)/Math.SQRT2,svgCore(obj,element),svgPresentation(obj,element),obj.objects=[],obj},svgEllipse=element=>{const obj={type:"ellipse",cx:"0",cy:"0",rx:"0",ry:"0"};return"cx"in element&&(obj.cx=element.cx),"cy"in element&&(obj.cy=element.cy),"rx"in element&&(obj.rx=element.rx),"ry"in element&&(obj.ry=element.ry),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgLine=element=>{const obj={type:"line",x1:"0",y1:"0",x2:"0",y2:"0"};return"x1"in element&&(obj.x1=element.x1),"y1"in element&&(obj.y1=element.y1),"x2"in element&&(obj.x2=element.x2),"y2"in element&&(obj.y2=element.y2),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgListOfPoints=list=>{const points=[],exp=/([\d\-+.]+)[\s,]+([\d\-+.]+)[\s,]*/i;list=list.trim();let v=exp.exec(list);for(;null!==v;){let point=v[0];const next=exp.lastIndex+point.length;point={x:v[1],y:v[2]},points.push(point),list=list.slice(next,list.length),v=exp.exec(list)}return points},svgPolyline=element=>{const obj={type:"polyline"};return svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"points"in element&&(obj.points=svgListOfPoints(element.points)),obj},svgPolygon=element=>{const obj={type:"polygon"};return svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"points"in element&&(obj.points=svgListOfPoints(element.points)),obj},svgRect=element=>{const obj={type:"rect",x:"0",y:"0",rx:"0",ry:"0",width:"0",height:"0"};return"x"in element&&(obj.x=element.x),"y"in element&&(obj.y=element.y),"rx"in element&&(obj.rx=element.rx,"ry"in element||(obj.ry=obj.rx)),"ry"in element&&(obj.ry=element.ry,"rx"in element||(obj.rx=obj.ry)),obj.rx!==obj.ry&&console.log("Warning: Unsupported RECT with rx and ry radius"),"width"in element&&(obj.width=element.width),"height"in element&&(obj.height=element.height),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgCircle=element=>{const obj={type:"circle",x:"0",y:"0",radius:"0"};return"cx"in element&&(obj.x=element.cx),"cy"in element&&(obj.y=element.cy),"r"in element&&(obj.radius=element.r),svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj},svgGroup=element=>{const obj={type:"group"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"x"in element||"y"in element){let x="0",y="0";"x"in element&&(x=element.x),"y"in element&&(y=element.y),"transforms"in obj||(obj.transforms=[]);const o={translate:[x,y]};obj.transforms.push(o)}return obj.objects=[],obj},svgPath=element=>{const obj={type:"path"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),obj.commands=[],"d"in element){let co=null,bf="",i=0;const l=element.d.length,offset=element.position[1]-l-2;for(;i0&&(co.p.push(bf),bf=""),bf+=c;break;case".":bf.length>0&&bf.indexOf(".")>=0&&(co.p.push(bf),bf=""),bf+=c;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":bf+=c;break;case"a":case"A":case"c":case"C":case"h":case"H":case"l":case"L":case"v":case"V":case"m":case"M":case"q":case"Q":case"s":case"S":case"t":case"T":case"z":case"Z":null!==co&&(bf.length>0&&(co.p.push(bf),bf=""),obj.commands.push(co)),co={c:c,p:[],pos:i+offset};break;case",":case" ":case"\n":null!==co&&bf.length>0&&(co.p.push(bf),bf="")}i++}i===l&&null!==co&&(bf.length>0&&co.p.push(bf),obj.commands.push(co))}return obj},svgUse=(element,{svgObjects:svgObjects})=>{const obj={type:"group"};if(svgTransforms(obj,element),svgCore(obj,element),svgPresentation(obj,element),"x"in element||"y"in element){let x="0",y="0";"x"in element&&(x=element.x),"y"in element&&(y=element.y),"transforms"in obj||(obj.transforms=[]);const o={translate:[x,y]};obj.transforms.push(o)}if(obj.objects=[],"xlink:href"in element){let ref=element["xlink:href"];"#"===ref[0]&&(ref=ref.slice(1,ref.length)),void 0!==svgObjects[ref]&&(ref=svgObjects[ref],ref=JSON.parse(JSON.stringify(ref)),obj.objects.push(ref))}return obj},shapesMapGeometry=(obj,objectify,params)=>{const{svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,svgGroups:svgGroups,target:target,segments:segments,pathSelfClosed:pathSelfClosed}=params,types={group:obj=>objectify({target:target,segments:segments},obj),rect:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{let x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY);const w=cagLengthX(obj.width,svgUnitsPmm,svgUnitsX),h=cagLengthY(obj.height,svgUnitsPmm,svgUnitsY),rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX);let shape;return w>0&&h>0&&(x+=w/2,y-=h/2,shape=0===rx?rectangle({center:[x,y],size:[w,h]}):(options=>{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1])return create$a();if(0===roundRadius)return rectangle({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS)throw new Error("roundRadius must be smaller than the radius of all dimensions");const cornerSegments=Math.floor(segments/4),corner0=add([0,0],center,[size[0]-roundRadius,size[1]-roundRadius]),corner1=add([0,0],center,[roundRadius-size[0],size[1]-roundRadius]),corner2=add([0,0],center,[roundRadius-size[0],roundRadius-size[1]]),corner3=add([0,0],center,[size[0]-roundRadius,roundRadius-size[1]]),corner0Points=[],corner1Points=[],corner2Points=[],corner3Points=[];for(let i=0;i<=cornerSegments;i++){const point=fromAngleRadians([0,0],TAU/4*i/cornerSegments);scale$1(point,point,roundRadius),corner0Points.push(add([0,0],corner0,point)),rotate$1(point,point,[0,0],TAU/4),corner1Points.push(add([0,0],corner1,point)),rotate$1(point,point,[0,0],TAU/4),corner2Points.push(add([0,0],corner2,point)),rotate$1(point,point,[0,0],TAU/4),corner3Points.push(add([0,0],corner3,point))}const points=corner0Points.concat(corner1Points,corner2Points,corner3Points);return create$a([points])})({center:[x,y],segments:segments,size:[w,h],roundRadius:rx}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},circle:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{const x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY),r=cagLengthP(obj.radius,svgUnitsPmm,svgUnitsV);let shape;return r>0&&(shape=(options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})})({center:[x,y],segments:segments,radius:r}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},ellipse:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)=>{const rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX),ry=cagLengthY(obj.ry,svgUnitsPmm,svgUnitsY),cx=cagLengthX(obj.cx,svgUnitsPmm,svgUnitsX),cy=0-cagLengthY(obj.cy,svgUnitsPmm,svgUnitsY);let shape;return rx>0&&ry>0&&(shape=ellipse({center:[cx,cy],segments:segments,radius:[rx,ry]}),"path"===target&&(shape=index$5.fromPoints({closed:!0},index$a.toPoints(shape)))),shape},line:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV)=>{const x1=cagLengthX(obj.x1,svgUnitsPmm,svgUnitsX),y1=0-cagLengthY(obj.y1,svgUnitsPmm,svgUnitsY),x2=cagLengthX(obj.x2,svgUnitsPmm,svgUnitsX),y2=0-cagLengthY(obj.y2,svgUnitsPmm,svgUnitsY);return line([[x1,y1],[x2,y2]])},polygon:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY)=>{const points=[];for(let j=0;j{const points=[];for(let j=0;j{const listofpaths=expandPath(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments,pathSelfClosed),shapes=Object.entries(listofpaths).sort(((a,b)=>a[0].localeCompare(b[0]))).map((entry=>{const path=entry[1];if("geom2"===target&&path.isClosed){const points=index$5.toPoints(path);return index$a.create([points])}return path}));return shapes}};return types[obj.type](obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments)},appendPoints=(points,geometry)=>geometry?index$5.appendPoints(points,geometry):index$5.fromPoints({},points),expandPath=(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,svgGroups,segments,pathSelfClosed)=>{const paths={};let sx=0,sy=0,cx=0,cy=0,pi=0,pathName="path"+pi,pc=!1,bx=0,by=0,qx=0,qy=0;const newPath=()=>{pi++,pathName="path"+pi,pc=!1},ensurePath=()=>{paths[pathName]||(paths[pathName]=index$5.fromPoints({},[]))};for(let j=0;j=i+2&&(cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),newPath(),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)]),sx=cx,sy=cy);pts.length>=i+2;)cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"M":for(pts.length>=i+2&&(cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),newPath(),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)]),sx=cx,sy=cy);pts.length>=i+2;)cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"a":for(;pts.length>=i+7;){const rx=parseFloat(pts[i++]),ry=parseFloat(pts[i++]),ro=0-.017453292519943295*parseFloat(pts[i++]),lf="1"===pts[i++],sf="1"===pts[i++];cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendArc({segments:segments,endpoint:svg2cag([cx,cy],svgUnitsPmm),radius:svg2cag([rx,ry],svgUnitsPmm),xaxisrotation:ro,clockwise:sf,large:lf},paths[pathName])}break;case"A":for(;pts.length>=i+7;){const rx=parseFloat(pts[i++]),ry=parseFloat(pts[i++]),ro=0-.017453292519943295*parseFloat(pts[i++]),lf="1"===pts[i++],sf="1"===pts[i++];cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendArc({segments:segments,endpoint:svg2cag([cx,cy],svgUnitsPmm),radius:svg2cag([rx,ry],svgUnitsPmm),xaxisrotation:ro,clockwise:sf,large:lf},paths[pathName])}break;case"c":for(;pts.length>=i+6;){const x1=cx+parseFloat(pts[i++]),y1=cy+parseFloat(pts[i++]);bx=cx+parseFloat(pts[i++]),by=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"C":for(;pts.length>=i+6;){const x1=parseFloat(pts[i++]),y1=parseFloat(pts[i++]);bx=parseFloat(pts[i++]),by=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"q":for(;pts.length>=i+4;){const p0=[cx,cy];qx=cx+parseFloat(pts[i++]),qy=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"Q":for(;pts.length>=i+4;){const p0=[cx,cy];qx=parseFloat(pts[i++]),qy=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"t":for(;pts.length>=i+2;){const p0=[cx,cy];cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"T":for(;pts.length>=i+2;){const p0=[cx,cy];cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]);const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag(q1,svgUnitsPmm),svg2cag(q2,svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"s":for(;pts.length>=i+4;){const x1=bx,y1=by;bx=cx+parseFloat(pts[i++]),by=cy+parseFloat(pts[i++]),cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"S":for(;pts.length>=i+4;){const x1=bx,y1=by;bx=parseFloat(pts[i++]),by=parseFloat(pts[i++]),cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),ensurePath(),paths[pathName]=index$5.appendBezier({segments:segments,controlPoints:[svg2cag([x1,y1],svgUnitsPmm),svg2cag([bx,by],svgUnitsPmm),svg2cag([cx,cy],svgUnitsPmm)]},paths[pathName]);const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"h":for(;pts.length>=i+1;)cx+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"H":for(;pts.length>=i+1;)cx=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"l":for(;pts.length>=i+2;)cx+=parseFloat(pts[i++]),cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"L":for(;pts.length>=i+2;)cx=parseFloat(pts[i++]),cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"v":for(;pts.length>=i+1;)cy+=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"V":for(;pts.length>=i+1;)cy=parseFloat(pts[i++]),paths[pathName]=appendPoints([svg2cag([cx,cy],svgUnitsPmm)],paths[pathName]);break;case"z":case"Z":paths[pathName]=index$5.close(paths[pathName]),cx=sx,cy=sy,pc=!0;break;default:console.log("Warning: Unknown PATH command ["+co.c+"]")}const isCloseCmd=cmd=>"z"===cmd||"Z"===cmd;if(!0!==pc&&paths[pathName]&&paths[pathName].isClosed){let coNext=obj.commands[j+1];if(coNext&&!isCloseCmd(coNext.c))if("trim"===pathSelfClosed)for(;coNext&&!isCloseCmd(coNext.c);)j++,coNext=obj.commands[j+1];else{if("split"!==pathSelfClosed)throw new Error(`Malformed svg path at ${obj.position[0]}:${co.pos}. Path closed itself with command #${j} ${co.c}${pts.join(" ")}`);newPath()}}}return paths},shapesMapJscad=(obj,codify,params)=>{const{level:level,indent:indent,on:on,svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,svgGroups:svgGroups,target:target,segments:segments}=params,types={group:obj=>{let code=codify({target:target,segments:segments},obj);return code+=`${indent}${on} = levels.l${level+1}\n`,code},rect:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{let x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY);const w=cagLengthX(obj.width,svgUnitsPmm,svgUnitsX),h=cagLengthY(obj.height,svgUnitsPmm,svgUnitsY),rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX);let code;return w>0&&h>0&&(x=(x+w/2).toFixed(4),y=(y-h/2).toFixed(4),code=0===rx?`${indent}${on} = rectangle({center: [${x}, ${y}], size: [${w}, ${h}]}) // line ${obj.position}\n`:`${indent}${on} = roundedRectangle({center: [${x}, ${y}], segments: ${segments}, size: [${w}, ${h}], roundRadius: ${rx}}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},circle:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{const x=cagLengthX(obj.x,svgUnitsPmm,svgUnitsX),y=0-cagLengthY(obj.y,svgUnitsPmm,svgUnitsY),r=cagLengthP(obj.radius,svgUnitsPmm,svgUnitsV);let code;return r>0&&(code=`${indent}${on} = circle({center: [${x}, ${y}], segments: ${segments}, radius: ${r}}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},ellipse:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV,params,svgGroups,segments)=>{const rx=cagLengthX(obj.rx,svgUnitsPmm,svgUnitsX),ry=cagLengthY(obj.ry,svgUnitsPmm,svgUnitsY),cx=cagLengthX(obj.cx,svgUnitsPmm,svgUnitsX),cy=0-cagLengthY(obj.cy,svgUnitsPmm,svgUnitsY);let code;return rx>0&&ry>0&&(code=`${indent}${on} = ellipse({center: [${cx}, ${cy}], segments: ${segments}, radius: [${rx}, ${ry}]}) // line ${obj.position}\n`,"path"===target&&(code+=`${indent}${on} = path2.fromPoints({closed: true}, geom2.toPoints(${on}))\n`)),code},line:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY,svgUnitsV)=>{const x1=cagLengthX(obj.x1,svgUnitsPmm,svgUnitsX),y1=0-cagLengthY(obj.y1,svgUnitsPmm,svgUnitsY),x2=cagLengthX(obj.x2,svgUnitsPmm,svgUnitsX),y2=0-cagLengthY(obj.y2,svgUnitsPmm,svgUnitsY);return`${indent}${on} = line([[${x1}, ${y1}], [${x2}, ${y2}]]) // line ${obj.position}\n`},polygon:(obj,svgUnitsPmm,svgUnitsX,svgUnitsY)=>{let code=`${indent}${on} = polygon({points: [\n`;for(let j=0;j{let code=`${indent}${on} = path2.fromPoints({}, [\n`;for(let j=0;j{const{indent:indent,on:on,target:target}=params;let tmpCode=`${indent}parts = [] // line ${obj.position}\n`,sx=0,sy=0,cx=0,cy=0,pi=0,pathName=on+pi,pc=!1,bx=0,by=0,qx=0,qy=0;for(let j=0;j0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),pts.length>=2&&(cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),pi++,pc=!1,pathName=on+pi,tmpCode+=`${indent}${pathName} = path2.fromPoints({}, [[${svg2cag([cx,cy],svgUnitsPmm)}]])\n`,sx=cx,sy=cy);pts.length>=2;)cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([${svg2cag([cx,cy],svgUnitsPmm)}], ${pathName})\n`;break;case"M":for(pi>0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),pts.length>=2&&(cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),pi++,pc=!1,pathName=on+pi,tmpCode+=`${indent}${pathName} = path2.fromPoints({}, [[${svg2cag([cx,cy],svgUnitsPmm)}]])\n`,sx=cx,sy=cy);pts.length>=2;)cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([${svg2cag([cx,cy],svgUnitsPmm)}], ${pathName})\n`;break;case"a":for(;pts.length>=7;){const rx=parseFloat(pts.shift()),ry=parseFloat(pts.shift()),ro=0-.017453292519943295*parseFloat(pts.shift()),lf="1"===pts.shift(),sf="1"===pts.shift();cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendArc({segments: ${segments}, endpoint: [${svg2cag([cx,cy],svgUnitsPmm)}], radius: [${svg2cag([rx,ry],svgUnitsPmm)}], xaxisrotation: ${ro}, clockwise: ${sf}, large: ${lf}}, ${pathName})\n`}break;case"A":for(;pts.length>=7;){const rx=parseFloat(pts.shift()),ry=parseFloat(pts.shift()),ro=0-.017453292519943295*parseFloat(pts.shift()),lf="1"===pts.shift(),sf="1"===pts.shift();cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendArc({segments: ${segments}, endpoint: [${svg2cag([cx,cy],svgUnitsPmm)}], radius: [${svg2cag([rx,ry],svgUnitsPmm)}], xaxisrotation: ${ro}, clockwise: ${sf}, large: ${lf}}, ${pathName})\n`}break;case"c":for(;pts.length>=6;){const x1=cx+parseFloat(pts.shift()),y1=cy+parseFloat(pts.shift());bx=cx+parseFloat(pts.shift()),by=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"C":for(;pts.length>=6;){const x1=parseFloat(pts.shift()),y1=parseFloat(pts.shift());bx=parseFloat(pts.shift()),by=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"q":for(;pts.length>=4;){const p0=[cx,cy];qx=cx+parseFloat(pts.shift()),qy=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"Q":for(;pts.length>=4;){const p0=[cx,cy];qx=parseFloat(pts.shift()),qy=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"t":for(;pts.length>=2;){const p0=[cx,cy];cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"T":for(;pts.length>=2;){const p0=[cx,cy];cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift());const q1=[p0[0]+2/3*(qx-p0[0]),p0[1]+2/3*(qy-p0[1])],q2=[q1[0]+1/3*(cx-p0[0]),q1[1]+1/3*(cy-p0[1])];tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[[${svg2cag(q1,svgUnitsPmm)}], [${svg2cag(q2,svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(qx,qy,cx,cy);qx=rf[0],qy=rf[1]}break;case"s":for(;pts.length>=4;){const x1=bx,y1=by;bx=cx+parseFloat(pts.shift()),by=cy+parseFloat(pts.shift()),cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"S":for(;pts.length>=4;){const x1=bx,y1=by;bx=parseFloat(pts.shift()),by=parseFloat(pts.shift()),cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendBezier({segments: ${segments}, controlPoints: [[${svg2cag([x1,y1],svgUnitsPmm)}], [${svg2cag([bx,by],svgUnitsPmm)}], [${svg2cag([cx,cy],svgUnitsPmm)}]]}, ${pathName})\n`;const rf=reflect(bx,by,cx,cy);bx=rf[0],by=rf[1]}break;case"h":for(;pts.length>=1;)cx+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"H":for(;pts.length>=1;)cx=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"l":for(;pts.length>=2;)cx+=parseFloat(pts.shift()),cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"L":for(;pts.length>=2;)cx=parseFloat(pts.shift()),cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"v":for(;pts.length>=1;)cy+=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"V":for(;pts.length>=1;)cy=parseFloat(pts.shift()),tmpCode+=`${indent}${pathName} = path2.appendPoints([[${svg2cag([cx,cy],svgUnitsPmm)}]], ${pathName})\n`;break;case"z":case"Z":tmpCode+=`${indent}${pathName} = path2.close(${pathName})\n`,"geom2"===target&&(tmpCode+=`${indent}${pathName} = geom2.create([path2.toPoints(${pathName})])\n`),tmpCode+=`${indent}parts.push(${pathName})\n`,cx=sx,cy=sy,pc=!0;break;default:console.log("Warning: Unknow PATH command ["+co.c+"]")}}return pi>0&&!1===pc&&(tmpCode+=`${indent}parts.push(${pathName})\n`),tmpCode+=`${indent}${on} = parts\n`,tmpCode},instantiate=(src,options)=>{const{pxPmm:pxPmm}=options;if(options&&options.statusCallback&&options.statusCallback({progress:0}),createSvgParser(src,pxPmm),!svgObj)throw new Error("SVG parsing failed, no valid SVG data retrieved");options&&options.statusCallback&&options.statusCallback({progress:50});const result=objectify(options,svgObj);return options&&options.statusCallback&&options.statusCallback({progress:100}),result},translateScript=(src,options)=>{const{filename:filename,version:version,pxPmm:pxPmm,addMetaData:addMetaData}=options;if(options&&options.statusCallback&&options.statusCallback({progress:0}),createSvgParser(src,pxPmm),!svgObj)throw new Error("SVG parsing failed, no valid SVG data retrieved");let code=addMetaData?`//\n // producer: JSCAD SVG Deserializer ${version}\n // date: ${new Date}\n // source: ${filename}\n //\n`:"";return code+="const { colors, geometries, primitives, transforms } = require('@jscad/modeling')\n\n",options&&options.statusCallback&&options.statusCallback({progress:50}),code+=codify(options,svgObj),code+="\nmodule.exports = { main }",options&&options.statusCallback&&options.statusCallback({progress:100}),code};let svgUnitsX,svgUnitsY,svgUnitsV;const svgObjects=[],svgGroups=[],svgDefs=[];let svgObj,svgInDefs=!1,svgUnitsPmm=[1,1];const objectify=(options,group)=>{const{target:target,segments:segments,pathSelfClosed:pathSelfClosed}=options,level=svgGroups.length;svgGroups.push(group);let i=level;for(;i>0;)i--;let geometries=[];const params={svgUnitsPmm:svgUnitsPmm,svgUnitsX:svgUnitsX,svgUnitsY:svgUnitsY,svgUnitsV:svgUnitsV,level:level,target:target,svgGroups:svgGroups,segments:segments,pathSelfClosed:pathSelfClosed};for(i=0;i{if("transforms"in obj){let rotateAttribute=null,scaleAttribute=null,translateAttribute=null;for(let j=0;j{const{target:target,segments:segments}=options,level=svgGroups.length;svgGroups.push(group);let indent=" ",i=level;for(;i>0;)indent+=" ",i--;let code="";0===level&&(code+="function main(params) {\n let levels = {}\n let paths = {}\n let parts\n");const ln="levels.l"+level;for(code+=`${indent}${ln} = []\n`,i=0;i{const parser=new saxes.SaxesParser;return void 0!==pxPmm&&pxPmm>parser.pxPmm&&(parser.pxPmm=pxPmm),parser.on("error",(e=>{console.log(`ERROR: SVG file, line ${parser.line}, column ${parser.column}`),console.log(e)})),parser.on("opentag",(node=>{const objMap={SVG:svgSvg,G:svgGroup,RECT:svgRect,CIRCLE:svgCircle,ELLIPSE:svgEllipse,LINE:svgLine,POLYLINE:svgPolyline,POLYGON:svgPolygon,PATH:svgPath,USE:svgUse,DEFS:()=>{svgInDefs=!0},DESC:()=>{},TITLE:()=>{},STYLE:()=>{},undefined:()=>console.log("WARNING: unsupported SVG element: "+node.name)};node.attributes.position=[parser.line+1,parser.column+1];const elementName=node.name.toUpperCase(),obj=objMap[elementName]?objMap[elementName](node.attributes,{svgObjects:svgObjects,customPxPmm:pxPmm}):void 0;if(obj)if("id"in obj&&(svgObjects[obj.id]=obj),"svg"===obj.type)svgGroups.push(obj),svgUnitsPmm=obj.unitsPmm,svgUnitsX=obj.viewW,svgUnitsY=obj.viewH,svgUnitsV=obj.viewP;else if(!0===svgInDefs){if(svgDefs.length>0){const group=svgDefs.pop();"objects"in group&&group.objects.push(obj),svgDefs.push(group)}"group"===obj.type&&svgDefs.push(obj)}else{if(svgGroups.length>0){const group=svgGroups.pop();"objects"in group&&group.objects.push(obj),svgGroups.push(group)}"group"===obj.type&&svgGroups.push(obj)}})),parser.on("closetag",(node=>{const popGroup=()=>!0===svgInDefs?svgDefs.pop():svgGroups.pop(),objMap={SVG:popGroup,DEFS:()=>{svgInDefs=!1},USE:popGroup,G:popGroup,undefined:()=>{}},elementName=node.name.toUpperCase(),obj=objMap[elementName]?objMap[elementName]():void 0;0===svgGroups.length&&(svgObj=obj)})),parser.on("end",(()=>{})),parser.write(src).close(),parser};exports.deserialize=(options,input)=>{const defaults={addMetaData:!0,filename:"svg",output:"script",pxPmm:pxPmm,segments:32,target:"path",pathSelfClosed:"error",version:"3.0.1-alpha.0"};return options=Object.assign({},defaults,options),input=((stringOrArrayBuffer,defaultBinaryEncoding="utf-8")=>"string"==typeof stringOrArrayBuffer?stringOrArrayBuffer:new TextDecoder(defaultBinaryEncoding).decode(new Uint8Array(stringOrArrayBuffer)))(input),"script"===options.output?translateScript(input,options):instantiate(input,options)},exports.mimeType="image/svg+xml",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadSvgDeserializer={}); diff --git a/packages/io/svg-deserializer/package.json b/packages/io/svg-deserializer/package.json index 51d1df272..041c9530d 100644 --- a/packages/io/svg-deserializer/package.json +++ b/packages/io/svg-deserializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/svg-deserializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "SVG Deserializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -37,9 +37,9 @@ ], "license": "MIT", "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/io-utils": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0", + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/io-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", "saxes": "6.0.0" }, "devDependencies": { diff --git a/packages/io/svg-serializer/CHANGELOG.md b/packages/io/svg-serializer/CHANGELOG.md index 7f0bef5c9..d7948ac83 100644 --- a/packages/io/svg-serializer/CHANGELOG.md +++ b/packages/io/svg-serializer/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/svg-serializer@2.3.10...@jscad/svg-serializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/svg-serializer@2.3.10...@jscad/svg-serializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/svg-serializer/dist/jscad-svg-serializer.es.js b/packages/io/svg-serializer/dist/jscad-svg-serializer.es.js index 9b39a5f8e..258382871 100644 --- a/packages/io/svg-serializer/dist/jscad-svg-serializer.es.js +++ b/packages/io/svg-serializer/dist/jscad-svg-serializer.es.js @@ -1,13 +1,13 @@ /** * SVG Serializer for JSCAD * @module @jscad/svg-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},stringify=(a,indentation)=>{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;return a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}))?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},mimeType="image/svg+xml",serialize=(options,...objects)=>{const defaults={unit:"mm",decimals:1e4,version:"3.0.0-alpha.0",statusCallback:null};options=Object.assign({},defaults,options);const objects2d=(objects=flatten(objects)).filter((object=>index$a.isA(object)||index$5.isA(object)));if(0===objects2d.length)throw new Error("only 2D geometries can be serialized to SVG");objects.length!==objects2d.length&&console.warn("some objects could not be serialized to SVG"),options.statusCallback&&options.statusCallback({progress:0});const bounds=getBounds(objects2d);let width=0,height=0;bounds&&(width=Math.round((bounds[1][0]-bounds[0][0])*options.decimals)/options.decimals,height=Math.round((bounds[1][1]-bounds[0][1])*options.decimals)/options.decimals);let body=["svg",{width:width+options.unit,height:height+options.unit,viewBox:"0 0 "+width+" "+height,fill:"none","fill-rule":"evenodd","stroke-width":"0.1px",version:"1.1",baseProfile:"tiny",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"}];bounds&&(body=body.concat(convertObjects(objects2d,bounds,options)));const svg=`\n\x3c!-- Created by JSCAD SVG Serializer --\x3e\n\n${stringify(body,2)}`;return options.statusCallback&&options.statusCallback({progress:100}),[svg]},getBounds=objects=>{const allbounds=((...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results})(objects);if(1===objects.length)return allbounds;return allbounds.reduce(((sum,bounds)=>(index$d.min(sum[0],sum[0],bounds[0]),index$d.max(sum[1],sum[1],bounds[1]),sum)),[[0,0,0],[0,0,0]])},convertObjects=(objects,bounds,options)=>{const xoffset=0-bounds[0][0],yoffset=0-bounds[1][1],contents=[];return objects.forEach(((object,i)=>{options.statusCallback&&options.statusCallback({progress:100*i/objects.length}),index$a.isA(object)&&contents.push(convertGeom2(object,[xoffset,yoffset],options)),index$5.isA(object)&&contents.push(convertPaths([object],[xoffset,yoffset],options))})),contents},reflect=(x,y,px,py)=>{const ox=x-px,oy=y-py;return x===px&&y===px?[x,y]:x===px?[x,py-oy]:y===py?[px- -ox,y]:[px- -ox,py-oy]},convertGeom2=(object,offsets,options)=>{const paths=index$a.toOutlines(object).map((outline=>index$5.fromPoints({closed:!0},outline)));return options.color="black",object.color&&(options.color=convertColor(object.color)),options.id=null,object.id&&(options.id=object.id),options.class=null,object.class&&(options.class=object.class),convertToContinousPath(paths,offsets,options)},convertToContinousPath=(paths,offsets,options)=>{let instructions="";paths.forEach((path=>instructions+=convertPath(path,offsets,options)));const d={fill:options.color,d:instructions};return options.id&&(d.id=options.id),options.class&&(d.class=options.class),["g",["path",d]]},convertPaths=(paths,offsets,options)=>paths.reduce(((res,path,i)=>{const d={d:convertPath(path,offsets,options)};return path.color&&(d.stroke=convertColor(path.color)),path.id&&(d.id=path.id),path.class&&(d.class=path.class),res.concat([["path",d]])}),["g"]),convertPath=(path,offsets,options)=>{let str="";const numpointsClosed=path.points.length+(path.isClosed?1:0);for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped],offpoint=[point[0]+offsets[0],point[1]+offsets[1]],svgpoint=reflect(offpoint[0],offpoint[1],0,0),x=Math.round(svgpoint[0]*options.decimals)/options.decimals,y=Math.round(svgpoint[1]*options.decimals)/options.decimals;str+=pointindex>0?`L${x} ${y}`:`M${x} ${y}`}return str},convertColor=color=>`rgb(${255*color[0]},${255*color[1]},${255*color[2]},${255*color[3]})`;export{mimeType,serialize}; +const clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},stringify=(a,indentation)=>{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;return a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}))?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},mimeType="image/svg+xml",serialize=(options,...objects)=>{const defaults={unit:"mm",decimals:1e4,version:"3.0.1-alpha.0",statusCallback:null};options=Object.assign({},defaults,options);const objects2d=(objects=flatten(objects)).filter((object=>index$a.isA(object)||index$5.isA(object)));if(0===objects2d.length)throw new Error("only 2D geometries can be serialized to SVG");objects.length!==objects2d.length&&console.warn("some objects could not be serialized to SVG"),options.statusCallback&&options.statusCallback({progress:0});const bounds=getBounds(objects2d);let width=0,height=0;bounds&&(width=Math.round((bounds[1][0]-bounds[0][0])*options.decimals)/options.decimals,height=Math.round((bounds[1][1]-bounds[0][1])*options.decimals)/options.decimals);let body=["svg",{width:width+options.unit,height:height+options.unit,viewBox:"0 0 "+width+" "+height,fill:"none","fill-rule":"evenodd","stroke-width":"0.1px",version:"1.1",baseProfile:"tiny",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"}];bounds&&(body=body.concat(convertObjects(objects2d,bounds,options)));const svg=`\n\x3c!-- Created by JSCAD SVG Serializer --\x3e\n\n${stringify(body,2)}`;return options.statusCallback&&options.statusCallback({progress:100}),[svg]},getBounds=objects=>{const allbounds=((...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results})(objects);if(1===objects.length)return allbounds;return allbounds.reduce(((sum,bounds)=>(index$d.min(sum[0],sum[0],bounds[0]),index$d.max(sum[1],sum[1],bounds[1]),sum)),[[0,0,0],[0,0,0]])},convertObjects=(objects,bounds,options)=>{const xoffset=0-bounds[0][0],yoffset=0-bounds[1][1],contents=[];return objects.forEach(((object,i)=>{options.statusCallback&&options.statusCallback({progress:100*i/objects.length}),index$a.isA(object)&&contents.push(convertGeom2(object,[xoffset,yoffset],options)),index$5.isA(object)&&contents.push(convertPaths([object],[xoffset,yoffset],options))})),contents},reflect=(x,y,px,py)=>{const ox=x-px,oy=y-py;return x===px&&y===px?[x,y]:x===px?[x,py-oy]:y===py?[px- -ox,y]:[px- -ox,py-oy]},convertGeom2=(object,offsets,options)=>{const paths=index$a.toOutlines(object).map((outline=>index$5.fromPoints({closed:!0},outline)));return options.color="black",object.color&&(options.color=convertColor(object.color)),options.id=null,object.id&&(options.id=object.id),options.class=null,object.class&&(options.class=object.class),convertToContinousPath(paths,offsets,options)},convertToContinousPath=(paths,offsets,options)=>{let instructions="";paths.forEach((path=>instructions+=convertPath(path,offsets,options)));const d={fill:options.color,d:instructions};return options.id&&(d.id=options.id),options.class&&(d.class=options.class),["g",["path",d]]},convertPaths=(paths,offsets,options)=>paths.reduce(((res,path,i)=>{const d={d:convertPath(path,offsets,options)};return path.color&&(d.stroke=convertColor(path.color)),path.id&&(d.id=path.id),path.class&&(d.class=path.class),res.concat([["path",d]])}),["g"]),convertPath=(path,offsets,options)=>{let str="";const numpointsClosed=path.points.length+(path.isClosed?1:0);for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped],offpoint=[point[0]+offsets[0],point[1]+offsets[1]],svgpoint=reflect(offpoint[0],offpoint[1],0,0),x=Math.round(svgpoint[0]*options.decimals)/options.decimals,y=Math.round(svgpoint[1]*options.decimals)/options.decimals;str+=pointindex>0?`L${x} ${y}`:`M${x} ${y}`}return str},convertColor=color=>`rgb(${255*color[0]},${255*color[1]},${255*color[2]},${255*color[3]})`;export{mimeType,serialize}; diff --git a/packages/io/svg-serializer/dist/jscad-svg-serializer.min.js b/packages/io/svg-serializer/dist/jscad-svg-serializer.min.js index 83cba1a1f..175ae1d8f 100644 --- a/packages/io/svg-serializer/dist/jscad-svg-serializer.min.js +++ b/packages/io/svg-serializer/dist/jscad-svg-serializer.min.js @@ -1,14 +1,14 @@ /** * SVG Serializer for JSCAD * @module @jscad/svg-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ var global,factory;global=this,factory=function(exports){ /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},stringify=(a,indentation)=>{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;return a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}))?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},getBounds=objects=>{const allbounds=((...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results})(objects);return 1===objects.length?allbounds:allbounds.reduce(((sum,bounds)=>(index$d.min(sum[0],sum[0],bounds[0]),index$d.max(sum[1],sum[1],bounds[1]),sum)),[[0,0,0],[0,0,0]])},convertObjects=(objects,bounds,options)=>{const xoffset=0-bounds[0][0],yoffset=0-bounds[1][1],contents=[];return objects.forEach(((object,i)=>{options.statusCallback&&options.statusCallback({progress:100*i/objects.length}),index$a.isA(object)&&contents.push(convertGeom2(object,[xoffset,yoffset],options)),index$5.isA(object)&&contents.push(convertPaths([object],[xoffset,yoffset],options))})),contents},reflect=(x,y,px,py)=>{const ox=x-px,oy=y-py;return x===px&&y===px?[x,y]:x===px?[x,py-oy]:y===py?[px- -ox,y]:[px- -ox,py-oy]},convertGeom2=(object,offsets,options)=>{const paths=index$a.toOutlines(object).map((outline=>index$5.fromPoints({closed:!0},outline)));return options.color="black",object.color&&(options.color=convertColor(object.color)),options.id=null,object.id&&(options.id=object.id),options.class=null,object.class&&(options.class=object.class),convertToContinousPath(paths,offsets,options)},convertToContinousPath=(paths,offsets,options)=>{let instructions="";paths.forEach((path=>instructions+=convertPath(path,offsets,options)));const d={fill:options.color,d:instructions};return options.id&&(d.id=options.id),options.class&&(d.class=options.class),["g",["path",d]]},convertPaths=(paths,offsets,options)=>paths.reduce(((res,path,i)=>{const d={d:convertPath(path,offsets,options)};return path.color&&(d.stroke=convertColor(path.color)),path.id&&(d.id=path.id),path.class&&(d.class=path.class),res.concat([["path",d]])}),["g"]),convertPath=(path,offsets,options)=>{let str="";const numpointsClosed=path.points.length+(path.isClosed?1:0);for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped],offpoint=[point[0]+offsets[0],point[1]+offsets[1]],svgpoint=reflect(offpoint[0],offpoint[1],0,0),x=Math.round(svgpoint[0]*options.decimals)/options.decimals,y=Math.round(svgpoint[1]*options.decimals)/options.decimals;str+=pointindex>0?`L${x} ${y}`:`M${x} ${y}`}return str},convertColor=color=>`rgb(${255*color[0]},${255*color[1]},${255*color[2]},${255*color[3]})`;exports.mimeType="image/svg+xml",exports.serialize=(options,...objects)=>{const defaults={unit:"mm",decimals:1e4,version:"3.0.0-alpha.0",statusCallback:null};options=Object.assign({},defaults,options);const objects2d=(objects=flatten(objects)).filter((object=>index$a.isA(object)||index$5.isA(object)));if(0===objects2d.length)throw new Error("only 2D geometries can be serialized to SVG");objects.length!==objects2d.length&&console.warn("some objects could not be serialized to SVG"),options.statusCallback&&options.statusCallback({progress:0});const bounds=getBounds(objects2d);let width=0,height=0;bounds&&(width=Math.round((bounds[1][0]-bounds[0][0])*options.decimals)/options.decimals,height=Math.round((bounds[1][1]-bounds[0][1])*options.decimals)/options.decimals);let body=["svg",{width:width+options.unit,height:height+options.unit,viewBox:"0 0 "+width+" "+height,fill:"none","fill-rule":"evenodd","stroke-width":"0.1px",version:"1.1",baseProfile:"tiny",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"}];bounds&&(body=body.concat(convertObjects(objects2d,bounds,options)));const svg=`\n\x3c!-- Created by JSCAD SVG Serializer --\x3e\n\n${stringify(body,2)}`;return options.statusCallback&&options.statusCallback({progress:100}),[svg]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadSvgSerializer={}); +const clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},stringify=(a,indentation)=>{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;return a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}))?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},getBounds=objects=>{const allbounds=((...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results})(objects);return 1===objects.length?allbounds:allbounds.reduce(((sum,bounds)=>(index$d.min(sum[0],sum[0],bounds[0]),index$d.max(sum[1],sum[1],bounds[1]),sum)),[[0,0,0],[0,0,0]])},convertObjects=(objects,bounds,options)=>{const xoffset=0-bounds[0][0],yoffset=0-bounds[1][1],contents=[];return objects.forEach(((object,i)=>{options.statusCallback&&options.statusCallback({progress:100*i/objects.length}),index$a.isA(object)&&contents.push(convertGeom2(object,[xoffset,yoffset],options)),index$5.isA(object)&&contents.push(convertPaths([object],[xoffset,yoffset],options))})),contents},reflect=(x,y,px,py)=>{const ox=x-px,oy=y-py;return x===px&&y===px?[x,y]:x===px?[x,py-oy]:y===py?[px- -ox,y]:[px- -ox,py-oy]},convertGeom2=(object,offsets,options)=>{const paths=index$a.toOutlines(object).map((outline=>index$5.fromPoints({closed:!0},outline)));return options.color="black",object.color&&(options.color=convertColor(object.color)),options.id=null,object.id&&(options.id=object.id),options.class=null,object.class&&(options.class=object.class),convertToContinousPath(paths,offsets,options)},convertToContinousPath=(paths,offsets,options)=>{let instructions="";paths.forEach((path=>instructions+=convertPath(path,offsets,options)));const d={fill:options.color,d:instructions};return options.id&&(d.id=options.id),options.class&&(d.class=options.class),["g",["path",d]]},convertPaths=(paths,offsets,options)=>paths.reduce(((res,path,i)=>{const d={d:convertPath(path,offsets,options)};return path.color&&(d.stroke=convertColor(path.color)),path.id&&(d.id=path.id),path.class&&(d.class=path.class),res.concat([["path",d]])}),["g"]),convertPath=(path,offsets,options)=>{let str="";const numpointsClosed=path.points.length+(path.isClosed?1:0);for(let pointindex=0;pointindex=path.points.length&&(pointindexwrapped-=path.points.length);const point=path.points[pointindexwrapped],offpoint=[point[0]+offsets[0],point[1]+offsets[1]],svgpoint=reflect(offpoint[0],offpoint[1],0,0),x=Math.round(svgpoint[0]*options.decimals)/options.decimals,y=Math.round(svgpoint[1]*options.decimals)/options.decimals;str+=pointindex>0?`L${x} ${y}`:`M${x} ${y}`}return str},convertColor=color=>`rgb(${255*color[0]},${255*color[1]},${255*color[2]},${255*color[3]})`;exports.mimeType="image/svg+xml",exports.serialize=(options,...objects)=>{const defaults={unit:"mm",decimals:1e4,version:"3.0.1-alpha.0",statusCallback:null};options=Object.assign({},defaults,options);const objects2d=(objects=flatten(objects)).filter((object=>index$a.isA(object)||index$5.isA(object)));if(0===objects2d.length)throw new Error("only 2D geometries can be serialized to SVG");objects.length!==objects2d.length&&console.warn("some objects could not be serialized to SVG"),options.statusCallback&&options.statusCallback({progress:0});const bounds=getBounds(objects2d);let width=0,height=0;bounds&&(width=Math.round((bounds[1][0]-bounds[0][0])*options.decimals)/options.decimals,height=Math.round((bounds[1][1]-bounds[0][1])*options.decimals)/options.decimals);let body=["svg",{width:width+options.unit,height:height+options.unit,viewBox:"0 0 "+width+" "+height,fill:"none","fill-rule":"evenodd","stroke-width":"0.1px",version:"1.1",baseProfile:"tiny",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"}];bounds&&(body=body.concat(convertObjects(objects2d,bounds,options)));const svg=`\n\x3c!-- Created by JSCAD SVG Serializer --\x3e\n\n${stringify(body,2)}`;return options.statusCallback&&options.statusCallback({progress:100}),[svg]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadSvgSerializer={}); diff --git a/packages/io/svg-serializer/package.json b/packages/io/svg-serializer/package.json index dbb6cb13c..5b16475cc 100644 --- a/packages/io/svg-serializer/package.json +++ b/packages/io/svg-serializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/svg-serializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "SVG Serializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -37,8 +37,8 @@ ], "license": "MIT", "dependencies": { - "@jscad/io-utils": "workspace:^3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0" + "@jscad/io-utils": "workspace:^3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0" }, "devDependencies": { "@rollup/plugin-node-resolve": "^15.0.1", diff --git a/packages/io/x3d-deserializer/CHANGELOG.md b/packages/io/x3d-deserializer/CHANGELOG.md index 5940377b8..3fe4a2db7 100644 --- a/packages/io/x3d-deserializer/CHANGELOG.md +++ b/packages/io/x3d-deserializer/CHANGELOG.md @@ -3,6 +3,20 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/x3d-deserializer@2.2.2...@jscad/x3d-deserializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **all:** various fixes to pass tests ([5cb1d64](https://github.com/jscad/OpenJSCAD.org/commit/5cb1d648d3af1a4448d2c9a6a6acc701d38f36d3)) +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) +* **x3d-deserializer:** corrected to accept commas as MF value delimiters ([ffe36d2](https://github.com/jscad/OpenJSCAD.org/commit/ffe36d2e1b39fa67fa7159b751d9d3e30380e466)) +* **x3d-deserializer:** correcting caching of x3d attributes in createX3DParser, allowing continuous parsing of X3D files ([e9cd527](https://github.com/jscad/OpenJSCAD.org/commit/e9cd527b8de27a918504e388434934142eb83a65)) + +### Features + +* **modeling:** renamed poly3 toVertices and fromVerticesAndPlane ([58621b9](https://github.com/jscad/OpenJSCAD.org/commit/58621b9d23d8e0905eff23faf8e9dddb2c4023fb)) +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/x3d-deserializer@2.2.2...@jscad/x3d-deserializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/x3d-deserializer/dist/jscad-x3d-deserializer.es.js b/packages/io/x3d-deserializer/dist/jscad-x3d-deserializer.es.js index bc805cd03..1c395569e 100644 --- a/packages/io/x3d-deserializer/dist/jscad-x3d-deserializer.es.js +++ b/packages/io/x3d-deserializer/dist/jscad-x3d-deserializer.es.js @@ -1,16 +1,16 @@ /** * X3D Deserializer for JSCAD * @module @jscad/x3d-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ +const clone$b=geometry=>Object.assign({},geometry),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues$4=(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out}; /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT - */ -const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$b=geometry=>Object.assign({},geometry),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues$4=(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:fromValues$4,fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,measureBoundingSphere$1=polygon=>{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$6=Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");if(3===color.length&&(color=[color[0],color[1],color[2],1]),0===(objects=flatten$1(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):(object.color=color,object)));return 1===results.length?results[0]:results},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),equals$3=(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices=vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours)),toEdges=slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges};class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}const toPolygons=slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)};var index$2=Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:equals$3,fromGeom2:fromGeom2,fromVertices:fromVertices,isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:toEdges,toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:toPolygons,toString:slice=>{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:transform$3,validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGT=(value,constant)=>Number.isFinite(value)&&value>constant,isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGT(radius,0))throw new Error("radius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS*EPS)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps)),point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},circle=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],(options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:TAU,segments:32};let{center:center,height:height,startRadius:startRadius,startAngle:startAngle,endRadius:endRadius,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGT(height,0))throw new Error("height must be greater then zero");if(!isNumberArray(startRadius,2))throw new Error("startRadius must be an array of X and Y values");if(!startRadius.every((n=>n>=0)))throw new Error("startRadius values must be positive");if(!isNumberArray(endRadius,2))throw new Error("endRadius must be an array of X and Y values");if(!endRadius.every((n=>n>=0)))throw new Error("endRadius values must be positive");if(endRadius.every((n=>0===n))&&startRadius.every((n=>0===n)))throw new Error("at least one radius must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(startRadius[0],startRadius[1],endRadius[0],endRadius[1]),minAngle=Math.acos((minRadius*minRadius+minRadius*minRadius-EPS*EPS)/(2*minRadius*minRadius));if(rotation{const angle=slice*rotation+startAngle;return scale$3(v1,axisX,radius[0]*cos(angle)),scale$3(v2,axisY,radius[1]*sin(angle)),add$1(v1,v1,v2),scale$3(v3,ray,stack),add$1(v3,v3,start),add$1([0,0,0],v1,v3)},fromVertices=(...vertices)=>{const newVertices=vertices.map((vertex=>add$1([0,0,0],vertex,center)));return create$7(newVertices)},polygons=[];for(let i=0;i0&&startRadius[1]>0&&polygons.push(fromVertices(start,genVertex(0,t1,startRadius),genVertex(0,t0,startRadius))),(startRadius[0]>0||startRadius[1]>0)&&polygons.push(fromVertices(genVertex(0,t0,startRadius),genVertex(0,t1,startRadius),genVertex(1,t0,endRadius))),endRadius[0]>0&&endRadius[1]>0&&polygons.push(fromVertices(end,genVertex(1,t0,endRadius),genVertex(1,t1,endRadius))),(endRadius[0]>0||endRadius[1]>0)&&polygons.push(fromVertices(genVertex(1,t0,endRadius),genVertex(0,t1,startRadius),genVertex(1,t1,endRadius))))}return rotation{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},sphere=options=>{let{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius,radius],(options=>{const{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(radius,3))throw new Error("radius must be an array of X, Y and Z values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===radius[0]||0===radius[1]||0===radius[2])return create$8();const xVector=scale$3([0,0,0],normalize$1([0,0,0],axes[0]),radius[0]),yVector=scale$3([0,0,0],normalize$1([0,0,0],axes[1]),radius[1]),zVector=scale$3([0,0,0],normalize$1([0,0,0],axes[2]),radius[2]),qSegments=Math.round(segments/4);let prevCylinderVertex;const polygons=[],p1=[0,0,0],p2=[0,0,0];for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(p1,xVector,cos(angle)),scale$3(p2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch;for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);if(slice2>0){let vertex,vertices=[];vertex=subtract$3([0,0,0],scale$3(p1,prevCylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),vertex=subtract$3([0,0,0],scale$3(p1,cylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),slice2a===b?a:a{const multiple=newLength/edges.length;if(1===multiple)return edges;const divisor=fromValues$3(multiple,multiple,multiple),newEdges=[];return edges.forEach((edge=>{const increment=subtract$3([0,0,0],edge[1],edge[0]);divide$1(increment,increment,divisor);let prev=edge[0];for(let i=1;i<=multiple;++i){const next=add$1([0,0,0],prev,increment);newEdges.push([prev,next]),prev=next}})),newEdges},EPSAREA=EPS*EPS/2*Math.sin(Math.PI/3),extrudeWalls=(slice0,slice1)=>{let edges0=toEdges(slice0),edges1=toEdges(slice1);if(edges0.length!==edges1.length){const newLength=(a=edges0.length)*(b=edges1.length)/gcd(a,b);newLength!==edges0.length&&(edges0=repartitionEdges(newLength,edges0)),newLength!==edges1.length&&(edges1=repartitionEdges(newLength,edges1))}var a,b;const walls=[];return edges0.forEach(((edge0,i)=>{const edge1=edges1[i],poly0=create$7([edge0[0],edge0[1],edge1[1]]),poly0area=measureArea$2(poly0);Number.isFinite(poly0area)&&poly0area>EPSAREA&&walls.push(poly0);const poly1=create$7([edge0[0],edge1[1],edge1[0]]),poly1area=measureArea$2(poly1);Number.isFinite(poly1area)&&poly1area>EPSAREA&&walls.push(poly1)})),walls},defaultCallback=(progress,index,base)=>{let baseSlice=null;return isA$5(base)&&(baseSlice=fromGeom2(base)),isA$4(base)&&(baseSlice=fromVertices(toVertices$1(base))),0===progress||1===progress?transform$3(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[0,0,progress]),baseSlice):null},rotateX=(angle,...objects)=>((angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");if(0===(objects=flatten$1(objects)).length)throw new Error("wrong number of arguments");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results})([angle,0,0],objects),DEFAULT_COMPARE=(a,b)=>a>b?1:a{const N=new Node$1(null,null);let l=N,r=N;for(;;){const cmp=comparator(i,t.key);if(cmp<0){if(null===t.left)break;if(comparator(i,t.left.key)<0){const y=t.left;if(t.left=y.right,y.right=t,null===(t=y).left)break}r.left=t,r=t,t=t.left}else{if(!(cmp>0))break;if(null===t.right)break;if(comparator(i,t.right.key)>0){const y=t.right;if(t.right=y.left,y.left=t,null===(t=y).right)break}l.right=t,l=t,t=t.right}}return l.right=t.left,r.left=t.right,t.left=N.right,t.right=N.left,t},insert=(i,data,t,comparator)=>{const node=new Node$1(i,data);if(null===t)return node.left=node.right=null,node;const cmp=comparator(i,(t=splay(i,t,comparator)).key);return cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>=0&&(node.right=t.right,node.left=t,t.right=null),node},split=(key,v,comparator)=>{let left=null,right=null;if(v){const cmp=comparator((v=splay(key,v,comparator)).key,key);0===cmp?(left=v.left,right=v.right):cmp<0?(right=v.right,v.right=null,left=v):(left=v.left,v.left=null,right=v)}return{left:left,right:right}},printRow=(root,prefix,isTail,out,printNode)=>{if(root){out(`${prefix}${isTail?"└── ":"├── "}${printNode(root)}\n`);const indent=prefix+(isTail?" ":"│ ");root.left&&printRow(root.left,indent,!1,out,printNode),root.right&&printRow(root.right,indent,!0,out,printNode)}};class Tree$1{constructor(comparator=DEFAULT_COMPARE){this._comparator=comparator,this._root=null,this._size=0}insert(key,data){return this._size++,this._root=insert(key,data,this._root,this._comparator),this._root}add(key,data){const node=new Node$1(key,data);null===this._root&&(node.left=node.right=null,this._size++,this._root=node);const comparator=this._comparator,t=splay(key,this._root,comparator),cmp=comparator(key,t.key);return 0===cmp?this._root=t:(cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>0&&(node.right=t.right,node.left=t,t.right=null),this._size++,this._root=node),this._root}remove(key){this._root=this._remove(key,this._root,this._comparator)}_remove(i,t,comparator){let x;return null===t?null:0===comparator(i,(t=splay(i,t,comparator)).key)?(null===t.left?x=t.right:(x=splay(i,t.left,comparator),x.right=t.right),this._size--,x):t}pop(){let node=this._root;if(node){for(;node.left;)node=node.left;return this._root=splay(node.key,this._root,this._comparator),this._root=this._remove(node.key,this._root,this._comparator),{key:node.key,data:node.data}}return null}findStatic(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return current;current=cmp<0?current.left:current.right}return null}find(key){return this._root&&(this._root=splay(key,this._root,this._comparator),0!==this._comparator(key,this._root.key))?null:this._root}contains(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return!0;current=cmp<0?current.left:current.right}return!1}forEach(visitor,ctx){let current=this._root;const Q=[];let done=!1;for(;!done;)null!==current?(Q.push(current),current=current.left):0!==Q.length?(current=Q.pop(),visitor.call(ctx,current),current=current.right):done=!0;return this}range(low,high,fn,ctx){const Q=[],compare=this._comparator;let cmp,node=this._root;for(;0!==Q.length||node;)if(node)Q.push(node),node=node.left;else{if(node=Q.pop(),cmp=compare(node.key,high),cmp>0)break;if(compare(node.key,low)>=0&&fn.call(ctx,node))return this;node=node.right}return this}keys(){const keys=[];return this.forEach((({key:key})=>keys.push(key))),keys}values(){const values=[];return this.forEach((({data:data})=>values.push(data))),values}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(index){let current=this._root,done=!1,i=0;const Q=[];for(;!done;)if(current)Q.push(current),current=current.left;else if(Q.length>0){if(current=Q.pop(),i===index)return current;i++,current=current.right}else done=!0;return null}next(d){let root=this._root,successor=null;if(d.right){for(successor=d.right;successor.left;)successor=successor.left;return successor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?(successor=root,root=root.left):root=root.right}return successor}prev(d){let root=this._root,predecessor=null;if(null!==d.left){for(predecessor=d.left;predecessor.right;)predecessor=predecessor.right;return predecessor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?root=root.left:(predecessor=root,root=root.right)}return predecessor}clear(){return this._root=null,this._size=0,this}toList(){return toList(this._root)}load(keys,values=[],presort=!1){let size=keys.length;const comparator=this._comparator;if(presort&&sort(keys,values,0,size-1,comparator),null===this._root)this._root=loadRecursive(keys,values,0,size),this._size=size;else{const mergedList=mergeLists(this.toList(),createList(keys,values),comparator);size=this._size+size,this._root=sortedListToBST({head:mergedList},0,size)}return this}isEmpty(){return null===this._root}size(){return this._size}root(){return this._root}toString(printNode=(n=>String(n.key))){const out=[];return printRow(this._root,"",!0,(v=>out.push(v)),printNode),out.join("")}update(key,newKey,newData){const comparator=this._comparator;let{left:left,right:right}=split(key,this._root,comparator);comparator(key,newKey)<0?right=insert(newKey,newData,right,comparator):left=insert(newKey,newData,left,comparator),this._root=((left,right,comparator)=>null===right?left:(null===left||((right=splay(left.key,right,comparator)).left=left),right))(left,right,comparator)}split(key){return split(key,this._root,this._comparator)}*[Symbol.iterator](){let n=this.minNode();for(;n;)yield n,n=this.next(n)}}const loadRecursive=(keys,values,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),key=keys[middle],data=values[middle],node=new Node$1(key,data);return node.left=loadRecursive(keys,values,start,middle),node.right=loadRecursive(keys,values,middle+1,end),node}return null},createList=(keys,values)=>{const head=new Node$1(null,null);let p=head;for(let i=0;i{let current=root;const Q=[];let done=!1;const head=new Node$1(null,null);let p=head;for(;!done;)current?(Q.push(current),current=current.left):Q.length>0?(current=p=p.next=Q.pop(),current=current.right):done=!0;return p.next=null,head.next},sortedListToBST=(list,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),left=sortedListToBST(list,start,middle),root=list.head;return root.left=left,list.head=list.head.next,root.right=sortedListToBST(list,middle+1,end),root}return null},mergeLists=(l1,l2,compare)=>{const head=new Node$1(null,null);let p=head,p1=l1,p2=l2;for(;null!==p1&&null!==p2;)compare(p1.key,p2.key)<0?(p.next=p1,p1=p1.next):(p.next=p2,p2=p2.next),p=p.next;return null!==p1?p.next=p1:null!==p2&&(p.next=p2),head.next},sort=(keys,values,left,right,compare)=>{if(left>=right)return;const pivot=keys[left+right>>1];let i=left-1,j=right+1;for(;;){do{i++}while(compare(keys[i],pivot)<0);do{j--}while(compare(keys[j],pivot)>0);if(i>=j)break;let tmp=keys[i];keys[i]=keys[j],keys[j]=tmp,tmp=values[i],values[i]=values[j],values[j]=tmp}sort(keys,values,left,j,compare),sort(keys,values,j+1,right,compare)},computeFields=(event,prev,operation)=>{null===prev?(event.inOut=!1,event.otherInOut=!0):(event.isSubject===prev.isSubject?(event.inOut=!prev.inOut,event.otherInOut=prev.otherInOut):(event.inOut=!prev.otherInOut,event.otherInOut=prev.isVertical()?!prev.inOut:prev.inOut),prev&&(event.prevInResult=!inResult(prev,operation)||prev.isVertical()?prev.prevInResult:prev));const isInResult=inResult(event,operation);event.resultTransition=isInResult?determineResultTransition(event,operation):0},inResult=(event,operation)=>{switch(event.type){case 0:switch(operation){case 0:return!event.otherInOut;case 1:return event.otherInOut;case 2:return event.isSubject&&event.otherInOut||!event.isSubject&&!event.otherInOut;case 3:return!0}break;case 2:return 0===operation||1===operation;case 3:return 2===operation;case 1:return!1}return!1},determineResultTransition=(event,operation)=>{const thisIn=!event.inOut,thatIn=!event.otherInOut;let isIn;switch(operation){case 0:isIn=thisIn&&thatIn;break;case 1:isIn=thisIn||thatIn;break;case 3:isIn=thisIn^thatIn;break;case 2:isIn=event.isSubject?thisIn&&!thatIn:thatIn&&!thisIn}return isIn?1:-1};class SweepEvent{constructor(point,left,otherEvent,isSubject,edgeType){this.left=left,this.point=point,this.otherEvent=otherEvent,this.isSubject=isSubject,this.type=edgeType||0,this.inOut=!1,this.otherInOut=!1,this.prevInResult=null,this.resultTransition=0,this.otherPos=-1,this.outputContourId=-1,this.isExteriorRing=!0}isBelow(p){const p0=this.point,p1=this.otherEvent.point;return this.left?(p0[0]-p[0])*(p1[1]-p[1])-(p1[0]-p[0])*(p0[1]-p[1])>0:(p1[0]-p[0])*(p0[1]-p[1])-(p0[0]-p[0])*(p1[1]-p[1])>0}isAbove(p){return!this.isBelow(p)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return 0!==this.resultTransition}clone(){const copy=new SweepEvent(this.point,this.left,this.otherEvent,this.isSubject,this.type);return copy.contourId=this.contourId,copy.resultTransition=this.resultTransition,copy.prevInResult=this.prevInResult,copy.isExteriorRing=this.isExteriorRing,copy.inOut=this.inOut,copy.otherInOut=this.otherInOut,copy}}const signedArea=(p0,p1,p2)=>{const res=(ax=p0[0],ay=p0[1],bx=p1[0],by=p1[1],cx=p2[0],(ay-(cy=p2[1]))*(bx-cx)-(ax-cx)*(by-cy));var ax,ay,bx,by,cx,cy;return res>0?-1:res<0?1:0},compareEvents=(e1,e2)=>{const p1=e1.point,p2=e2.point;return p1[0]>p2[0]?1:p1[0]p2[1]?1:-1:specialCases(e1,e2,p1)},specialCases=(e1,e2,p1,p2)=>e1.left!==e2.left?e1.left?1:-1:0!==signedArea(p1,e1.otherEvent.point,e2.otherEvent.point)?e1.isBelow(e2.otherEvent.point)?-1:1:!e1.isSubject&&e2.isSubject?1:-1,divideSegment=(se,p,queue)=>{const r=new SweepEvent(p,!1,se,se.isSubject),l=new SweepEvent(p,!0,se.otherEvent,se.isSubject);return r.contourId=l.contourId=se.contourId,compareEvents(l,se.otherEvent)>0&&(se.otherEvent.left=!0,l.left=!1),se.otherEvent.otherEvent=l,se.otherEvent=r,queue.push(l),queue.push(r),queue},crossProduct=(a,b)=>a[0]*b[1]-a[1]*b[0],possibleIntersection=(se1,se2,queue)=>{const inter=((a1,a2,b1,b2,noEndpointTouch)=>{const va=[a2[0]-a1[0],a2[1]-a1[1]],vb=[b2[0]-b1[0],b2[1]-b1[1]],toPoint=(p,s,d)=>[p[0]+s*d[0],p[1]+s*d[1]],e=[b1[0]-a1[0],b1[1]-a1[1]];let kross=crossProduct(va,vb),sqrKross=kross*kross;const sqrLenA=dot$1(va,va);if(sqrKross>0){const s=crossProduct(e,vb)/kross;if(s<0||s>1)return null;const t=crossProduct(e,va)/kross;return t<0||t>1?null:0===s||1===s?[toPoint(a1,s,va)]:0===t||1===t?[toPoint(b1,t,vb)]:[toPoint(a1,s,va)]}if(kross=crossProduct(e,va),sqrKross=kross*kross,sqrKross>0)return null;const sa=dot$1(va,e)/sqrLenA,sb=sa+dot$1(va,vb)/sqrLenA,smin=Math.min(sa,sb),smax=Math.max(sa,sb);return smin<=1&&smax>=0?1===smin?[toPoint(a1,smin>0?smin:0,va)]:0===smax?[toPoint(a1,smax<1?smax:1,va)]:[toPoint(a1,smin>0?smin:0,va),toPoint(a1,smax<1?smax:1,va)]:null})(se1.point,se1.otherEvent.point,se2.point,se2.otherEvent.point),nIntersections=inter?inter.length:0;if(0===nIntersections)return 0;if(1===nIntersections&&(equals$6(se1.point,se2.point)||equals$6(se1.otherEvent.point,se2.otherEvent.point)))return 0;if(2===nIntersections&&se1.isSubject===se2.isSubject)return 0;if(1===nIntersections)return equals$6(se1.point,inter[0])||equals$6(se1.otherEvent.point,inter[0])||divideSegment(se1,inter[0],queue),equals$6(se2.point,inter[0])||equals$6(se2.otherEvent.point,inter[0])||divideSegment(se2,inter[0],queue),1;const events=[];let leftCoincide=!1,rightCoincide=!1;return equals$6(se1.point,se2.point)?leftCoincide=!0:1===compareEvents(se1,se2)?events.push(se2,se1):events.push(se1,se2),equals$6(se1.otherEvent.point,se2.otherEvent.point)?rightCoincide=!0:1===compareEvents(se1.otherEvent,se2.otherEvent)?events.push(se2.otherEvent,se1.otherEvent):events.push(se1.otherEvent,se2.otherEvent),leftCoincide&&rightCoincide||leftCoincide?(se2.type=1,se1.type=se2.inOut===se1.inOut?2:3,leftCoincide&&!rightCoincide&÷Segment(events[1].otherEvent,events[0].point,queue),2):rightCoincide?(divideSegment(events[0],events[1].point,queue),3):events[0]!==events[3].otherEvent?(divideSegment(events[0],events[1].point,queue),divideSegment(events[1],events[2].point,queue),3):(divideSegment(events[0],events[1].point,queue),divideSegment(events[3].otherEvent,events[2].point,queue),3)},compareSegments=(le1,le2)=>{if(le1===le2)return 0;if(0!==signedArea(le1.point,le1.otherEvent.point,le2.point)||0!==signedArea(le1.point,le1.otherEvent.point,le2.otherEvent.point))return equals$6(le1.point,le2.point)?le1.isBelow(le2.otherEvent.point)?-1:1:le1.point[0]===le2.point[0]?le1.point[1]le2.contourId?1:-1}return 1===compareEvents(le1,le2)?1:-1};class Contour{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return null==this.holeOf}}const nextPos=(pos,resultEvents,processed,origPos)=>{let newPos=pos+1;const p=resultEvents[pos].point;let p1;const length=resultEvents.length;for(newPosorigPos;)newPos--;return newPos},initializeContourFromContext=(event,contours,contourId)=>{const contour=new Contour;if(null!=event.prevInResult){const prevInResult=event.prevInResult,lowerContourId=prevInResult.outputContourId,lowerResultTransition=prevInResult.resultTransition;if(lowerContourId<0)contour.holeOf=null,contour.depth=0;else if(lowerResultTransition>0){const lowerContour=contours[lowerContourId];if(null!=lowerContour.holeOf){const parentContourId=lowerContour.holeOf;contours[parentContourId].holeIds.push(contourId),contour.holeOf=parentContourId,contour.depth=contours[lowerContourId].depth}else contours[lowerContourId].holeIds.push(contourId),contour.holeOf=lowerContourId,contour.depth=contours[lowerContourId].depth+1}else contour.holeOf=null,contour.depth=contours[lowerContourId].depth}else contour.holeOf=null,contour.depth=0;return contour};class Queue{constructor(data,compare){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this._up(this.length++)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return--this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos=0)break;data[pos]=data[bestChild],pos=bestChild}data[pos]=item}}const max=Math.max,min=Math.min;let contourId=0;const processPolygon=(contourOrHole,isSubject,depth,queue,bbox,isExteriorRing)=>{const len=contourOrHole.length-1;let s1,s2,e1,e2;for(let i=0;i0?e2.left=!0:e1.left=!0;const x=s1[0],y=s1[1];bbox[0]=min(bbox[0],x),bbox[1]=min(bbox[1],y),bbox[2]=max(bbox[2],x),bbox[3]=max(bbox[3],y),queue.push(e1),queue.push(e2)}},EMPTY=[],toMartinez=geometry=>{const outlines=[];return toOutlines(geometry).forEach((outline=>{equals$6(outline[0],outline[outline.length-1])?outlines.push(outline):outlines.push([...outline,outline[0]])})),[outlines]},fromOutlines=outlines=>(outlines.forEach((outline=>{equals$6(outline[0],outline[outline.length-1])&&outline.pop()})),outlines=outlines.filter((o=>o.length>=3)),create$a(outlines)),boolean=(subjectGeom,clippingGeom,operation)=>{const subject=toMartinez(subjectGeom),clipping=toMartinez(clippingGeom);let trivial=((subject,clipping,operation)=>{let result=null;if(subject.length*clipping.length==0){if(0===operation)return EMPTY;2===operation?result=subject:1!==operation&&3!==operation||(result=0===subject.length?clipping:subject)}return result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,operation);if(trivial)return trivial;const sbbox=[1/0,1/0,-1/0,-1/0],cbbox=[1/0,1/0,-1/0,-1/0],eventQueue=((subject,clipping,sbbox,cbbox,operation)=>{const eventQueue=new Queue([],compareEvents);let polygonSet,isExteriorRing,i,ii,j,jj;for(i=0,ii=subject.length;i{let result=null;return(sbbox[0]>cbbox[2]||cbbox[0]>sbbox[2]||sbbox[1]>cbbox[3]||cbbox[1]>sbbox[3])&&(0===operation?result=EMPTY:2===operation?result=subject:1!==operation&&3!==operation||(result=subject.concat(clipping))),result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,sbbox,cbbox,operation),trivial)return trivial;const sortedEvents=((eventQueue,subject,clipping,sbbox,cbbox,operation)=>{const sweepLine=new Tree$1(compareSegments),sortedEvents=[],rightBound=Math.min(sbbox[2],cbbox[2]);let prev,next,begin;for(;0!==eventQueue.length;){let event=eventQueue.pop();if(sortedEvents.push(event),0===operation&&event.point[0]>rightBound||2===operation&&event.point[0]>sbbox[2])break;if(event.left){next=prev=sweepLine.insert(event),begin=sweepLine.minNode(),prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next);const prevEvent=prev?prev.key:null;let prevprevEvent;if(computeFields(event,prevEvent,operation),next&&2===possibleIntersection(event,next.key,eventQueue)&&(computeFields(event,prevEvent,operation),computeFields(next.key,event,operation)),prev&&2===possibleIntersection(prev.key,event,eventQueue)){let prevprev=prev;prevprev=prevprev!==begin?sweepLine.prev(prevprev):null,prevprevEvent=prevprev?prevprev.key:null,computeFields(prevEvent,prevprevEvent,operation),computeFields(event,prevEvent,operation)}}else event=event.otherEvent,next=prev=sweepLine.find(event),prev&&next&&(prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next),sweepLine.remove(event),next&&prev&&possibleIntersection(prev.key,next.key,eventQueue))}return sortedEvents})(eventQueue,0,0,sbbox,cbbox,operation),contours=(sortedEvents=>{const resultEvents=(sortedEvents=>{let event,i,len,tmp;const resultEvents=[];for(i=0,len=sortedEvents.length;i{processed[pos]=!0,pos=resultEvents.length)&&resultEvents[pos];);contours.push(contour)}return contours})(sortedEvents),polygons=[];for(let i=0;i=0;k--)hole.push(holePoints[k]);rings.push(hole)}polygons.push(rings)}}return polygons?fromOutlines(polygons.flat()):create$a()},interpolateBetween2DPointsForY=(point1,point2,y)=>{let t,f1=y-point1[1],f2=point2[1]-point1[1];return f2<0&&(f1=-f1,f2=-f2),t=f1<=0?0:f1>=f2?1:f2<1e-10?.5:f1/f2,point1[0]+t*(point2[0]-point1[0])};class OrthonormalFormula{constructor(plane){this.plane=plane;const rightVector=orthogonal([0,0,0],plane);this.v=normalize$1(rightVector,cross$1(rightVector,plane,rightVector)),this.u=cross$1([0,0,0],this.v,plane),this.planeOrigin=scale$3([0,0,0],plane,plane[3]),this.basisMap=new Map}getProjectionMatrix(){return fromValues$4(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)}getInverseProjectionMatrix(){return fromValues$4(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,this.planeOrigin[0],this.planeOrigin[1],this.planeOrigin[2],1)}to2D(vertex){const point=fromValues$2(dot$2(vertex,this.u),dot$2(vertex,this.v));return this.basisMap.set(point,vertex),point}to3D(point){const original=this.basisMap.get(point);if(original)return original;const v1=scale$3([0,0,0],this.u,point[0]),v2=scale$3([0,0,0],this.v,point[1]),v3=add$1(v1,v1,this.planeOrigin);return add$1(v2,v2,v3)}}const insertSorted=(array,element,compareFunc)=>{let leftBound=0,rightBound=array.length;for(;rightBound>leftBound;){const testIndex=Math.floor((leftBound+rightBound)/2);compareFunc(element,array[testIndex])>0?leftBound=testIndex+1:rightBound=testIndex}array.splice(leftBound,0,element)},fnNumberSort=(a,b)=>a-b,classifyPolygons=polygons=>{let clusters=[polygons];const nonCoplanar=[];for(let component=3;component>=0;component--){const maybeCoplanar=[],tolerance=3===component?15e-9:1e-13;clusters.forEach((cluster=>{cluster.sort(byPlaneComponent(component,tolerance));let startIndex=0;for(let i=1;itolerance&&(i-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex,i)),startIndex=i);cluster.length-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex))})),clusters=maybeCoplanar}const result=[];return clusters.forEach((cluster=>{cluster[0]&&(result[cluster[0].index]=cluster)})),nonCoplanar.forEach((polygon=>{result[polygon.index]=polygon})),result},byPlaneComponent=(component,tolerance)=>(a,b)=>a.plane[component]-b.plane[component]>tolerance?1:b.plane[component]-a.plane[component]>tolerance?-1:0;class Node{constructor(parent){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=parent}invert(){const queue=[this];let node;for(let i=0;i{treeNode.isRemoved()||treeNode.splitByPlane(plane,coplanarFrontNodes,backNodes,frontNodes,backNodes)})),node.front&&frontNodes.length>0&&stack.push({node:node.front,polygonTreeNodes:frontNodes});const numBackNodes=backNodes.length;if(node.back&&numBackNodes>0)stack.push({node:node.back,polygonTreeNodes:backNodes});else for(let i=0;i0&&tree.rootnode.clipPolygons(node.polygontreenodes,alsoRemoveCoplanarFront),node.front&&stack.push(node.front),node.back&&stack.push(node.back),node=stack.pop()}while(void 0!==node)}addPolygonTreeNodes(newPolygonTreeNodes){let current={node:this,polygonTreeNodes:newPolygonTreeNodes};const stack=[];do{const node=current.node,polygonTreeNodes=current.polygonTreeNodes,len=polygonTreeNodes.length;if(0===len){current=stack.pop();continue}if(!node.plane){let index=0;index=Math.floor(len/2);const bestPoly=polygonTreeNodes[index].getPolygon();node.plane=plane(bestPoly)}const frontNodes=[],backNodes=[];for(let i=0;i0&&(node.front||(node.front=new Node(node)),len===frontNodes.length&&0===backNodes.length?node.front.polygontreenodes=frontNodes:stack.push({node:node.front,polygonTreeNodes:frontNodes})),backNodes.length>0&&(node.back||(node.back=new Node(node)),len===backNodes.length&&0===frontNodes.length?node.back.polygontreenodes=backNodes:stack.push({node:node.back,polygonTreeNodes:backNodes})),current=stack.pop()}while(void 0!==current)}}const splitLineSegmentByPlane=(plane,p1,p2)=>{const direction=subtract$3([0,0,0],p2,p1);let lambda=(plane[3]-dot$2(plane,p1))/dot$2(plane,direction);return Number.isNaN(lambda)&&(lambda=0),lambda>1&&(lambda=1),lambda<0&&(lambda=0),scale$3(direction,direction,lambda),add$1(direction,p1,direction),direction};class PolygonTreeNode{constructor(parent,polygon){this.parent=parent,this.children=[],this.polygon=polygon,this.removed=!1}addPolygons(polygons){if(!this.isRootNode())throw new Error("Assertion failed");const _this=this;polygons.forEach((polygon=>{_this.addChild(polygon)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const parentschildren=this.parent.children,i=parentschildren.indexOf(this);if(i<0)throw new Error("Assertion failed");parentschildren.splice(i,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(result){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){if(this.children.length){const queue=[this.children];let i,j,l,node,nodes;for(i=0;i0?queue.push(node.children):node._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}else this._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}_splitByPlane(splane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){const polygon=this.polygon;if(polygon){const bound=measureBoundingSphere$1(polygon),sphereRadius=bound[3]+EPS,d=dot$2(splane,bound)-splane[3];if(d>sphereRadius)frontNodes.push(this);else if(d<-sphereRadius)backNodes.push(this);else{const splitResult=((splane,polygon)=>{const result={type:null,front:null,back:null},vertices=polygon.vertices,numVertices=vertices.length,pplane=plane(polygon);if(equals$5(pplane,splane))result.type=0;else{let hasFront=!1,hasBack=!1;const vertexIsBack=[],MINEPS=-EPS;for(let i=0;iEPS&&(hasFront=!0),t=numVertices&&(nextVertexIndex=0);const nextIsBack=vertexIsBack[nextVertexIndex];if(isback===nextIsBack)isback?backVertices.push(vertex):frontVertices.push(vertex);else{const nextPoint=vertices[nextVertexIndex],intersectionPoint=splitLineSegmentByPlane(splane,vertex,nextPoint);isback?(backVertices.push(vertex),backVertices.push(intersectionPoint),frontVertices.push(intersectionPoint)):(frontVertices.push(vertex),frontVertices.push(intersectionPoint),backVertices.push(intersectionPoint))}isback=nextIsBack}const EPS_SQUARED=EPS*EPS;if(backVertices.length>=3){let prevVertex=backVertices[backVertices.length-1];for(let vertexIndex=0;vertexIndex=3){let prevVertex=frontVertices[frontVertices.length-1];for(let vertexIndex=0;vertexIndex=3&&(result.front=fromVerticesAndPlane(frontVertices,pplane)),backVertices.length>=3&&(result.back=fromVerticesAndPlane(backVertices,pplane))}else result.type=3;else result.type=2;else{const t=dot$2(splane,pplane);result.type=t>=0?0:1}}return result})(splane,polygon);switch(splitResult.type){case 0:coplanarFrontNodes.push(this);break;case 1:coplanarBackNodes.push(this);break;case 2:frontNodes.push(this);break;case 3:backNodes.push(this);break;case 4:if(splitResult.front){const frontNode=this.addChild(splitResult.front);frontNodes.push(frontNode)}if(splitResult.back){const backNode=this.addChild(splitResult.back);backNodes.push(backNode)}}}}}addChild(polygon){const newChild=new PolygonTreeNode(this,polygon);return this.children.push(newChild),newChild}invertSub(){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let children=[this];const queue=[children];for(let i=0;i0&&queue.push(node.children),node.children=[]}}}toString(){let result="",children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}return result}}class Tree{constructor(polygons){this.polygonTree=new PolygonTreeNode,this.rootnode=new Node(null),polygons&&this.addPolygons(polygons)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(tree,alsoRemoveCoplanarFront=!1){this.rootnode.clipTo(tree,alsoRemoveCoplanarFront)}allPolygons(){const result=[];return this.polygonTree.getPolygons(result),result}addPolygons(polygons){const polygonTreeNodes=new Array(polygons.length);for(let i=0;i{let newGeometry=(geometries=flatten$1(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!((geometry1,geometry2)=>{if(0===geometry1.polygons.length||0===geometry2.polygons.length)return!1;const bounds1=measureBoundingBox(geometry1),min1=bounds1[0],max1=bounds1[1],bounds2=measureBoundingBox(geometry2),min2=bounds2[0],max2=bounds2[1];return!(min2[0]-max1[0]>EPS||min1[0]-max2[0]>EPS||min2[1]-max1[1]>EPS||min1[1]-max2[1]>EPS||min2[2]-max1[2]>EPS||min1[2]-max2[2]>EPS)})(geometry1,geometry2))return clone$7(geometry1);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),a.clipTo(b),b.clipTo(a,!0),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=(geometry=>{if(geometry.isRetesselated)return geometry;const polygons=toPolygons$1(geometry).map(((polygon,index)=>({vertices:polygon.vertices,plane:plane(polygon),index:index}))),classified=classifyPolygons(polygons),destPolygons=[];classified.forEach((group=>{if(Array.isArray(group)){const reTessellateCoplanarPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const destPolygons=[],numPolygons=sourcePolygons.length,plane$1=plane(sourcePolygons[0]),orthonormalFormula=new OrthonormalFormula(plane$1),polygonVertices2d=[],polygonTopVertexIndexes=[],topy2polygonIndexes=new Map,yCoordinateToPolygonIndexes=new Map,yCoordinateBins=new Map;for(let polygonIndex=0;polygonIndex0){let miny,maxy;for(let i=0;imaxy)&&(maxy=y);let polygonIndexes=yCoordinateToPolygonIndexes.get(y);polygonIndexes||(polygonIndexes={},yCoordinateToPolygonIndexes.set(y,polygonIndexes)),polygonIndexes[polygonIndex]=!0}if(miny>=maxy)vertices2d=[],numVertices=0,minIndex=-1;else{let polygonIndexes=topy2polygonIndexes.get(miny);polygonIndexes||(polygonIndexes=[],topy2polygonIndexes.set(miny,polygonIndexes)),polygonIndexes.push(polygonIndex)}}vertices2d.reverse(),minIndex=numVertices-minIndex-1,polygonVertices2d.push(vertices2d),polygonTopVertexIndexes.push(minIndex)}const yCoordinates=[];yCoordinateToPolygonIndexes.forEach(((polylist,y)=>yCoordinates.push(y))),yCoordinates.sort(fnNumberSort);let activePolygons=[],prevOutPolygonRow=[];for(let yIndex=0;yIndex=numVertices&&(nextLeftVertexIndex=0),vertices2d[nextLeftVertexIndex][1]!==yCoordinate)break;newLeftVertexIndex=nextLeftVertexIndex}let nextRightVertexIndex=newRightVertexIndex-1;if(nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),vertices2d[nextRightVertexIndex][1]===yCoordinate&&(newRightVertexIndex=nextRightVertexIndex),newLeftVertexIndex!==activePolygon.leftVertexIndex&&newLeftVertexIndex===newRightVertexIndex)activePolygons.splice(activePolygonIndex,1),--activePolygonIndex;else{activePolygon.leftVertexIndex=newLeftVertexIndex,activePolygon.rightVertexIndex=newRightVertexIndex,activePolygon.topLeft=vertices2d[newLeftVertexIndex],activePolygon.topRight=vertices2d[newRightVertexIndex];let nextLeftVertexIndex=newLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0),activePolygon.bottomLeft=vertices2d[nextLeftVertexIndex];let nextRightVertexIndex=newRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),activePolygon.bottomRight=vertices2d[nextRightVertexIndex]}}}let nextYcoordinate;if(yIndex>=yCoordinates.length-1)activePolygons=[],nextYcoordinate=null;else{nextYcoordinate=Number(yCoordinates[yIndex+1]);const middleYcoordinate=.5*(yCoordinate+nextYcoordinate),startingPolygonIndexes=topy2polygonIndexes.get(yCoordinate);for(const polygonIndexKey in startingPolygonIndexes){const polygonIndex=startingPolygonIndexes[polygonIndexKey],vertices2d=polygonVertices2d[polygonIndex],numVertices=vertices2d.length,topVertexIndex=polygonTopVertexIndexes[polygonIndex];let topLeftVertexIndex=topVertexIndex;for(;;){let i=topLeftVertexIndex+1;if(i>=numVertices&&(i=0),vertices2d[i][1]!==yCoordinate)break;if(i===topVertexIndex)break;topLeftVertexIndex=i}let topRightVertexIndex=topVertexIndex;for(;;){let i=topRightVertexIndex-1;if(i<0&&(i=numVertices-1),vertices2d[i][1]!==yCoordinate)break;if(i===topLeftVertexIndex)break;topRightVertexIndex=i}let nextLeftVertexIndex=topLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0);let nextRightVertexIndex=topRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1);const newActivePolygon={polygonIndex:polygonIndex,leftVertexIndex:topLeftVertexIndex,rightVertexIndex:topRightVertexIndex,topLeft:vertices2d[topLeftVertexIndex],topRight:vertices2d[topRightVertexIndex],bottomLeft:vertices2d[nextLeftVertexIndex],bottomRight:vertices2d[nextRightVertexIndex]};insertSorted(activePolygons,newActivePolygon,((el1,el2)=>{const x1=interpolateBetween2DPointsForY(el1.topLeft,el1.bottomLeft,middleYcoordinate),x2=interpolateBetween2DPointsForY(el2.topLeft,el2.bottomLeft,middleYcoordinate);return x1>x2?1:x10){const prevOutPolygon=newOutPolygonRow[newOutPolygonRow.length-1],d1=distance(outPolygon.topLeft,prevOutPolygon.topRight),d2=distance(outPolygon.bottomLeft,prevOutPolygon.bottomRight);d10){const prevContinuedIndexes=new Set,matchedIndexes=new Set;for(let i=0;i=0)&&(rightLineContinues||d2>=0)&&(thisPolygon.outPolygon=prevPolygon.outPolygon,thisPolygon.leftLineContinues=leftLineContinues,thisPolygon.rightLineContinues=rightLineContinues,prevContinuedIndexes.add(ii));break}}}for(let ii=0;iiEPS&&prevPolygon.outPolygon.leftPoints.push(prevPolygon.bottomLeft),prevPolygon.outPolygon.leftPoints.reverse();const vertices3d=prevPolygon.outPolygon.rightPoints.concat(prevPolygon.outPolygon.leftPoints).map((point2d=>orthonormalFormula.to3D(point2d))),polygon=fromVerticesAndPlane(vertices3d,plane$1);polygon.vertices.length&&destPolygons.push(polygon)}}for(let i=0;iEPS&&thisPolygon.outPolygon.rightPoints.push(thisPolygon.topRight))}prevOutPolygonRow=newOutPolygonRow}return destPolygons})(group);destPolygons.push(...reTessellateCoplanarPolygons)}else destPolygons.push(group)}));const result=create$8(destPolygons);return result.isRetesselated=!0,result})(newGeometry),newGeometry},subtract=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("subtract wrong number of arguments");if(!(shapes=>{let previousType;for(const shape of shapes){let currentType=0;if(isA$5(shape)&&(currentType=1),isA$3(shape)&&(currentType=2),isA$2(shape)&&(currentType=3),previousType&¤tType!==previousType)return!1;previousType=currentType}return!0})(geometries))throw new Error("subtract arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return((...geometries)=>{let newGeometry=(geometries=flatten$1(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,2)})),newGeometry})(geometries);if(isA$3(geometry))return subtractGeom3(geometries);throw new Error("subtract unsupported geometry type")},createTransform=(center,rotation,scale,scaleOrientation,translation)=>{const matrix=index$c.create(),temp=index$c.create();return index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,translation)),index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,center)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,rotation[3],rotation)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,scaleOrientation[3],scaleOrientation)),index$c.multiply(matrix,matrix,index$c.fromScaling(temp,scale)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,scaleOrientation[3],index$d.negate(index$d.create(),scaleOrientation))),index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,index$d.negate(index$d.create(),center))),matrix},x3dTypes_X3D=0,x3dTypes_UNIT=1,x3dTypes_META=2,x3dTypes_SCENE=3,x3dTypes_TRANSFORM=4,x3dTypes_SHAPE=5,x3dTypes_GROUP=6,x3dTypes_APPEARANCE=7,x3dTypes_TRIANGLESET=10,x3dTypes_TRIANGLEFANSET=11,x3dTypes_TRIANGLESTRIPSET=12,x3dTypes_QUADSET=13,x3dTypes_INDEXEDTRIANGLESET=14,x3dTypes_INDEXEDTRIANGLEFANSET=15,x3dTypes_INDEXEDTRIANGLESTRIPSET=16,x3dTypes_INDEXEDQUADSET=17,x3dTypes_ELEVATIONGRID=18,x3dTypes_INDEXEDFACESET=19,x3dTypes_LINESET=20,x3dTypes_INDEXEDLINESET=21,x3dTypes_BOX=50,x3dTypes_CONE=51,x3dTypes_CYLINDER=52,x3dTypes_SPHERE=53,x3dTypes_EXTRUSION=54,x3dTypes_ARC2D=61,x3dTypes_ARCCLOSE2D=62,x3dTypes_CIRCLE2D=63,x3dTypes_DISK2D=64,x3dTypes_POLYLINE2D=65,x3dTypes_RECTANGLE2D=66,x3dTypes_TRIANGLESET2D=67,x3dTypes_COLOR=91,x3dTypes_COORDINATE=92,x3dTypes_MATERIAL=93,x3dGroup=element=>{const obj={definition:x3dTypes_GROUP,objects:[]};return obj},isZeroVector=vector=>vector[0]+0===0&&vector[1]+0===0&&vector[2]+0===0,calculateZaxis=(z,p,i,n)=>{const a=index$d.subtract(index$d.create(),n,i),b=index$d.subtract(index$d.create(),p,i);return index$d.normalize(z,index$d.cross(z,a,b))},extrudeX3D=x3dshape=>{let{beginCap:beginCap,endCap:endCap,crossSection:crossSection,orientations:orientations,scales:scales,spine:spine}=Object.assign({},x3dshape);if(index$3.measureArea(index$3.create(crossSection))<0&&crossSection.reverse(),1===scales.length&&(scales=spine.map((s=>scales[0]))),1===orientations.length&&(orientations=spine.map((s=>orientations[0]))),spine.length!==scales.length||spine.length!==orientations.length)throw new Error(`invalid X3D specification; spine scale orientaion length must be the same; ${spine.length}`);const initialShape=index$a.create([crossSection]),initialSlice=index$2.fromGeom2(initialShape);let yaxes=(spine=>{const slength=spine.length,closed=index$d.equals(spine[0],spine[slength-1]),yaxes=[];for(let i=0;i{const slength=spine.length,closed=index$d.equals(spine[0],spine[slength-1]),zaxes=[];let previousZaxis;for(let i=0;i2&&calculateZaxis(zaxis,spine[0],spine[1],spine[2]):i===slength-1?closed?calculateZaxis(zaxis,spine[slength-2],spine[0],spine[1]):slength>2&&calculateZaxis(zaxis,spine[slength-3],spine[slength-2],spine[slength-1]):calculateZaxis(zaxis,spine[i-1],spine[i],spine[i+1]),previousZaxis&&index$d.dot(previousZaxis,zaxis)<0&&index$d.negate(zaxis,zaxis),zaxes.push(zaxis),previousZaxis=zaxis}if(isZeroVector(zaxes[0]))for(let i=1;i{const xaxes=[];for(let i=0;iacc&&isZeroVector(axis)),!0)&&(index$d.subtract(y0direction,spine[1],spine[0]),index$c.fromVectorRotation(y0matrix,index$d.fromValues(0,0,1),y0direction),xaxes=xaxes.map((axis=>[1,0,0])),yaxes=yaxes.map((axis=>[0,1,0])),zaxes=zaxes.map((axis=>[0,0,1]))),((options,base)=>{const defaults={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,callback:defaultCallback},{numberOfSlices:numberOfSlices,capStart:capStart,capEnd:capEnd,close:close,callback:generate}=Object.assign({},defaults,options);if(numberOfSlices<2)throw new Error("numberOfSlices must be 2 or more");const sMax=numberOfSlices-1;let startSlice=null,endSlice=null,prevSlice=null,polygons=[];for(let s=0;s(out[0]=xaxis[0],out[1]=yaxis[0],out[2]=zaxis[0],out[3]=0,out[4]=xaxis[1],out[5]=yaxis[1],out[6]=zaxis[1],out[7]=0,out[8]=xaxis[2],out[9]=yaxis[2],out[10]=zaxis[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out))(index$c.create(),xaxis,yaxis,zaxis),orientationMatrix=index$c.fromRotation(index$c.create(),orientation[3],orientation),rotationMatrix=index$c.create();index$c.multiply(rotationMatrix,y0matrix,rotationMatrix),index$c.multiply(rotationMatrix,scpMatrix,rotationMatrix),index$c.multiply(rotationMatrix,orientationMatrix,rotationMatrix),index$c.multiply(rotationMatrix,translationMatrix,rotationMatrix);let newslice=base;return newslice=index$2.transform(scaleMatrix,newslice),newslice=index$2.transform(rotationMatrix,newslice),newslice}},initialSlice)},findNode=(x3dtype,objects)=>objects.find((object=>object.definition===x3dtype)),findColor=(objects,options)=>{const appearance=findNode(x3dTypes_APPEARANCE,objects);let material;return appearance&&(material=findNode(x3dTypes_MATERIAL,appearance.objects),material)?material.color?material.color:null:(material=findNode(x3dTypes_MATERIAL,objects),material&&material.color?material.color:null)},pointsToString=triangle=>`[\n ${triangle.map((point=>(point=>`[${point}]`)(point))).join(",\n ")}\n ]`,createColors=(shape,color)=>{if(!color)return null;if(!Array.isArray(shape.colorIndex))return null;let colors=null;var colorIndex,faceColors;return!0===shape.colorPerVertex?colors=((colorIndex,vertexColors)=>{if(!Array.isArray(colorIndex)||!Array.isArray(vertexColors))return null;if(colorIndex.length<0||!Array.isArray(colorIndex[0]))return console.log("ERROR: WRONG FORMAT FOR VERTEXCOLORS"),null;const colors=[];for(let i=0;ifaceColors[index]?faceColors[index]:null)):null),colors},convertLine=(options,objects)=>{let shape=findNode(x3dTypes_INDEXEDLINESET,objects);if(shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),indexes=shape.indexes,color=findNode(x3dTypes_COLOR,shape.objects);if(coordinate&&indexes){const pointsSet=indexes.map((index=>{let points=index.map((i=>coordinate.points[i]));return points.findIndex((p=>0!==p[2]))>=0&&(console.warn("WARNING: unsupported 3D indexed line set was ignored"),points=[]),points}));!0===shape.colorPerVertex?shape.colorIndex=indexes:shape.colorIndex=indexes.map(((index,i)=>i));return{pointsSet:pointsSet,colors:createColors(shape,color)}}}if(shape=findNode(x3dTypes_LINESET,objects),shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),color=findNode(x3dTypes_COLOR,shape.objects),counts=shape.vertexCount;if(coordinate&&counts){let vi=0;const pointsSet=counts.map((count=>{let points=[];for(let i=0;i0!==p[2]))>=0&&(console.warn("WARNING: unsupported 3D line set was ignored"),points=[]),points}));if(!0===shape.colorPerVertex){let ci=0;shape.colorIndex=counts.map((count=>{const index=[];for(let i=0;ii));return{pointsSet:pointsSet,colors:createColors(shape,color)}}}return null},convertMesh=(options,objects)=>{let shape=findNode(x3dTypes_TRIANGLESET,objects);if(shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),color=findNode(x3dTypes_COLOR,shape.objects);if(coordinate){const points=coordinate.points,numpoints=points.length,numfaces=Math.trunc(numpoints/3),faces=[];for(let ti=0;ti2){const points=coordinate.points,numfaces=Math.trunc(index.length/3),faces=[];for(let fi=0;fi0){const points=coordinate.points,numfans=fans.length,faces=[];for(let fi=0;fi0){const points=coordinate.points,numstrips=strips.length,faces=[];for(let si=0;si3){const points=coordinate.points,numquads=Math.trunc(index.length/4),faces=[];for(let qi=0;qi0){const points=coordinate.points;return{type:`indexed faces (${faces.length})`,points:points,faces:faces,colors:createColors(shape,color),orientation:shape.ccw?"outward":"inward"}}}if(shape=findNode(x3dTypes_ELEVATIONGRID,objects),shape){const height=shape.height,color=findNode(x3dTypes_COLOR,shape.objects);if(height&&height.length>0){const xDimension=shape.xDimension,xSpacing=shape.xSpacing,zDimension=shape.zDimension,zSpacing=shape.zSpacing,points=[];let vi=0;for(let z0=0;z0=distances[0]&&distances[1]>=distances[2]&&distances[1]>=distances[3]&&(apexi=1),distances[2]>=distances[0]&&distances[2]>=distances[1]&&distances[2]>=distances[3]&&(apexi=2),distances[3]>=distances[0]&&distances[3]>=distances[1]&&distances[3]>=distances[2]&&(apexi=3),0===apexi&&faces.push([iTL,iBR,iTR],[iTL,iBL,iBR]),1===apexi&&faces.push([iTR,iBL,iBR],[iTR,iTL,iBL]),2===apexi&&faces.push([iBL,iTR,iTL],[iBL,iBR,iTR]),3===apexi&&faces.push([iBR,iTL,iBL],[iBR,iTR,iTL])}const orientation=shape.ccw?"outward":"inward";!0===shape.colorPerVertex&&(shape.colorIndex=faces);return{type:`elevation grid (${xDimension} X ${zDimension})`,points:points,faces:faces,colors:createColors(shape,color),orientation:orientation}}}return null},instantiateMesh=(options,objects)=>{let geometry;const components=convertMesh(0,objects);return components&&(geometry=(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})(components)),geometry},translateMesh=(options,objects)=>{const components=convertMesh(0,objects);if(components){const{type:type,points:points,faces:faces,colors:colors,orientation:orientation}=components;return((type,points,faces,colors,orientation)=>{const colorsCode=Array.isArray(colors)?pointsToString(colors):"null";return{primitive:"polyhedron({points, faces, colors, orientation})",code:`\n // 3D ${type} set: ${points.length} points, ${faces.length} faces\n const points = ${pointsToString(points)}\n const faces = ${pointsToString(faces)}\n const colors = ${colorsCode}\n const orientation = '${orientation}'\n`}})(type,points,faces,colors,orientation)}return null},translateShape=(options,object)=>{let code=`\n// shape\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects,color=findColor(objects);let primitive,shape=findNode(x3dTypes_BOX,objects);if(shape)primitive=`cuboid({size: [${shape.size}]})`;else if(shape=findNode(x3dTypes_CONE,objects),shape)code+=` const shape = rotateX(-Math.PI/2, cylinderElliptic({startRadius: [${shape.bottomRadius},${shape.bottomRadius}], height: ${shape.height}, segments: ${shape.subdivision}, endRadius: [${shape.topRadius}, ${shape.topRadius}]}))\n`,primitive="shape";else if(shape=findNode(x3dTypes_CYLINDER,objects),shape)code+=` const shape = rotateX(-Math.PI/2, cylinder({radius: ${shape.radius}, height: ${shape.height}, segments: ${shape.subdivision}}))\n`,primitive="shape";else if(shape=findNode(x3dTypes_SPHERE,objects),shape)primitive=`sphere({radius: ${shape.radius}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_EXTRUSION,objects),shape){const geometry=extrudeX3D(shape);code+=` const polygons = [\n ${index$6.toPolygons(geometry).map((polygon=>pointsToString(index$7.toVertices(polygon)))).join(",\n ")}\n]\n`,primitive="geom3.fromPoints(polygons)"}if(!primitive)if(shape=findNode(x3dTypes_ARC2D,objects),shape)primitive=`arc({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_ARCCLOSE2D,objects),shape)primitive="PIE"===shape.closureType?`circle({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})`:`geom2.create([path2.toPoints(path2.close(arc({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})))])`;else if(shape=findNode(x3dTypes_CIRCLE2D,objects),shape)primitive=`arc({radius: ${shape.radius}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_DISK2D,objects),shape)primitive=shape.innerRadius===shape.outerRadius?`arc({radius: ${shape.outerRadius}, segments: ${shape.subdivision}})`:0===shape.innerRadius?`circle({radius: ${shape.outerRadius}, segments: ${shape.subdivision}})`:`subtract(circle({radius: ${shape.outerRadius}, segments: ${shape.subdivision}}), primitives.circle({radius: ${shape.innerRadius}, segments: ${shape.subdivision}}))`;else if(shape=findNode(x3dTypes_POLYLINE2D,objects),shape){primitive=`line([[${shape.lineSegments.join("], [")}]])`}else if(shape=findNode(x3dTypes_RECTANGLE2D,objects),shape)primitive=`rectangle({size: [${shape.size}]})`;else if(shape=findNode(x3dTypes_TRIANGLESET2D,objects),shape){const numpoints=shape.vertices.length,numfaces=Math.trunc(numpoints/3);code+=`\n // 2D triangle set: ${numpoints} points, ${numfaces} faces\n const vertices = ${pointsToString(shape.vertices)}\n const triangles = []\n for (let i = 0; i < ${numfaces}; i = i + 3) {\n triangles.push(geom2.create([[vertices[i], vertices[i + 1], vertices[i + 2]]]))\n }\n`,primitive="triangles"}let results=translateMesh(0,objects);return results&&(primitive=results.primitive,code+=results.code),results=((options,objects)=>{const components=convertLine(0,objects);if(components){const{pointsSet:pointsSet,colors:colors}=components;let code=" let lines = []\n";return pointsSet.forEach(((points,i)=>{if(colors){const lineColor=colors[i];code+=` const line${i} = colorize([${lineColor}], primitives.line(${pointsToString(points)}))\n lines.push(line${i})\n`}else code+=` const line${i} = primitives.line(${pointsToString(points)})\n lines.push(line${i})\n`})),{primitive:"...lines",code:code}}return null})(0,objects),results&&(primitive=results.primitive,code+=results.code),primitive&&(code+=color?` objects.push(colorize([${color}], ${primitive}))`:` objects.push(${primitive})`),code+="\n return objects\n}\n",code},translatedList=[],translateDefinition=(options,object)=>{if(translatedList.includes(object.id))return"";translatedList.push(object.id);let code="";switch(object.definition){case x3dTypes_TRANSFORM:code+=((options,object)=>{let code=`\n// transform\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects;for(let i=0;i{let code=`\n// group\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects;for(let i=0;iobjects.reduce(((code,object,index)=>code+translateDefinition(options,object)),"");var saxes={},ed5$1={};!function(exports){ + */var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:fromValues$4,fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,measureBoundingSphere$1=polygon=>{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$6=Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");3===color.length&&(color=[color[0],color[1],color[2],1]);const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):Array.isArray(object)?colorize(color,...object):(object.color=color,object)));return 1===results.length?results[0]:results},flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),equals$3=(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices=vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours)),toEdges=slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges};class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}const toPolygons=slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)};var index$2=Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:equals$3,fromGeom2:fromGeom2,fromVertices:fromVertices,isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:toEdges,toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:toPolygons,toString:slice=>{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:transform$3,validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGT=(value,constant)=>Number.isFinite(value)&&value>constant,isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGT(radius,0))throw new Error("radius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS*EPS)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps)),point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},circle=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],(options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:TAU,segments:32};let{center:center,height:height,startRadius:startRadius,startAngle:startAngle,endRadius:endRadius,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGT(height,0))throw new Error("height must be greater then zero");if(!isNumberArray(startRadius,2))throw new Error("startRadius must be an array of X and Y values");if(!startRadius.every((n=>n>=0)))throw new Error("startRadius values must be positive");if(!isNumberArray(endRadius,2))throw new Error("endRadius must be an array of X and Y values");if(!endRadius.every((n=>n>=0)))throw new Error("endRadius values must be positive");if(endRadius.every((n=>0===n))&&startRadius.every((n=>0===n)))throw new Error("at least one radius must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(startRadius[0],startRadius[1],endRadius[0],endRadius[1]),minAngle=Math.acos((minRadius*minRadius+minRadius*minRadius-EPS*EPS)/(2*minRadius*minRadius));if(rotation{const angle=slice*rotation+startAngle;return scale$3(v1,axisX,radius[0]*cos(angle)),scale$3(v2,axisY,radius[1]*sin(angle)),add$1(v1,v1,v2),scale$3(v3,ray,stack),add$1(v3,v3,start),add$1([0,0,0],v1,v3)},fromVertices=(...vertices)=>{const newVertices=vertices.map((vertex=>add$1([0,0,0],vertex,center)));return create$7(newVertices)},polygons=[];for(let i=0;i0&&startRadius[1]>0&&polygons.push(fromVertices(start,genVertex(0,t1,startRadius),genVertex(0,t0,startRadius))),(startRadius[0]>0||startRadius[1]>0)&&polygons.push(fromVertices(genVertex(0,t0,startRadius),genVertex(0,t1,startRadius),genVertex(1,t0,endRadius))),endRadius[0]>0&&endRadius[1]>0&&polygons.push(fromVertices(end,genVertex(1,t0,endRadius),genVertex(1,t1,endRadius))),(endRadius[0]>0||endRadius[1]>0)&&polygons.push(fromVertices(genVertex(1,t0,endRadius),genVertex(0,t1,startRadius),genVertex(1,t1,endRadius))))}return rotation{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},sphere=options=>{let{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius,radius],(options=>{const{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(radius,3))throw new Error("radius must be an array of X, Y and Z values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===radius[0]||0===radius[1]||0===radius[2])return create$8();const xVector=scale$3([0,0,0],normalize$1([0,0,0],axes[0]),radius[0]),yVector=scale$3([0,0,0],normalize$1([0,0,0],axes[1]),radius[1]),zVector=scale$3([0,0,0],normalize$1([0,0,0],axes[2]),radius[2]),qSegments=Math.round(segments/4);let prevCylinderVertex;const polygons=[],p1=[0,0,0],p2=[0,0,0];for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(p1,xVector,cos(angle)),scale$3(p2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch;for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);if(slice2>0){let vertex,vertices=[];vertex=subtract$3([0,0,0],scale$3(p1,prevCylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),vertex=subtract$3([0,0,0],scale$3(p1,cylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),slice2a===b?a:a{const multiple=newLength/edges.length;if(1===multiple)return edges;const divisor=fromValues$3(multiple,multiple,multiple),newEdges=[];return edges.forEach((edge=>{const increment=subtract$3([0,0,0],edge[1],edge[0]);divide$1(increment,increment,divisor);let prev=edge[0];for(let i=1;i<=multiple;++i){const next=add$1([0,0,0],prev,increment);newEdges.push([prev,next]),prev=next}})),newEdges},EPSAREA=EPS*EPS/2*Math.sin(Math.PI/3),extrudeWalls=(slice0,slice1)=>{let edges0=toEdges(slice0),edges1=toEdges(slice1);if(edges0.length!==edges1.length){const newLength=(a=edges0.length)*(b=edges1.length)/gcd(a,b);newLength!==edges0.length&&(edges0=repartitionEdges(newLength,edges0)),newLength!==edges1.length&&(edges1=repartitionEdges(newLength,edges1))}var a,b;const walls=[];return edges0.forEach(((edge0,i)=>{const edge1=edges1[i],poly0=create$7([edge0[0],edge0[1],edge1[1]]),poly0area=measureArea$2(poly0);Number.isFinite(poly0area)&&poly0area>EPSAREA&&walls.push(poly0);const poly1=create$7([edge0[0],edge1[1],edge1[0]]),poly1area=measureArea$2(poly1);Number.isFinite(poly1area)&&poly1area>EPSAREA&&walls.push(poly1)})),walls},defaultCallback=(progress,index,base)=>{let baseSlice=null;return isA$5(base)&&(baseSlice=fromGeom2(base)),isA$4(base)&&(baseSlice=fromVertices(toVertices$1(base))),0===progress||1===progress?transform$3(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[0,0,progress]),baseSlice):null},rotate=(angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?rotate(angles,...object):object));return 1===results.length?results[0]:results},rotateX=(angle,...objects)=>rotate([angle,0,0],...objects),flattenHelper=(arr,out)=>(Array.isArray(arr)?arr.forEach((child=>flattenHelper(child,out))):null!=arr&&void 0!==arr&&out.push(arr),out),DEFAULT_COMPARE=(a,b)=>a>b?1:a{const N=new Node$1(null,null);let l=N,r=N;for(;;){const cmp=comparator(i,t.key);if(cmp<0){if(null===t.left)break;if(comparator(i,t.left.key)<0){const y=t.left;if(t.left=y.right,y.right=t,null===(t=y).left)break}r.left=t,r=t,t=t.left}else{if(!(cmp>0))break;if(null===t.right)break;if(comparator(i,t.right.key)>0){const y=t.right;if(t.right=y.left,y.left=t,null===(t=y).right)break}l.right=t,l=t,t=t.right}}return l.right=t.left,r.left=t.right,t.left=N.right,t.right=N.left,t},insert=(i,data,t,comparator)=>{const node=new Node$1(i,data);if(null===t)return node.left=node.right=null,node;const cmp=comparator(i,(t=splay(i,t,comparator)).key);return cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>=0&&(node.right=t.right,node.left=t,t.right=null),node},split=(key,v,comparator)=>{let left=null,right=null;if(v){const cmp=comparator((v=splay(key,v,comparator)).key,key);0===cmp?(left=v.left,right=v.right):cmp<0?(right=v.right,v.right=null,left=v):(left=v.left,v.left=null,right=v)}return{left:left,right:right}},printRow=(root,prefix,isTail,out,printNode)=>{if(root){out(`${prefix}${isTail?"└── ":"├── "}${printNode(root)}\n`);const indent=prefix+(isTail?" ":"│ ");root.left&&printRow(root.left,indent,!1,out,printNode),root.right&&printRow(root.right,indent,!0,out,printNode)}};class Tree$1{constructor(comparator=DEFAULT_COMPARE){this._comparator=comparator,this._root=null,this._size=0}insert(key,data){return this._size++,this._root=insert(key,data,this._root,this._comparator),this._root}add(key,data){const node=new Node$1(key,data);null===this._root&&(node.left=node.right=null,this._size++,this._root=node);const comparator=this._comparator,t=splay(key,this._root,comparator),cmp=comparator(key,t.key);return 0===cmp?this._root=t:(cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>0&&(node.right=t.right,node.left=t,t.right=null),this._size++,this._root=node),this._root}remove(key){this._root=this._remove(key,this._root,this._comparator)}_remove(i,t,comparator){let x;return null===t?null:0===comparator(i,(t=splay(i,t,comparator)).key)?(null===t.left?x=t.right:(x=splay(i,t.left,comparator),x.right=t.right),this._size--,x):t}pop(){let node=this._root;if(node){for(;node.left;)node=node.left;return this._root=splay(node.key,this._root,this._comparator),this._root=this._remove(node.key,this._root,this._comparator),{key:node.key,data:node.data}}return null}findStatic(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return current;current=cmp<0?current.left:current.right}return null}find(key){return this._root&&(this._root=splay(key,this._root,this._comparator),0!==this._comparator(key,this._root.key))?null:this._root}contains(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return!0;current=cmp<0?current.left:current.right}return!1}forEach(visitor,ctx){let current=this._root;const Q=[];let done=!1;for(;!done;)null!==current?(Q.push(current),current=current.left):0!==Q.length?(current=Q.pop(),visitor.call(ctx,current),current=current.right):done=!0;return this}range(low,high,fn,ctx){const Q=[],compare=this._comparator;let cmp,node=this._root;for(;0!==Q.length||node;)if(node)Q.push(node),node=node.left;else{if(node=Q.pop(),cmp=compare(node.key,high),cmp>0)break;if(compare(node.key,low)>=0&&fn.call(ctx,node))return this;node=node.right}return this}keys(){const keys=[];return this.forEach((({key:key})=>keys.push(key))),keys}values(){const values=[];return this.forEach((({data:data})=>values.push(data))),values}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(index){let current=this._root,done=!1,i=0;const Q=[];for(;!done;)if(current)Q.push(current),current=current.left;else if(Q.length>0){if(current=Q.pop(),i===index)return current;i++,current=current.right}else done=!0;return null}next(d){let root=this._root,successor=null;if(d.right){for(successor=d.right;successor.left;)successor=successor.left;return successor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?(successor=root,root=root.left):root=root.right}return successor}prev(d){let root=this._root,predecessor=null;if(null!==d.left){for(predecessor=d.left;predecessor.right;)predecessor=predecessor.right;return predecessor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?root=root.left:(predecessor=root,root=root.right)}return predecessor}clear(){return this._root=null,this._size=0,this}toList(){return toList(this._root)}load(keys,values=[],presort=!1){let size=keys.length;const comparator=this._comparator;if(presort&&sort(keys,values,0,size-1,comparator),null===this._root)this._root=loadRecursive(keys,values,0,size),this._size=size;else{const mergedList=mergeLists(this.toList(),createList(keys,values),comparator);size=this._size+size,this._root=sortedListToBST({head:mergedList},0,size)}return this}isEmpty(){return null===this._root}size(){return this._size}root(){return this._root}toString(printNode=(n=>String(n.key))){const out=[];return printRow(this._root,"",!0,(v=>out.push(v)),printNode),out.join("")}update(key,newKey,newData){const comparator=this._comparator;let{left:left,right:right}=split(key,this._root,comparator);comparator(key,newKey)<0?right=insert(newKey,newData,right,comparator):left=insert(newKey,newData,left,comparator),this._root=((left,right,comparator)=>null===right?left:(null===left||((right=splay(left.key,right,comparator)).left=left),right))(left,right,comparator)}split(key){return split(key,this._root,this._comparator)}*[Symbol.iterator](){let n=this.minNode();for(;n;)yield n,n=this.next(n)}}const loadRecursive=(keys,values,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),key=keys[middle],data=values[middle],node=new Node$1(key,data);return node.left=loadRecursive(keys,values,start,middle),node.right=loadRecursive(keys,values,middle+1,end),node}return null},createList=(keys,values)=>{const head=new Node$1(null,null);let p=head;for(let i=0;i{let current=root;const Q=[];let done=!1;const head=new Node$1(null,null);let p=head;for(;!done;)current?(Q.push(current),current=current.left):Q.length>0?(current=p=p.next=Q.pop(),current=current.right):done=!0;return p.next=null,head.next},sortedListToBST=(list,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),left=sortedListToBST(list,start,middle),root=list.head;return root.left=left,list.head=list.head.next,root.right=sortedListToBST(list,middle+1,end),root}return null},mergeLists=(l1,l2,compare)=>{const head=new Node$1(null,null);let p=head,p1=l1,p2=l2;for(;null!==p1&&null!==p2;)compare(p1.key,p2.key)<0?(p.next=p1,p1=p1.next):(p.next=p2,p2=p2.next),p=p.next;return null!==p1?p.next=p1:null!==p2&&(p.next=p2),head.next},sort=(keys,values,left,right,compare)=>{if(left>=right)return;const pivot=keys[left+right>>1];let i=left-1,j=right+1;for(;;){do{i++}while(compare(keys[i],pivot)<0);do{j--}while(compare(keys[j],pivot)>0);if(i>=j)break;let tmp=keys[i];keys[i]=keys[j],keys[j]=tmp,tmp=values[i],values[i]=values[j],values[j]=tmp}sort(keys,values,left,j,compare),sort(keys,values,j+1,right,compare)},computeFields=(event,prev,operation)=>{null===prev?(event.inOut=!1,event.otherInOut=!0):(event.isSubject===prev.isSubject?(event.inOut=!prev.inOut,event.otherInOut=prev.otherInOut):(event.inOut=!prev.otherInOut,event.otherInOut=prev.isVertical()?!prev.inOut:prev.inOut),prev&&(event.prevInResult=!inResult(prev,operation)||prev.isVertical()?prev.prevInResult:prev));const isInResult=inResult(event,operation);event.resultTransition=isInResult?determineResultTransition(event,operation):0},inResult=(event,operation)=>{switch(event.type){case 0:switch(operation){case 0:return!event.otherInOut;case 1:return event.otherInOut;case 2:return event.isSubject&&event.otherInOut||!event.isSubject&&!event.otherInOut;case 3:return!0}break;case 2:return 0===operation||1===operation;case 3:return 2===operation;case 1:return!1}return!1},determineResultTransition=(event,operation)=>{const thisIn=!event.inOut,thatIn=!event.otherInOut;let isIn;switch(operation){case 0:isIn=thisIn&&thatIn;break;case 1:isIn=thisIn||thatIn;break;case 3:isIn=thisIn^thatIn;break;case 2:isIn=event.isSubject?thisIn&&!thatIn:thatIn&&!thisIn}return isIn?1:-1};class SweepEvent{constructor(point,left,otherEvent,isSubject,edgeType){this.left=left,this.point=point,this.otherEvent=otherEvent,this.isSubject=isSubject,this.type=edgeType||0,this.inOut=!1,this.otherInOut=!1,this.prevInResult=null,this.resultTransition=0,this.otherPos=-1,this.outputContourId=-1,this.isExteriorRing=!0}isBelow(p){const p0=this.point,p1=this.otherEvent.point;return this.left?(p0[0]-p[0])*(p1[1]-p[1])-(p1[0]-p[0])*(p0[1]-p[1])>0:(p1[0]-p[0])*(p0[1]-p[1])-(p0[0]-p[0])*(p1[1]-p[1])>0}isAbove(p){return!this.isBelow(p)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return 0!==this.resultTransition}clone(){const copy=new SweepEvent(this.point,this.left,this.otherEvent,this.isSubject,this.type);return copy.contourId=this.contourId,copy.resultTransition=this.resultTransition,copy.prevInResult=this.prevInResult,copy.isExteriorRing=this.isExteriorRing,copy.inOut=this.inOut,copy.otherInOut=this.otherInOut,copy}}const signedArea=(p0,p1,p2)=>{const res=(ax=p0[0],ay=p0[1],bx=p1[0],by=p1[1],cx=p2[0],(ay-(cy=p2[1]))*(bx-cx)-(ax-cx)*(by-cy));var ax,ay,bx,by,cx,cy;return res>0?-1:res<0?1:0},compareEvents=(e1,e2)=>{const p1=e1.point,p2=e2.point;return p1[0]>p2[0]?1:p1[0]p2[1]?1:-1:specialCases(e1,e2,p1)},specialCases=(e1,e2,p1,p2)=>e1.left!==e2.left?e1.left?1:-1:0!==signedArea(p1,e1.otherEvent.point,e2.otherEvent.point)?e1.isBelow(e2.otherEvent.point)?-1:1:!e1.isSubject&&e2.isSubject?1:-1,divideSegment=(se,p,queue)=>{const r=new SweepEvent(p,!1,se,se.isSubject),l=new SweepEvent(p,!0,se.otherEvent,se.isSubject);return r.contourId=l.contourId=se.contourId,compareEvents(l,se.otherEvent)>0&&(se.otherEvent.left=!0,l.left=!1),se.otherEvent.otherEvent=l,se.otherEvent=r,queue.push(l),queue.push(r),queue},crossProduct=(a,b)=>a[0]*b[1]-a[1]*b[0],possibleIntersection=(se1,se2,queue)=>{const inter=((a1,a2,b1,b2,noEndpointTouch)=>{const va=[a2[0]-a1[0],a2[1]-a1[1]],vb=[b2[0]-b1[0],b2[1]-b1[1]],toPoint=(p,s,d)=>[p[0]+s*d[0],p[1]+s*d[1]],e=[b1[0]-a1[0],b1[1]-a1[1]];let kross=crossProduct(va,vb),sqrKross=kross*kross;const sqrLenA=dot$1(va,va);if(sqrKross>0){const s=crossProduct(e,vb)/kross;if(s<0||s>1)return null;const t=crossProduct(e,va)/kross;return t<0||t>1?null:0===s||1===s?[toPoint(a1,s,va)]:0===t||1===t?[toPoint(b1,t,vb)]:[toPoint(a1,s,va)]}if(kross=crossProduct(e,va),sqrKross=kross*kross,sqrKross>0)return null;const sa=dot$1(va,e)/sqrLenA,sb=sa+dot$1(va,vb)/sqrLenA,smin=Math.min(sa,sb),smax=Math.max(sa,sb);return smin<=1&&smax>=0?1===smin?[toPoint(a1,smin>0?smin:0,va)]:0===smax?[toPoint(a1,smax<1?smax:1,va)]:[toPoint(a1,smin>0?smin:0,va),toPoint(a1,smax<1?smax:1,va)]:null})(se1.point,se1.otherEvent.point,se2.point,se2.otherEvent.point),nIntersections=inter?inter.length:0;if(0===nIntersections)return 0;if(1===nIntersections&&(equals$6(se1.point,se2.point)||equals$6(se1.otherEvent.point,se2.otherEvent.point)))return 0;if(2===nIntersections&&se1.isSubject===se2.isSubject)return 0;if(1===nIntersections)return equals$6(se1.point,inter[0])||equals$6(se1.otherEvent.point,inter[0])||divideSegment(se1,inter[0],queue),equals$6(se2.point,inter[0])||equals$6(se2.otherEvent.point,inter[0])||divideSegment(se2,inter[0],queue),1;const events=[];let leftCoincide=!1,rightCoincide=!1;return equals$6(se1.point,se2.point)?leftCoincide=!0:1===compareEvents(se1,se2)?events.push(se2,se1):events.push(se1,se2),equals$6(se1.otherEvent.point,se2.otherEvent.point)?rightCoincide=!0:1===compareEvents(se1.otherEvent,se2.otherEvent)?events.push(se2.otherEvent,se1.otherEvent):events.push(se1.otherEvent,se2.otherEvent),leftCoincide&&rightCoincide||leftCoincide?(se2.type=1,se1.type=se2.inOut===se1.inOut?2:3,leftCoincide&&!rightCoincide&÷Segment(events[1].otherEvent,events[0].point,queue),2):rightCoincide?(divideSegment(events[0],events[1].point,queue),3):events[0]!==events[3].otherEvent?(divideSegment(events[0],events[1].point,queue),divideSegment(events[1],events[2].point,queue),3):(divideSegment(events[0],events[1].point,queue),divideSegment(events[3].otherEvent,events[2].point,queue),3)},compareSegments=(le1,le2)=>{if(le1===le2)return 0;if(0!==signedArea(le1.point,le1.otherEvent.point,le2.point)||0!==signedArea(le1.point,le1.otherEvent.point,le2.otherEvent.point))return equals$6(le1.point,le2.point)?le1.isBelow(le2.otherEvent.point)?-1:1:le1.point[0]===le2.point[0]?le1.point[1]le2.contourId?1:-1}return 1===compareEvents(le1,le2)?1:-1};class Contour{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return null==this.holeOf}}const nextPos=(pos,resultEvents,processed,origPos)=>{let newPos=pos+1;const p=resultEvents[pos].point;let p1;const length=resultEvents.length;for(newPosorigPos;)newPos--;return newPos},initializeContourFromContext=(event,contours,contourId)=>{const contour=new Contour;if(null!=event.prevInResult){const prevInResult=event.prevInResult,lowerContourId=prevInResult.outputContourId,lowerResultTransition=prevInResult.resultTransition;if(lowerContourId<0)contour.holeOf=null,contour.depth=0;else if(lowerResultTransition>0){const lowerContour=contours[lowerContourId];if(null!=lowerContour.holeOf){const parentContourId=lowerContour.holeOf;contours[parentContourId].holeIds.push(contourId),contour.holeOf=parentContourId,contour.depth=contours[lowerContourId].depth}else contours[lowerContourId].holeIds.push(contourId),contour.holeOf=lowerContourId,contour.depth=contours[lowerContourId].depth+1}else contour.holeOf=null,contour.depth=contours[lowerContourId].depth}else contour.holeOf=null,contour.depth=0;return contour};class Queue{constructor(data,compare){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this._up(this.length++)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return--this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos=0)break;data[pos]=data[bestChild],pos=bestChild}data[pos]=item}}const max=Math.max,min=Math.min;let contourId=0;const processPolygon=(contourOrHole,isSubject,depth,queue,bbox,isExteriorRing)=>{const len=contourOrHole.length-1;let s1,s2,e1,e2;for(let i=0;i0?e2.left=!0:e1.left=!0;const x=s1[0],y=s1[1];bbox[0]=min(bbox[0],x),bbox[1]=min(bbox[1],y),bbox[2]=max(bbox[2],x),bbox[3]=max(bbox[3],y),queue.push(e1),queue.push(e2)}},EMPTY=[],toMartinez=geometry=>{const outlines=[];return toOutlines(geometry).forEach((outline=>{equals$6(outline[0],outline[outline.length-1])?outlines.push(outline):outlines.push([...outline,outline[0]])})),[outlines]},fromOutlines=outlines=>(outlines.forEach((outline=>{equals$6(outline[0],outline[outline.length-1])&&outline.pop()})),outlines=outlines.filter((o=>o.length>=3)),create$a(outlines)),boolean=(subjectGeom,clippingGeom,operation)=>{const subject=toMartinez(subjectGeom),clipping=toMartinez(clippingGeom);let trivial=((subject,clipping,operation)=>{let result=null;if(subject.length*clipping.length==0){if(0===operation)return EMPTY;2===operation?result=subject:1!==operation&&3!==operation||(result=0===subject.length?clipping:subject)}return result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,operation);if(trivial)return trivial;const sbbox=[1/0,1/0,-1/0,-1/0],cbbox=[1/0,1/0,-1/0,-1/0],eventQueue=((subject,clipping,sbbox,cbbox,operation)=>{const eventQueue=new Queue([],compareEvents);let polygonSet,isExteriorRing,i,ii,j,jj;for(i=0,ii=subject.length;i{let result=null;return(sbbox[0]>cbbox[2]||cbbox[0]>sbbox[2]||sbbox[1]>cbbox[3]||cbbox[1]>sbbox[3])&&(0===operation?result=EMPTY:2===operation?result=subject:1!==operation&&3!==operation||(result=subject.concat(clipping))),result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,sbbox,cbbox,operation),trivial)return trivial;const sortedEvents=((eventQueue,subject,clipping,sbbox,cbbox,operation)=>{const sweepLine=new Tree$1(compareSegments),sortedEvents=[],rightBound=Math.min(sbbox[2],cbbox[2]);let prev,next,begin;for(;0!==eventQueue.length;){let event=eventQueue.pop();if(sortedEvents.push(event),0===operation&&event.point[0]>rightBound||2===operation&&event.point[0]>sbbox[2])break;if(event.left){next=prev=sweepLine.insert(event),begin=sweepLine.minNode(),prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next);const prevEvent=prev?prev.key:null;let prevprevEvent;if(computeFields(event,prevEvent,operation),next&&2===possibleIntersection(event,next.key,eventQueue)&&(computeFields(event,prevEvent,operation),computeFields(next.key,event,operation)),prev&&2===possibleIntersection(prev.key,event,eventQueue)){let prevprev=prev;prevprev=prevprev!==begin?sweepLine.prev(prevprev):null,prevprevEvent=prevprev?prevprev.key:null,computeFields(prevEvent,prevprevEvent,operation),computeFields(event,prevEvent,operation)}}else event=event.otherEvent,next=prev=sweepLine.find(event),prev&&next&&(prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next),sweepLine.remove(event),next&&prev&&possibleIntersection(prev.key,next.key,eventQueue))}return sortedEvents})(eventQueue,0,0,sbbox,cbbox,operation),contours=(sortedEvents=>{const resultEvents=(sortedEvents=>{let event,i,len,tmp;const resultEvents=[];for(i=0,len=sortedEvents.length;i{processed[pos]=!0,pos=resultEvents.length)&&resultEvents[pos];);contours.push(contour)}return contours})(sortedEvents),polygons=[];for(let i=0;i=0;k--)hole.push(holePoints[k]);rings.push(hole)}polygons.push(rings)}}return polygons?fromOutlines(polygons.flat()):create$a()},interpolateBetween2DPointsForY=(point1,point2,y)=>{let t,f1=y-point1[1],f2=point2[1]-point1[1];return f2<0&&(f1=-f1,f2=-f2),t=f1<=0?0:f1>=f2?1:f2<1e-10?.5:f1/f2,point1[0]+t*(point2[0]-point1[0])};class OrthonormalFormula{constructor(plane){this.plane=plane;const rightVector=orthogonal([0,0,0],plane);this.v=normalize$1(rightVector,cross$1(rightVector,plane,rightVector)),this.u=cross$1([0,0,0],this.v,plane),this.planeOrigin=scale$3([0,0,0],plane,plane[3]),this.basisMap=new Map}getProjectionMatrix(){return fromValues$4(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)}getInverseProjectionMatrix(){return fromValues$4(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,this.planeOrigin[0],this.planeOrigin[1],this.planeOrigin[2],1)}to2D(vertex){const point=fromValues$2(dot$2(vertex,this.u),dot$2(vertex,this.v));return this.basisMap.set(point,vertex),point}to3D(point){const original=this.basisMap.get(point);if(original)return original;const v1=scale$3([0,0,0],this.u,point[0]),v2=scale$3([0,0,0],this.v,point[1]),v3=add$1(v1,v1,this.planeOrigin);return add$1(v2,v2,v3)}}const insertSorted=(array,element,compareFunc)=>{let leftBound=0,rightBound=array.length;for(;rightBound>leftBound;){const testIndex=Math.floor((leftBound+rightBound)/2);compareFunc(element,array[testIndex])>0?leftBound=testIndex+1:rightBound=testIndex}array.splice(leftBound,0,element)},fnNumberSort=(a,b)=>a-b,classifyPolygons=polygons=>{let clusters=[polygons];const nonCoplanar=[];for(let component=3;component>=0;component--){const maybeCoplanar=[],tolerance=3===component?15e-9:1e-13;clusters.forEach((cluster=>{cluster.sort(byPlaneComponent(component,tolerance));let startIndex=0;for(let i=1;itolerance&&(i-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex,i)),startIndex=i);cluster.length-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex))})),clusters=maybeCoplanar}const result=[];return clusters.forEach((cluster=>{cluster[0]&&(result[cluster[0].index]=cluster)})),nonCoplanar.forEach((polygon=>{result[polygon.index]=polygon})),result},byPlaneComponent=(component,tolerance)=>(a,b)=>a.plane[component]-b.plane[component]>tolerance?1:b.plane[component]-a.plane[component]>tolerance?-1:0;class Node{constructor(parent){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=parent}invert(){const queue=[this];let node;for(let i=0;i{treeNode.isRemoved()||treeNode.splitByPlane(plane,coplanarFrontNodes,backNodes,frontNodes,backNodes)})),node.front&&frontNodes.length>0&&stack.push({node:node.front,polygonTreeNodes:frontNodes});const numBackNodes=backNodes.length;if(node.back&&numBackNodes>0)stack.push({node:node.back,polygonTreeNodes:backNodes});else for(let i=0;i0&&tree.rootnode.clipPolygons(node.polygontreenodes,alsoRemoveCoplanarFront),node.front&&stack.push(node.front),node.back&&stack.push(node.back),node=stack.pop()}while(void 0!==node)}addPolygonTreeNodes(newPolygonTreeNodes){let current={node:this,polygonTreeNodes:newPolygonTreeNodes};const stack=[];do{const node=current.node,polygonTreeNodes=current.polygonTreeNodes,len=polygonTreeNodes.length;if(0===len){current=stack.pop();continue}if(!node.plane){let index=0;index=Math.floor(len/2);const bestPoly=polygonTreeNodes[index].getPolygon();node.plane=plane(bestPoly)}const frontNodes=[],backNodes=[];for(let i=0;i0&&(node.front||(node.front=new Node(node)),len===frontNodes.length&&0===backNodes.length?node.front.polygontreenodes=frontNodes:stack.push({node:node.front,polygonTreeNodes:frontNodes})),backNodes.length>0&&(node.back||(node.back=new Node(node)),len===backNodes.length&&0===frontNodes.length?node.back.polygontreenodes=backNodes:stack.push({node:node.back,polygonTreeNodes:backNodes})),current=stack.pop()}while(void 0!==current)}}const splitLineSegmentByPlane=(plane,p1,p2)=>{const direction=subtract$3([0,0,0],p2,p1);let lambda=(plane[3]-dot$2(plane,p1))/dot$2(plane,direction);return Number.isNaN(lambda)&&(lambda=0),lambda>1&&(lambda=1),lambda<0&&(lambda=0),scale$3(direction,direction,lambda),add$1(direction,p1,direction),direction};class PolygonTreeNode{constructor(parent,polygon){this.parent=parent,this.children=[],this.polygon=polygon,this.removed=!1}addPolygons(polygons){if(!this.isRootNode())throw new Error("Assertion failed");const _this=this;polygons.forEach((polygon=>{_this.addChild(polygon)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const parentschildren=this.parent.children,i=parentschildren.indexOf(this);if(i<0)throw new Error("Assertion failed");parentschildren.splice(i,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(result){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){if(this.children.length){const queue=[this.children];let i,j,l,node,nodes;for(i=0;i0?queue.push(node.children):node._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}else this._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}_splitByPlane(splane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){const polygon=this.polygon;if(polygon){const bound=measureBoundingSphere$1(polygon),sphereRadius=bound[3]+EPS,d=dot$2(splane,bound)-splane[3];if(d>sphereRadius)frontNodes.push(this);else if(d<-sphereRadius)backNodes.push(this);else{const splitResult=((splane,polygon)=>{const result={type:null,front:null,back:null},vertices=polygon.vertices,numVertices=vertices.length,pplane=plane(polygon);if(equals$5(pplane,splane))result.type=0;else{let hasFront=!1,hasBack=!1;const vertexIsBack=[],MINEPS=-EPS;for(let i=0;iEPS&&(hasFront=!0),t=numVertices&&(nextVertexIndex=0);const nextIsBack=vertexIsBack[nextVertexIndex];if(isback===nextIsBack)isback?backVertices.push(vertex):frontVertices.push(vertex);else{const nextPoint=vertices[nextVertexIndex],intersectionPoint=splitLineSegmentByPlane(splane,vertex,nextPoint);isback?(backVertices.push(vertex),backVertices.push(intersectionPoint),frontVertices.push(intersectionPoint)):(frontVertices.push(vertex),frontVertices.push(intersectionPoint),backVertices.push(intersectionPoint))}isback=nextIsBack}const EPS_SQUARED=EPS*EPS;if(backVertices.length>=3){let prevVertex=backVertices[backVertices.length-1];for(let vertexIndex=0;vertexIndex=3){let prevVertex=frontVertices[frontVertices.length-1];for(let vertexIndex=0;vertexIndex=3&&(result.front=fromVerticesAndPlane(frontVertices,pplane)),backVertices.length>=3&&(result.back=fromVerticesAndPlane(backVertices,pplane))}else result.type=3;else result.type=2;else{const t=dot$2(splane,pplane);result.type=t>=0?0:1}}return result})(splane,polygon);switch(splitResult.type){case 0:coplanarFrontNodes.push(this);break;case 1:coplanarBackNodes.push(this);break;case 2:frontNodes.push(this);break;case 3:backNodes.push(this);break;case 4:if(splitResult.front){const frontNode=this.addChild(splitResult.front);frontNodes.push(frontNode)}if(splitResult.back){const backNode=this.addChild(splitResult.back);backNodes.push(backNode)}}}}}addChild(polygon){const newChild=new PolygonTreeNode(this,polygon);return this.children.push(newChild),newChild}invertSub(){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let children=[this];const queue=[children];for(let i=0;i0&&queue.push(node.children),node.children=[]}}}toString(){let result="",children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}return result}}class Tree{constructor(polygons){this.polygonTree=new PolygonTreeNode,this.rootnode=new Node(null),polygons&&this.addPolygons(polygons)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(tree,alsoRemoveCoplanarFront=!1){this.rootnode.clipTo(tree,alsoRemoveCoplanarFront)}allPolygons(){const result=[];return this.polygonTree.getPolygons(result),result}addPolygons(polygons){const polygonTreeNodes=new Array(polygons.length);for(let i=0;i{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!((geometry1,geometry2)=>{if(0===geometry1.polygons.length||0===geometry2.polygons.length)return!1;const bounds1=measureBoundingBox(geometry1),min1=bounds1[0],max1=bounds1[1],bounds2=measureBoundingBox(geometry2),min2=bounds2[0],max2=bounds2[1];return!(min2[0]-max1[0]>EPS||min1[0]-max2[0]>EPS||min2[1]-max1[1]>EPS||min1[1]-max2[1]>EPS||min2[2]-max1[2]>EPS||min1[2]-max2[2]>EPS)})(geometry1,geometry2))return clone$7(geometry1);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),a.clipTo(b),b.clipTo(a,!0),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=(geometry=>{if(geometry.isRetesselated)return geometry;const polygons=toPolygons$1(geometry).map(((polygon,index)=>({vertices:polygon.vertices,plane:plane(polygon),index:index}))),classified=classifyPolygons(polygons),destPolygons=[];classified.forEach((group=>{if(Array.isArray(group)){const reTessellateCoplanarPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const destPolygons=[],numPolygons=sourcePolygons.length,plane$1=plane(sourcePolygons[0]),orthonormalFormula=new OrthonormalFormula(plane$1),polygonVertices2d=[],polygonTopVertexIndexes=[],topy2polygonIndexes=new Map,yCoordinateToPolygonIndexes=new Map,yCoordinateBins=new Map;for(let polygonIndex=0;polygonIndex0){let miny,maxy;for(let i=0;imaxy)&&(maxy=y);let polygonIndexes=yCoordinateToPolygonIndexes.get(y);polygonIndexes||(polygonIndexes={},yCoordinateToPolygonIndexes.set(y,polygonIndexes)),polygonIndexes[polygonIndex]=!0}if(miny>=maxy)vertices2d=[],numVertices=0,minIndex=-1;else{let polygonIndexes=topy2polygonIndexes.get(miny);polygonIndexes||(polygonIndexes=[],topy2polygonIndexes.set(miny,polygonIndexes)),polygonIndexes.push(polygonIndex)}}vertices2d.reverse(),minIndex=numVertices-minIndex-1,polygonVertices2d.push(vertices2d),polygonTopVertexIndexes.push(minIndex)}const yCoordinates=[];yCoordinateToPolygonIndexes.forEach(((polylist,y)=>yCoordinates.push(y))),yCoordinates.sort(fnNumberSort);let activePolygons=[],prevOutPolygonRow=[];for(let yIndex=0;yIndex=numVertices&&(nextLeftVertexIndex=0),vertices2d[nextLeftVertexIndex][1]!==yCoordinate)break;newLeftVertexIndex=nextLeftVertexIndex}let nextRightVertexIndex=newRightVertexIndex-1;if(nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),vertices2d[nextRightVertexIndex][1]===yCoordinate&&(newRightVertexIndex=nextRightVertexIndex),newLeftVertexIndex!==activePolygon.leftVertexIndex&&newLeftVertexIndex===newRightVertexIndex)activePolygons.splice(activePolygonIndex,1),--activePolygonIndex;else{activePolygon.leftVertexIndex=newLeftVertexIndex,activePolygon.rightVertexIndex=newRightVertexIndex,activePolygon.topLeft=vertices2d[newLeftVertexIndex],activePolygon.topRight=vertices2d[newRightVertexIndex];let nextLeftVertexIndex=newLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0),activePolygon.bottomLeft=vertices2d[nextLeftVertexIndex];let nextRightVertexIndex=newRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),activePolygon.bottomRight=vertices2d[nextRightVertexIndex]}}}let nextYcoordinate;if(yIndex>=yCoordinates.length-1)activePolygons=[],nextYcoordinate=null;else{nextYcoordinate=Number(yCoordinates[yIndex+1]);const middleYcoordinate=.5*(yCoordinate+nextYcoordinate),startingPolygonIndexes=topy2polygonIndexes.get(yCoordinate);for(const polygonIndexKey in startingPolygonIndexes){const polygonIndex=startingPolygonIndexes[polygonIndexKey],vertices2d=polygonVertices2d[polygonIndex],numVertices=vertices2d.length,topVertexIndex=polygonTopVertexIndexes[polygonIndex];let topLeftVertexIndex=topVertexIndex;for(;;){let i=topLeftVertexIndex+1;if(i>=numVertices&&(i=0),vertices2d[i][1]!==yCoordinate)break;if(i===topVertexIndex)break;topLeftVertexIndex=i}let topRightVertexIndex=topVertexIndex;for(;;){let i=topRightVertexIndex-1;if(i<0&&(i=numVertices-1),vertices2d[i][1]!==yCoordinate)break;if(i===topLeftVertexIndex)break;topRightVertexIndex=i}let nextLeftVertexIndex=topLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0);let nextRightVertexIndex=topRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1);const newActivePolygon={polygonIndex:polygonIndex,leftVertexIndex:topLeftVertexIndex,rightVertexIndex:topRightVertexIndex,topLeft:vertices2d[topLeftVertexIndex],topRight:vertices2d[topRightVertexIndex],bottomLeft:vertices2d[nextLeftVertexIndex],bottomRight:vertices2d[nextRightVertexIndex]};insertSorted(activePolygons,newActivePolygon,((el1,el2)=>{const x1=interpolateBetween2DPointsForY(el1.topLeft,el1.bottomLeft,middleYcoordinate),x2=interpolateBetween2DPointsForY(el2.topLeft,el2.bottomLeft,middleYcoordinate);return x1>x2?1:x10){const prevOutPolygon=newOutPolygonRow[newOutPolygonRow.length-1],d1=distance(outPolygon.topLeft,prevOutPolygon.topRight),d2=distance(outPolygon.bottomLeft,prevOutPolygon.bottomRight);d10){const prevContinuedIndexes=new Set,matchedIndexes=new Set;for(let i=0;i=0)&&(rightLineContinues||d2>=0)&&(thisPolygon.outPolygon=prevPolygon.outPolygon,thisPolygon.leftLineContinues=leftLineContinues,thisPolygon.rightLineContinues=rightLineContinues,prevContinuedIndexes.add(ii));break}}}for(let ii=0;iiEPS&&prevPolygon.outPolygon.leftPoints.push(prevPolygon.bottomLeft),prevPolygon.outPolygon.leftPoints.reverse();const vertices3d=prevPolygon.outPolygon.rightPoints.concat(prevPolygon.outPolygon.leftPoints).map((point2d=>orthonormalFormula.to3D(point2d))),polygon=fromVerticesAndPlane(vertices3d,plane$1);polygon.vertices.length&&destPolygons.push(polygon)}}for(let i=0;iEPS&&thisPolygon.outPolygon.rightPoints.push(thisPolygon.topRight))}prevOutPolygonRow=newOutPolygonRow}return destPolygons})(group);destPolygons.push(...reTessellateCoplanarPolygons)}else destPolygons.push(group)}));const result=create$8(destPolygons);return result.isRetesselated=!0,result})(newGeometry),newGeometry},subtract=(...geometries)=>{if(0===(arr=geometries,geometries=flattenHelper(arr,[])).length)return;var arr;if(!(shapes=>{let previousType;for(const shape of shapes){let currentType=0;if(isA$5(shape)&&(currentType=1),isA$3(shape)&&(currentType=2),isA$2(shape)&&(currentType=3),previousType&¤tType!==previousType)return!1;previousType=currentType}return!0})(geometries))throw new Error("subtract arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return(geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,2)})),newGeometry})(geometries);if(isA$3(geometry))return subtractGeom3(geometries);throw new Error("subtract unsupported geometry type")},transform=(matrix,...objects)=>{const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?transform(matrix,...object):object));return 1===results.length?results[0]:results},createTransform=(center,rotation,scale,scaleOrientation,translation)=>{const matrix=index$c.create(),temp=index$c.create();return index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,translation)),index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,center)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,rotation[3],rotation)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,scaleOrientation[3],scaleOrientation)),index$c.multiply(matrix,matrix,index$c.fromScaling(temp,scale)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,scaleOrientation[3],index$d.negate(index$d.create(),scaleOrientation))),index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,index$d.negate(index$d.create(),center))),matrix},x3dTypes_X3D=0,x3dTypes_UNIT=1,x3dTypes_META=2,x3dTypes_SCENE=3,x3dTypes_TRANSFORM=4,x3dTypes_SHAPE=5,x3dTypes_GROUP=6,x3dTypes_APPEARANCE=7,x3dTypes_TRIANGLESET=10,x3dTypes_TRIANGLEFANSET=11,x3dTypes_TRIANGLESTRIPSET=12,x3dTypes_QUADSET=13,x3dTypes_INDEXEDTRIANGLESET=14,x3dTypes_INDEXEDTRIANGLEFANSET=15,x3dTypes_INDEXEDTRIANGLESTRIPSET=16,x3dTypes_INDEXEDQUADSET=17,x3dTypes_ELEVATIONGRID=18,x3dTypes_INDEXEDFACESET=19,x3dTypes_LINESET=20,x3dTypes_INDEXEDLINESET=21,x3dTypes_BOX=50,x3dTypes_CONE=51,x3dTypes_CYLINDER=52,x3dTypes_SPHERE=53,x3dTypes_EXTRUSION=54,x3dTypes_ARC2D=61,x3dTypes_ARCCLOSE2D=62,x3dTypes_CIRCLE2D=63,x3dTypes_DISK2D=64,x3dTypes_POLYLINE2D=65,x3dTypes_RECTANGLE2D=66,x3dTypes_TRIANGLESET2D=67,x3dTypes_COLOR=91,x3dTypes_COORDINATE=92,x3dTypes_MATERIAL=93,x3dGroup=element=>{const obj={definition:x3dTypes_GROUP,objects:[]};return obj},parseNumbers=attribute=>attribute.trim().replace(/,/g," ").split(/ +/).map((v=>parseFloat(v))),parseIndices=attribute=>attribute.replace(/,/g," ").trim().split(/ -1/).map((index=>parseNumbers(index))),isZeroVector=vector=>vector[0]+0===0&&vector[1]+0===0&&vector[2]+0===0,calculateZaxis=(z,p,i,n)=>{const a=index$d.subtract(index$d.create(),n,i),b=index$d.subtract(index$d.create(),p,i);return index$d.normalize(z,index$d.cross(z,a,b))},extrudeX3D=x3dshape=>{let{beginCap:beginCap,endCap:endCap,crossSection:crossSection,orientations:orientations,scales:scales,spine:spine}=Object.assign({},x3dshape);if(index$3.measureArea(index$3.create(crossSection))<0&&crossSection.reverse(),1===scales.length&&(scales=spine.map((s=>scales[0]))),1===orientations.length&&(orientations=spine.map((s=>orientations[0]))),spine.length!==scales.length||spine.length!==orientations.length)throw new Error(`invalid X3D specification; spine scale orientaion length must be the same; ${spine.length}`);const initialShape=index$a.create([crossSection]),initialSlice=index$2.fromGeom2(initialShape);let yaxes=(spine=>{const slength=spine.length,closed=index$d.equals(spine[0],spine[slength-1]),yaxes=[];for(let i=0;i{const slength=spine.length,closed=index$d.equals(spine[0],spine[slength-1]),zaxes=[];let previousZaxis;for(let i=0;i2&&calculateZaxis(zaxis,spine[0],spine[1],spine[2]):i===slength-1?closed?calculateZaxis(zaxis,spine[slength-2],spine[0],spine[1]):slength>2&&calculateZaxis(zaxis,spine[slength-3],spine[slength-2],spine[slength-1]):calculateZaxis(zaxis,spine[i-1],spine[i],spine[i+1]),previousZaxis&&index$d.dot(previousZaxis,zaxis)<0&&index$d.negate(zaxis,zaxis),zaxes.push(zaxis),previousZaxis=zaxis}if(isZeroVector(zaxes[0]))for(let i=1;i{const xaxes=[];for(let i=0;iacc&&isZeroVector(axis)),!0)&&(index$d.subtract(y0direction,spine[1],spine[0]),index$c.fromVectorRotation(y0matrix,index$d.fromValues(0,0,1),y0direction),xaxes=xaxes.map((axis=>[1,0,0])),yaxes=yaxes.map((axis=>[0,1,0])),zaxes=zaxes.map((axis=>[0,0,1]))),((options,base)=>{const defaults={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,callback:defaultCallback},{numberOfSlices:numberOfSlices,capStart:capStart,capEnd:capEnd,close:close,callback:generate}=Object.assign({},defaults,options);if(numberOfSlices<2)throw new Error("numberOfSlices must be 2 or more");const sMax=numberOfSlices-1;let startSlice=null,endSlice=null,prevSlice=null,polygons=[];for(let s=0;s(out[0]=xaxis[0],out[1]=yaxis[0],out[2]=zaxis[0],out[3]=0,out[4]=xaxis[1],out[5]=yaxis[1],out[6]=zaxis[1],out[7]=0,out[8]=xaxis[2],out[9]=yaxis[2],out[10]=zaxis[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out))(index$c.create(),xaxis,yaxis,zaxis),orientationMatrix=index$c.fromRotation(index$c.create(),orientation[3],orientation),rotationMatrix=index$c.create();index$c.multiply(rotationMatrix,y0matrix,rotationMatrix),index$c.multiply(rotationMatrix,scpMatrix,rotationMatrix),index$c.multiply(rotationMatrix,orientationMatrix,rotationMatrix),index$c.multiply(rotationMatrix,translationMatrix,rotationMatrix);let newslice=base;return newslice=index$2.transform(scaleMatrix,newslice),newslice=index$2.transform(rotationMatrix,newslice),newslice}},initialSlice)},findNode=(x3dtype,objects)=>objects.find((object=>object.definition===x3dtype)),findColor=(objects,options)=>{const appearance=findNode(x3dTypes_APPEARANCE,objects);let material;return appearance&&(material=findNode(x3dTypes_MATERIAL,appearance.objects),material)?material.color?material.color:null:(material=findNode(x3dTypes_MATERIAL,objects),material&&material.color?material.color:null)},pointsToString=triangle=>`[\n ${triangle.map((point=>(point=>`[${point}]`)(point))).join(",\n ")}\n ]`,createColors=(shape,color)=>{if(!color)return null;if(!Array.isArray(shape.colorIndex))return null;let colors=null;var colorIndex,faceColors;return!0===shape.colorPerVertex?colors=((colorIndex,vertexColors)=>{if(!Array.isArray(colorIndex)||!Array.isArray(vertexColors))return null;if(colorIndex.length<0||!Array.isArray(colorIndex[0]))return console.log("ERROR: WRONG FORMAT FOR VERTEXCOLORS"),null;const colors=[];for(let i=0;ifaceColors[index]?faceColors[index]:null)):null),colors},convertLine=(options,objects)=>{let shape=findNode(x3dTypes_INDEXEDLINESET,objects);if(shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),indexes=shape.indexes,color=findNode(x3dTypes_COLOR,shape.objects);if(coordinate&&indexes){const pointsSet=indexes.map((index=>{let points=index.map((i=>coordinate.points[i]));return points.findIndex((p=>0!==p[2]))>=0&&(console.warn("WARNING: unsupported 3D indexed line set was ignored"),points=[]),points}));!0===shape.colorPerVertex?shape.colorIndex=indexes:shape.colorIndex=indexes.map(((index,i)=>i));return{pointsSet:pointsSet,colors:createColors(shape,color)}}}if(shape=findNode(x3dTypes_LINESET,objects),shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),color=findNode(x3dTypes_COLOR,shape.objects),counts=shape.vertexCount;if(coordinate&&counts){let vi=0;const pointsSet=counts.map((count=>{let points=[];for(let i=0;i0!==p[2]))>=0&&(console.warn("WARNING: unsupported 3D line set was ignored"),points=[]),points}));if(!0===shape.colorPerVertex){let ci=0;shape.colorIndex=counts.map((count=>{const index=[];for(let i=0;ii));return{pointsSet:pointsSet,colors:createColors(shape,color)}}}return null},convertMesh=(options,objects)=>{let shape=findNode(x3dTypes_TRIANGLESET,objects);if(shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),color=findNode(x3dTypes_COLOR,shape.objects);if(coordinate){const points=coordinate.points,numpoints=points.length,numfaces=Math.trunc(numpoints/3),faces=[];for(let ti=0;ti2){const points=coordinate.points,numfaces=Math.trunc(index.length/3),faces=[];for(let fi=0;fi0){const points=coordinate.points,numfans=fans.length,faces=[];for(let fi=0;fi0){const points=coordinate.points,numstrips=strips.length,faces=[];for(let si=0;si3){const points=coordinate.points,numquads=Math.trunc(index.length/4),faces=[];for(let qi=0;qi0){const points=coordinate.points;return{type:`indexed faces (${faces.length})`,points:points,faces:faces,colors:createColors(shape,color),orientation:shape.ccw?"outward":"inward"}}}if(shape=findNode(x3dTypes_ELEVATIONGRID,objects),shape){const height=shape.height,color=findNode(x3dTypes_COLOR,shape.objects);if(height&&height.length>0){const xDimension=shape.xDimension,xSpacing=shape.xSpacing,zDimension=shape.zDimension,zSpacing=shape.zSpacing,points=[];let vi=0;for(let z0=0;z0=distances[0]&&distances[1]>=distances[2]&&distances[1]>=distances[3]&&(apexi=1),distances[2]>=distances[0]&&distances[2]>=distances[1]&&distances[2]>=distances[3]&&(apexi=2),distances[3]>=distances[0]&&distances[3]>=distances[1]&&distances[3]>=distances[2]&&(apexi=3),0===apexi&&faces.push([iTL,iBR,iTR],[iTL,iBL,iBR]),1===apexi&&faces.push([iTR,iBL,iBR],[iTR,iTL,iBL]),2===apexi&&faces.push([iBL,iTR,iTL],[iBL,iBR,iTR]),3===apexi&&faces.push([iBR,iTL,iBL],[iBR,iTR,iTL])}const orientation=shape.ccw?"outward":"inward";!0===shape.colorPerVertex&&(shape.colorIndex=faces);return{type:`elevation grid (${xDimension} X ${zDimension})`,points:points,faces:faces,colors:createColors(shape,color),orientation:orientation}}}return null},instantiateMesh=(options,objects)=>{let geometry;const components=convertMesh(0,objects);return components&&(geometry=(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})(components)),geometry},translateMesh=(options,objects)=>{const components=convertMesh(0,objects);if(components){const{type:type,points:points,faces:faces,colors:colors,orientation:orientation}=components;return((type,points,faces,colors,orientation)=>{const colorsCode=Array.isArray(colors)?pointsToString(colors):"null";return{primitive:"polyhedron({points, faces, colors, orientation})",code:`\n // 3D ${type} set: ${points.length} points, ${faces.length} faces\n const points = ${pointsToString(points)}\n const faces = ${pointsToString(faces)}\n const colors = ${colorsCode}\n const orientation = '${orientation}'\n`}})(type,points,faces,colors,orientation)}return null},translateShape=(options,object)=>{let code=`\n// shape\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects,color=findColor(objects);let primitive,shape=findNode(x3dTypes_BOX,objects);if(shape)primitive=`cuboid({size: [${shape.size}]})`;else if(shape=findNode(x3dTypes_CONE,objects),shape)code+=` const shape = rotateX(-Math.PI/2, cylinderElliptic({startRadius: [${shape.bottomRadius},${shape.bottomRadius}], height: ${shape.height}, segments: ${shape.subdivision}, endRadius: [${shape.topRadius}, ${shape.topRadius}]}))\n`,primitive="shape";else if(shape=findNode(x3dTypes_CYLINDER,objects),shape)code+=` const shape = rotateX(-Math.PI/2, cylinder({radius: ${shape.radius}, height: ${shape.height}, segments: ${shape.subdivision}}))\n`,primitive="shape";else if(shape=findNode(x3dTypes_SPHERE,objects),shape)primitive=`sphere({radius: ${shape.radius}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_EXTRUSION,objects),shape){const geometry=extrudeX3D(shape);code+=` const polygons = [\n ${index$6.toPolygons(geometry).map((polygon=>pointsToString(index$7.toVertices(polygon)))).join(",\n ")}\n]\n`,primitive="geom3.fromPoints(polygons)"}if(!primitive)if(shape=findNode(x3dTypes_ARC2D,objects),shape)primitive=`arc({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_ARCCLOSE2D,objects),shape)primitive="PIE"===shape.closureType?`circle({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})`:`geom2.create([path2.toPoints(path2.close(arc({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})))])`;else if(shape=findNode(x3dTypes_CIRCLE2D,objects),shape)primitive=`arc({radius: ${shape.radius}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_DISK2D,objects),shape)primitive=shape.innerRadius===shape.outerRadius?`arc({radius: ${shape.outerRadius}, segments: ${shape.subdivision}})`:0===shape.innerRadius?`circle({radius: ${shape.outerRadius}, segments: ${shape.subdivision}})`:`subtract(circle({radius: ${shape.outerRadius}, segments: ${shape.subdivision}}), primitives.circle({radius: ${shape.innerRadius}, segments: ${shape.subdivision}}))`;else if(shape=findNode(x3dTypes_POLYLINE2D,objects),shape){primitive=`line([[${shape.lineSegments.join("], [")}]])`}else if(shape=findNode(x3dTypes_RECTANGLE2D,objects),shape)primitive=`rectangle({size: [${shape.size}]})`;else if(shape=findNode(x3dTypes_TRIANGLESET2D,objects),shape){const numpoints=shape.vertices.length,numfaces=Math.trunc(numpoints/3);code+=`\n // 2D triangle set: ${numpoints} points, ${numfaces} faces\n const vertices = ${pointsToString(shape.vertices)}\n const triangles = []\n for (let i = 0; i < ${numfaces}; i = i + 3) {\n triangles.push(geom2.create([[vertices[i], vertices[i + 1], vertices[i + 2]]]))\n }\n`,primitive="triangles"}let results=translateMesh(0,objects);return results&&(primitive=results.primitive,code+=results.code),results=((options,objects)=>{const components=convertLine(0,objects);if(components){const{pointsSet:pointsSet,colors:colors}=components;let code=" let lines = []\n";return pointsSet.forEach(((points,i)=>{if(colors){const lineColor=colors[i];code+=` const line${i} = colorize([${lineColor}], primitives.line(${pointsToString(points)}))\n lines.push(line${i})\n`}else code+=` const line${i} = primitives.line(${pointsToString(points)})\n lines.push(line${i})\n`})),{primitive:"...lines",code:code}}return null})(0,objects),results&&(primitive=results.primitive,code+=results.code),primitive&&(code+=color?` objects.push(colorize([${color}], ${primitive}))`:` objects.push(${primitive})`),code+="\n return objects\n}\n",code},translatedList=[],translateDefinition=(options,object)=>{if(translatedList.includes(object.id))return"";translatedList.push(object.id);let code="";switch(object.definition){case x3dTypes_TRANSFORM:code+=((options,object)=>{let code=`\n// transform\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects;for(let i=0;i{let code=`\n// group\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects;for(let i=0;iobjects.reduce(((code,object,index)=>code+translateDefinition(options,object)),"");var saxes={},ed5$1={};!function(exports){ /** * Character classes and associated utilities for the 5th edition of XML 1.0. * @@ -34,4 +34,4 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.CHAR="-퟿- * @license MIT * @copyright Louis-Dominique Dubeau */ -Object.defineProperty(exports,"__esModule",{value:!0}),exports.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",exports.NC_NAME_CHAR="-"+exports.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",exports.NC_NAME_START_CHAR_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]$","u"),exports.NC_NAME_CHAR_RE=new RegExp("^["+exports.NC_NAME_CHAR+"]$","u"),exports.NC_NAME_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]["+exports.NC_NAME_CHAR+"]*$","u"),exports.isNCNameStartChar=isNCNameStartChar,exports.isNCNameChar=function(c){return isNCNameStartChar(c)||45===c||46===c||c>=48&&c<=57||183===c||c>=768&&c<=879||c>=8255&&c<=8256}}(ed3),Object.defineProperty(saxes,"__esModule",{value:!0});var SaxesParser_1=saxes.SaxesParser=saxes.EVENTS=void 0;var isS=ed5$1.isS,isChar10=ed5$1.isChar,isNameStartChar=ed5$1.isNameStartChar,isNameChar=ed5$1.isNameChar,S_LIST=ed5$1.S_LIST,NAME_RE=ed5$1.NAME_RE,isChar11=ed2$1.isChar,isNCNameStartChar=ed3.isNCNameStartChar,isNCNameChar=ed3.isNCNameChar,NC_NAME_RE=ed3.NC_NAME_RE;const XML_NAMESPACE="http://www.w3.org/XML/1998/namespace",XMLNS_NAMESPACE="http://www.w3.org/2000/xmlns/",rootNS={__proto__:null,xml:XML_NAMESPACE,xmlns:XMLNS_NAMESPACE},XML_ENTITIES={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},isQuote=c=>34===c||39===c,QUOTES=[34,39],DOCTYPE_TERMINATOR=[...QUOTES,91,62],DTD_TERMINATOR=[...QUOTES,60,93],XML_DECL_NAME_TERMINATOR=[61,63,...S_LIST],ATTRIB_VALUE_UNQUOTED_TERMINATOR=[...S_LIST,62,38,60];function nsPairCheck(parser,prefix,uri){switch(prefix){case"xml":uri!==XML_NAMESPACE&&parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);break;case"xmlns":uri!==XMLNS_NAMESPACE&&parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`)}switch(uri){case XMLNS_NAMESPACE:parser.fail(""===prefix?`the default namespace may not be set to ${uri}.`:`may not assign a prefix (even "xmlns") to the URI ${XMLNS_NAMESPACE}.`);break;case XML_NAMESPACE:switch(prefix){case"xml":break;case"":parser.fail(`the default namespace may not be set to ${uri}.`);break;default:parser.fail("may not assign the xml namespace to another prefix.")}}}const isNCName=name=>NC_NAME_RE.test(name),isName=name=>NAME_RE.test(name);saxes.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];const EVENT_NAME_TO_HANDLER_NAME={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};SaxesParser_1=saxes.SaxesParser=class{constructor(opt){this.opt=null!=opt?opt:{},this.fragmentOpt=!!this.opt.fragment;const xmlnsOpt=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=!1!==this.opt.position,this.fileName=this.opt.fileName,xmlnsOpt){this.nameStartCheck=isNCNameStartChar,this.nameCheck=isNCNameChar,this.isName=isNCName,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},rootNS);const additional=this.opt.additionalNamespaces;null!=additional&&(!function(parser,mapping){for(const local of Object.keys(mapping))nsPairCheck(parser,local,mapping[local])}(this,additional),Object.assign(this.ns,additional))}else this.nameStartCheck=isNameStartChar,this.nameCheck=isNameChar,this.isName=isName,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var _a;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=0,this.attribList=[];const{fragmentOpt:fragmentOpt}=this;this.state=fragmentOpt?13:0,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=fragmentOpt,this.xmlDeclPossible=!fragmentOpt,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:defaultXMLVersion}=this.opt;if(void 0===defaultXMLVersion){if(!0===this.opt.forceXMLVersion)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");defaultXMLVersion="1.0"}this.setXMLVersion(defaultXMLVersion),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(XML_ENTITIES),null===(_a=this.readyHandler)||void 0===_a||_a.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(name,handler){this[EVENT_NAME_TO_HANDLER_NAME[name]]=handler}off(name){this[EVENT_NAME_TO_HANDLER_NAME[name]]=void 0}makeError(message){var _a;let msg=null!==(_a=this.fileName)&&void 0!==_a?_a:"";return this.trackPosition&&(msg.length>0&&(msg+=":"),msg+=`${this.line}:${this.column}`),msg.length>0&&(msg+=": "),new Error(msg+message)}fail(message){const err=this.makeError(message),handler=this.errorHandler;if(void 0===handler)throw err;return handler(err),this}write(chunk){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let end=!1;null===chunk?(end=!0,chunk=""):"object"==typeof chunk&&(chunk=chunk.toString()),void 0!==this.carriedFromPrevious&&(chunk=`${this.carriedFromPrevious}${chunk}`,this.carriedFromPrevious=void 0);let limit=chunk.length;const lastCode=chunk.charCodeAt(limit-1);!end&&(13===lastCode||lastCode>=55296&&lastCode<=56319)&&(this.carriedFromPrevious=chunk[limit-1],limit--,chunk=chunk.slice(0,limit));const{stateTable:stateTable}=this;for(this.chunk=chunk,this.i=0;this.i=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>=32||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:return 10===chunk.charCodeAt(i+1)&&(this.i=i+2),this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCode11(){const{chunk:chunk,i:i}=this;if(this.prevI=i,this.i=i+1,i>=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>31&&code<127||code>159&&8232!==code||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:{const next=chunk.charCodeAt(i+1);10!==next&&133!==next||(this.i=i+2)}case 133:case 8232:return this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCodeNorm(){const c=this.getCode();return-2===c?10:c}unget(){this.i=this.prevI,this.column--}captureTo(chars){let{i:start}=this;const{chunk:chunk}=this;for(;;){const c=this.getCode(),isNLLike=-2===c,final=isNLLike?10:c;if(-1===final||chars.includes(final))return this.text+=chunk.slice(start,this.prevI),final;isNLLike&&(this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i)}}captureToChar(char){let{i:start}=this;const{chunk:chunk}=this;for(;;){let c=this.getCode();switch(c){case-2:this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i,c=10;break;case-1:return this.text+=chunk.slice(start),!1}if(c===char)return this.text+=chunk.slice(start,this.prevI),!0}}captureNameChars(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCode();if(-1===c)return this.name+=chunk.slice(start),-1;if(!isNameChar(c))return this.name+=chunk.slice(start,this.prevI),-2===c?10:c}}skipSpaces(){for(;;){const c=this.getCodeNorm();if(-1===c||!isS(c))return c}}setXMLVersion(version){this.currentXMLVersion=version,"1.0"===version?(this.isChar=isChar10,this.getCode=this.getCode10):(this.isChar=isChar11,this.getCode=this.getCode11)}sBegin(){65279===this.chunk.charCodeAt(0)&&(this.i++,this.column++),this.state=1}sBeginWhitespace(){const iBefore=this.i,c=this.skipSpaces();switch(this.prevI!==iBefore&&(this.xmlDeclPossible=!1),c){case 60:if(this.state=15,0!==this.text.length)throw new Error("no-empty text at start");break;case-1:break;default:this.unget(),this.state=13,this.xmlDeclPossible=!1}}sDoctype(){var _a;const c=this.captureTo(DOCTYPE_TERMINATOR);switch(c){case 62:null===(_a=this.doctypeHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13,this.doctype=!0;break;case-1:break;default:this.text+=String.fromCodePoint(c),91===c?this.state=4:isQuote(c)&&(this.state=3,this.q=c)}}sDoctypeQuote(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.q=null,this.state=2)}sDTD(){const c=this.captureTo(DTD_TERMINATOR);-1!==c&&(this.text+=String.fromCodePoint(c),93===c?this.state=2:60===c?this.state=6:isQuote(c)&&(this.state=5,this.q=c))}sDTDQuoted(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.state=4,this.q=null)}sDTDOpenWaka(){const c=this.getCodeNorm();switch(this.text+=String.fromCodePoint(c),c){case 33:this.state=7,this.openWakaBang="";break;case 63:this.state=11;break;default:this.state=4}}sDTDOpenWakaBang(){const char=String.fromCodePoint(this.getCodeNorm()),owb=this.openWakaBang+=char;this.text+=char,"-"!==owb&&(this.state="--"===owb?8:4,this.openWakaBang="")}sDTDComment(){this.captureToChar(45)&&(this.text+="-",this.state=9)}sDTDCommentEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),this.state=45===c?10:8}sDTDCommentEnded(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c?this.state=4:(this.fail("malformed comment."),this.state=8)}sDTDPI(){this.captureToChar(63)&&(this.text+="?",this.state=12)}sDTDPIEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c&&(this.state=4)}sText(){0!==this.tags.length?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:start}=this;const{chunk:chunk}=this;loop:for(;;)switch(this.getCode()){case-2:this.entity+=`${chunk.slice(start,this.prevI)}\n`,start=this.i;break;case 59:{const{entityReturnState:entityReturnState}=this,entity=this.entity+chunk.slice(start,this.prevI);let parsed;this.state=entityReturnState,""===entity?(this.fail("empty entity name."),parsed="&;"):(parsed=this.parseEntity(entity),this.entity=""),13===entityReturnState&&void 0===this.textHandler||(this.text+=parsed);break loop}case-1:this.entity+=chunk.slice(start);break loop}}sOpenWaka(){const c=this.getCode();if(isNameStartChar(c))this.state=34,this.unget(),this.xmlDeclPossible=!1;else switch(c){case 47:this.state=43,this.xmlDeclPossible=!1;break;case 33:this.state=16,this.openWakaBang="",this.xmlDeclPossible=!1;break;case 63:this.state=23;break;default:this.fail("disallowed character in tag name"),this.state=13,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=20,this.openWakaBang="";break;case"--":this.state=17,this.openWakaBang="";break;case"DOCTYPE":this.state=2,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(45)&&(this.state=18)}sCommentEnding(){var _a;const c=this.getCodeNorm();45===c?(this.state=19,null===(_a=this.commentHandler)||void 0===_a||_a.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(c)}`,this.state=17)}sCommentEnded(){const c=this.getCodeNorm();62!==c?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(c)}`,this.state=17):this.state=13}sCData(){this.captureToChar(93)&&(this.state=21)}sCDataEnding(){const c=this.getCodeNorm();93===c?this.state=22:(this.text+=`]${String.fromCodePoint(c)}`,this.state=20)}sCDataEnding2(){var _a;const c=this.getCodeNorm();switch(c){case 62:null===(_a=this.cdataHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13;break;case 93:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(c)}`,this.state=20}}sPIFirstChar(){const c=this.getCodeNorm();this.nameStartCheck(c)?(this.piTarget+=String.fromCodePoint(c),this.state=24):63===c||isS(c)?(this.fail("processing instruction without a target."),this.state=63===c?26:25):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c),this.state=24)}sPIRest(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCodeNorm();if(-1===c)return void(this.piTarget+=chunk.slice(start));if(!this.nameCheck(c)){this.piTarget+=chunk.slice(start,this.prevI);const isQuestion=63===c;isQuestion||isS(c)?"xml"===this.piTarget?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=isQuestion?33:27):this.state=isQuestion?26:25:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c));break}}}sPIBody(){if(0===this.text.length){const c=this.getCodeNorm();63===c?this.state=26:isS(c)||(this.text=String.fromCodePoint(c))}else this.captureToChar(63)&&(this.state=26)}sPIEnding(){var _a;const c=this.getCodeNorm();if(62===c){const{piTarget:piTarget}=this;"xml"===piTarget.toLowerCase()&&this.fail("the XML declaration must appear at the start of the document."),null===(_a=this.piHandler)||void 0===_a||_a.call(this,{target:piTarget,body:this.text}),this.piTarget=this.text="",this.state=13}else 63===c?this.text+="?":(this.text+=`?${String.fromCodePoint(c)}`,this.state=25);this.xmlDeclPossible=!1}sXMLDeclNameStart(){const c=this.skipSpaces();63!==c?-1!==c&&(this.state=28,this.name=String.fromCodePoint(c)):this.state=33}sXMLDeclName(){const c=this.captureTo(XML_DECL_NAME_TERMINATOR);if(63===c)return this.state=33,this.name+=this.text,this.text="",void this.fail("XML declaration is incomplete.");if(isS(c)||61===c){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=61===c?30:29}}sXMLDeclEq(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(61!==c&&this.fail("value required."),this.state=30)}sXMLDeclValueStart(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(isQuote(c)?this.q=c:(this.fail("value must be quoted."),this.q=32),this.state=31)}sXMLDeclValue(){const c=this.captureTo([this.q,63]);if(63===c)return this.state=33,this.text="",void this.fail("XML declaration is incomplete.");if(-1===c)return;const value=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];const version=value;this.xmlDecl.version=version,/^1\.[0-9]+$/.test(version)?this.opt.forceXMLVersion||this.setXMLVersion(version):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=value;break;case"standalone":"yes"!==value&&"no"!==value&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=value}this.name="",this.state=32}sXMLDeclSeparator(){const c=this.getCodeNorm();63!==c?(isS(c)||(this.fail("whitespace required."),this.unget()),this.state=27):this.state=33}sXMLDeclEnding(){var _a;62===this.getCodeNorm()?("xml"!==this.piTarget?this.fail("processing instructions are not allowed before root."):"version"!==this.name&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),null===(_a=this.xmldeclHandler)||void 0===_a||_a.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=13):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var _a;const c=this.captureNameChars();if(-1===c)return;const tag=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=tag.ns=Object.create(null)),null===(_a=this.openTagStartHandler)||void 0===_a||_a.call(this,tag),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),c){case 62:this.openTag();break;case 47:this.state=35;break;default:isS(c)||this.fail("disallowed character in tag name."),this.state=36}}sOpenTagSlash(){62===this.getCode()?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=36)}sAttrib(){const c=this.skipSpaces();-1!==c&&(isNameStartChar(c)?(this.unget(),this.state=37):62===c?this.openTag():47===c?this.state=35:this.fail("disallowed character in attribute name."))}sAttribName(){const c=this.captureNameChars();61===c?this.state=39:isS(c)?this.state=38:62===c?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):-1!==c&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){const c=this.skipSpaces();switch(c){case-1:return;case 61:this.state=39;break;default:this.fail("attribute without value."),this.text="",this.name="",62===c?this.openTag():isNameStartChar(c)?(this.unget(),this.state=37):(this.fail("disallowed character in attribute name."),this.state=36)}}sAttribValue(){const c=this.getCodeNorm();isQuote(c)?(this.q=c,this.state=40):isS(c)||(this.fail("unquoted attribute value."),this.state=42,this.unget())}sAttribValueQuoted(){const{q:q,chunk:chunk}=this;let{i:start}=this;for(;;)switch(this.getCode()){case q:return this.pushAttrib(this.name,this.text+chunk.slice(start,this.prevI)),this.name=this.text="",this.q=null,void(this.state=41);case 38:return this.text+=chunk.slice(start,this.prevI),this.state=14,void(this.entityReturnState=40);case 10:case-2:case 9:this.text+=`${chunk.slice(start,this.prevI)} `,start=this.i;break;case 60:return this.text+=chunk.slice(start,this.prevI),void this.fail("disallowed character.");case-1:return void(this.text+=chunk.slice(start))}}sAttribValueClosed(){const c=this.getCodeNorm();isS(c)?this.state=36:62===c?this.openTag():47===c?this.state=35:isNameStartChar(c)?(this.fail("no whitespace between attributes."),this.unget(),this.state=37):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){const c=this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);switch(c){case 38:this.state=14,this.entityReturnState=42;break;case 60:this.fail("disallowed character.");break;case-1:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",62===c?this.openTag():this.state=36}}sCloseTag(){const c=this.captureNameChars();62===c?this.closeTag():isS(c)?this.state=44:-1!==c&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case 62:this.closeTag();break;case-1:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:start,forbiddenState:forbiddenState}=this;const{chunk:chunk,textHandler:handler}=this;scanLoop:for(;;)switch(this.getCode()){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}forbiddenState=0;break scanLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),forbiddenState=0;break scanLoop;case 93:switch(forbiddenState){case 0:forbiddenState=1;break;case 1:forbiddenState=2;break;case 2:break;default:throw new Error("impossible state")}break;case 62:2===forbiddenState&&this.fail('the string "]]>" is disallowed in char data.'),forbiddenState=0;break;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i,forbiddenState=0;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break scanLoop;default:forbiddenState=0}this.forbiddenState=forbiddenState}handleTextOutsideRoot(){let{i:start}=this;const{chunk:chunk,textHandler:handler}=this;let nonSpace=!1;outRootLoop:for(;;){const code=this.getCode();switch(code){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}break outRootLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),nonSpace=!0;break outRootLoop;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break outRootLoop;default:isS(code)||(nonSpace=!0)}}nonSpace&&(this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(name,value){var _a;const{prefix:prefix,local:local}=this.qname(name),attr={name:name,prefix:prefix,local:local,value:value};if(this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr),"xmlns"===prefix){const trimmed=value.trim();"1.0"===this.currentXMLVersion&&""===trimmed&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[local]=trimmed,nsPairCheck(this,local,trimmed)}else if("xmlns"===name){const trimmed=value.trim();this.topNS[""]=trimmed,nsPairCheck(this,"",trimmed)}}pushAttribPlain(name,value){var _a;const attr={name:name,value:value};this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr)}end(){var _a,_b;this.sawRoot||this.fail("document must contain a root element.");const{tags:tags}=this;for(;tags.length>0;){const tag=tags.pop();this.fail(`unclosed tag: ${tag.name}`)}0!==this.state&&13!==this.state&&this.fail("unexpected end.");const{text:text}=this;return 0!==text.length&&(null===(_a=this.textHandler)||void 0===_a||_a.call(this,text),this.text=""),this._closed=!0,null===(_b=this.endHandler)||void 0===_b||_b.call(this),this._init(),this}resolve(prefix){var _a,_b;let uri=this.topNS[prefix];if(void 0!==uri)return uri;const{tags:tags}=this;for(let index=tags.length-1;index>=0;index--)if(uri=tags[index].ns[prefix],void 0!==uri)return uri;return uri=this.ns[prefix],void 0!==uri?uri:null===(_b=(_a=this.opt).resolvePrefix)||void 0===_b?void 0:_b.call(_a,prefix)}qname(name){const colon=name.indexOf(":");if(-1===colon)return{prefix:"",local:name};const local=name.slice(colon+1),prefix=name.slice(0,colon);return(""===prefix||""===local||local.includes(":"))&&this.fail(`malformed name: ${name}.`),{prefix:prefix,local:local}}processAttribsNS(){var _a;const{attribList:attribList}=this,tag=this.tag;{const{prefix:prefix,local:local}=this.qname(tag.name);tag.prefix=prefix,tag.local=local;const uri=tag.uri=null!==(_a=this.resolve(prefix))&&void 0!==_a?_a:"";""!==prefix&&("xmlns"===prefix&&this.fail('tags may not have "xmlns" as prefix.'),""===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),tag.uri=prefix))}if(0===attribList.length)return;const{attributes:attributes}=tag,seen=new Set;for(const attr of attribList){const{name:name,prefix:prefix,local:local}=attr;let uri,eqname;""===prefix?(uri="xmlns"===name?XMLNS_NAMESPACE:"",eqname=name):(uri=this.resolve(prefix),void 0===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),uri=prefix),eqname=`{${uri}}${local}`),seen.has(eqname)&&this.fail(`duplicate attribute: ${eqname}.`),seen.add(eqname),attr.uri=uri,attributes[name]=attr}this.attribList=[]}processAttribsPlain(){const{attribList:attribList}=this,attributes=this.tag.attributes;for(const{name:name,value:value}of attribList)void 0!==attributes[name]&&this.fail(`duplicate attribute: ${name}.`),attributes[name]=value;this.attribList=[]}openTag(){var _a;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!1,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),tags.push(tag),this.state=13,this.name=""}openSelfClosingTag(){var _a,_b,_c;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!0,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),null===(_b=this.closeTagHandler)||void 0===_b||_b.call(this,tag);null===(this.tag=null!==(_c=tags[tags.length-1])&&void 0!==_c?_c:null)&&(this.closedRoot=!0),this.state=13,this.name=""}closeTag(){const{tags:tags,name:name}=this;if(this.state=13,this.name="",""===name)return this.fail("weird empty close tag."),void(this.text+="");const handler=this.closeTagHandler;let l=tags.length;for(;l-- >0;){const tag=this.tag=tags.pop();if(this.topNS=tag.ns,null==handler||handler(tag),tag.name===name)break;this.fail("unexpected close tag.")}0===l?this.closedRoot=!0:l<0&&(this.fail(`unmatched closing tag: ${name}.`),this.text+=``)}parseEntity(entity){if("#"!==entity[0]){const defined=this.ENTITIES[entity];return void 0!==defined?defined:(this.fail(this.isName(entity)?"undefined entity.":"disallowed character in entity name."),`&${entity};`)}let num=NaN;return"x"===entity[1]&&/^#x[0-9a-f]+$/i.test(entity)?num=parseInt(entity.slice(2),16):/^#[0-9]+$/.test(entity)&&(num=parseInt(entity.slice(1),10)),this.isChar(num)?String.fromCodePoint(num):(this.fail("malformed character entity."),`&${entity};`)}};let x3dLast=null,x3dDefinition=x3dTypes_X3D;const x3dObjects=[],x3dDefs=new Map,x3dMaterials=[],x3dTextures=[],x3dLength={factor:1,name:"meters"},x3dAngle={factor:1,name:"radians"};let x3dObj=null;const nodeToObjectMap={X3D:element=>{const obj={definition:x3dTypes_X3D,objects:[]};return obj},UNIT:element=>{const obj={definition:x3dTypes_UNIT,category:"",name:"",conversionFactor:1};return element.category&&(obj.category=element.category),element.name&&(obj.name=element.name),element.conversionfactor&&(obj.conversionFactor=element.conversionfactor),obj},META:element=>{const obj={definition:x3dTypes_META,content:"",name:""};return element.content&&(obj.content=element.content),element.name&&(obj.name=element.name),obj},SCENE:element=>{const obj={definition:x3dTypes_SCENE,objects:[]};return obj},TRANSFORM:element=>{const obj={definition:x3dTypes_TRANSFORM,center:[0,0,0],rotation:[0,0,1,0],scale:[1,1,1],scaleOrientation:[0,0,1,0],translation:[0,0,0]};if(element.center){const values=element.center.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(obj.center=values)}if(element.rotation){const values=element.rotation.trim().split(/ +/).map((v=>parseFloat(v)));values.length>3&&(obj.rotation=values)}if(element.scale){const values=element.scale.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(obj.scale=values)}if(element.scaleorientation){const values=element.scaleorientation.trim().split(/ +/).map((v=>parseFloat(v)));values.length>3&&(obj.scaleOrientation=values)}if(element.translation){const values=element.translation.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(obj.translation=values)}return obj.objects=[],obj},SHAPE:element=>{const obj={definition:x3dTypes_SHAPE,objects:[]};return obj},GROUP:x3dGroup,STATICGROUP:x3dGroup,BOX:element=>{const obj={definition:x3dTypes_BOX,size:[2,2,2]};if(element.size){const values=element.size.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(obj.size=values)}return obj},CONE:element=>{const obj={definition:x3dTypes_CONE,bottomRadius:1,height:2,subdivision:32,topRadius:1e-5};return element.bottomRadius&&(obj.bottomRadius=Math.max(parseFloat(element.bottomRadius),1e-5)),element.height&&(obj.height=parseFloat(element.height)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),element.topRadius&&(obj.topRadius=Math.max(parseFloat(element.topRadius),1e-5)),obj},CYLINDER:element=>{const obj={definition:x3dTypes_CYLINDER,height:2,radius:1,subdivision:32};return element.height&&(obj.height=parseFloat(element.height)),element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},SPHERE:element=>{const obj={definition:x3dTypes_SPHERE,radius:1,subdivision:24};if(element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision){const values=element.subdivision.trim().split(/ +/).map((v=>parseFloat(v)));values.length>1&&(obj.subdivision=Math.max(...values))}return obj},EXTRUSION:element=>{const obj={definition:x3dTypes_EXTRUSION,ccw:!0,beginCap:!0,endCap:!0,crossSection:[[1,1],[1,-1],[-1,-1],[-1,1],[1,1]],orientations:[[0,0,1,0]],scales:[[1,1]],spine:[[0,0,0],[0,1,0]]};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.beginCap&&(obj.beginCap=element.beginCap.includes("TRUE")||element.beginCap.includes("true")),element.endCap&&(obj.endCap=element.endCap.includes("TRUE")||element.endCap.includes("true")),element.crossSection){const values=element.crossSection.trim().split(/ +/).map((v=>parseFloat(v))),numpoints=Math.trunc(values.length/2),points=[];for(let i=0;iparseFloat(v))),numpoints=Math.trunc(values.length/4),points=[];for(let i=0;iparseFloat(v))),numpoints=Math.trunc(values.length/2),points=[];for(let i=0;iparseFloat(v))),numpoints=Math.trunc(values.length/3),points=[];for(let i=0;i{const obj={definition:x3dTypes_ARC2D,endAngle:Math.PI/2,radius:1,startAngle:0,subdivision:32};return element.endAngle&&(obj.endAngle=parseFloat(element.endAngle)),element.radius&&(obj.radius=parseFloat(element.radius)),element.startAngle&&(obj.startAngle=parseFloat(element.startAngle)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},ARCCLOSE2D:element=>{const obj={definition:x3dTypes_ARCCLOSE2D,closureType:"PIE",endAngle:Math.PI/2,radius:1,startAngle:0,subdivision:32};return element.closureType&&(obj.closureType=element.closureType),element.endAngle&&(obj.endAngle=parseFloat(element.endAngle)),element.radius&&(obj.radius=parseFloat(element.radius)),element.startAngle&&(obj.startAngle=parseFloat(element.startAngle)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},CIRCLE2D:element=>{const obj={definition:x3dTypes_CIRCLE2D,radius:1,subdivision:32};return element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},DISK2D:element=>{const obj={definition:x3dTypes_DISK2D,innerRadius:0,outerRadius:1,subdivision:32};return element.innerRadius&&(obj.innerRadius=parseFloat(element.innerRadius)),element.outerRadius&&(obj.outerRadius=parseFloat(element.outerRadius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},POLYLINE2D:element=>{const obj={definition:x3dTypes_POLYLINE2D,lineSegments:[]};if(element.lineSegments){const values=element.lineSegments.trim().split(/ +/).map((v=>parseFloat(v)));for(let i=0;i{const obj={definition:x3dTypes_RECTANGLE2D,size:[2,2]};if(element.size){const values=element.size.trim().split(/ +/).map((v=>parseFloat(v)));values.length>1&&(obj.size=values)}return obj},TRIANGLESET2D:element=>{const obj={definition:x3dTypes_TRIANGLESET2D,vertices:[]};if(element.vertices){const values=element.vertices.trim().split(/ +/).map((v=>parseFloat(v)));for(let i=0;i{const obj={definition:x3dTypes_COLOR,colors:[]};if(element.color){const values=element.color.trim().split(/ +/).map((v=>parseFloat(v))),numvalues=values.length,numcolors=Math.trunc(numvalues/3);for(let i=0;i{const obj={definition:x3dTypes_COORDINATE,points:[]};if(element.point){const values=element.point.trim().split(/ +/).map((v=>parseFloat(v))),numvalues=values.length,numpoints=Math.trunc(numvalues/3);for(let i=0;i{const obj={definition:x3dTypes_TRIANGLESET,ccw:!0,colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),obj.objects=[],obj},TRIANGLEFANSET:element=>{const obj={definition:x3dTypes_TRIANGLEFANSET,ccw:!0,fanCount:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.fanCount&&(obj.fanCount=element.fanCount.trim().split(/ +/).map((v=>parseFloat(v)))),obj.objects=[],obj},TRIANGLESTRIPSET:element=>{const obj={definition:x3dTypes_TRIANGLESTRIPSET,ccw:!0,stripCount:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.stripCount&&(obj.stripCount=element.stripCount.trim().split(/ +/).map((v=>parseFloat(v)))),obj.objects=[],obj},QUADSET:element=>{const obj={definition:x3dTypes_QUADSET,ccw:!0,colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),obj.objects=[],obj},INDEXEDTRIANGLESET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLESET,ccw:!0,index:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index&&(obj.index=element.index.trim().split(/ +/).map((v=>parseFloat(v)))),obj.objects=[],obj},INDEXEDTRIANGLEFANSET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLEFANSET,ccw:!0,fans:[],colorPerVertex:!0};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index){const indexes=element.index.trim().split(/ -1/);obj.fans=indexes.map((index=>index.trim().split(/ +/).map((v=>parseFloat(v))))).filter((index=>index.length>2))}return obj.objects=[],obj},INDEXEDTRIANGLESTRIPSET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLESTRIPSET,ccw:!0,strips:[],colorPerVertex:!0,objects:[]};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index){const indexes=element.index.trim().split(/ -1/);obj.strips=indexes.map((index=>index.trim().split(/ +/).map((v=>parseFloat(v))))).filter((index=>index.length>2))}return obj},INDEXEDQUADSET:element=>{const obj={definition:x3dTypes_INDEXEDQUADSET,ccw:!0,index:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index&&(obj.index=element.index.trim().split(/ +/).map((v=>parseFloat(v)))),obj.objects=[],obj},INDEXEDFACESET:element=>{const obj={definition:x3dTypes_INDEXEDFACESET,ccw:!0,convex:!0,faces:[],colorPerVertex:!0,colorIndex:null};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.convex&&(obj.convex=element.convex.includes("TRUE")||element.convex.includes("true")),element.coordIndex){const indexes=element.coordIndex.trim().split(/ -1/);obj.faces=indexes.map((index=>index.trim().split(/ +/).map((v=>parseFloat(v))))).filter((index=>index.length>2))}if(element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),element.colorIndex)if(obj.colorPerVertex){const indexes=element.colorIndex.trim().split(/ -1/);obj.colorIndex=indexes.map((index=>index.trim().split(/ +/).map((v=>parseFloat(v))))).filter((index=>index.length>2))}else obj.colorIndex=element.colorIndex.trim().split(/ +/).map((v=>parseFloat(v)));else obj.colorIndex=obj.faces;return obj.objects=[],obj},ELEVATIONGRID:element=>{const obj={definition:x3dTypes_ELEVATIONGRID,xDimension:2,zDimension:2,xSpacing:1,zSpacing:1,height:[0,0,0,0],ccw:!0,solid:!1,colorPerVertex:!0};return element.xDimension&&(obj.xDimension=parseFloat(element.xDimension)),element.zDimension&&(obj.zDimension=parseFloat(element.zDimension)),element.xSpacing&&(obj.xSpacing=parseFloat(element.xSpacing)),element.zSpacing&&(obj.zSpacing=parseFloat(element.zSpacing)),element.height&&(obj.height=element.height.trim().split(/ +/).map((v=>parseFloat(v)))),element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.solid&&(obj.solid=element.solid.includes("TRUE")||element.solid.includes("true")),element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},LINESET:element=>{const obj={definition:x3dTypes_LINESET,vertexCount:[],colorPerVertex:!0};return element.vertexCount&&(obj.vertexCount=element.vertexCount.trim().split(/ +/).map((v=>parseFloat(v)))),element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},INDEXEDLINESET:element=>{const obj={definition:x3dTypes_INDEXEDLINESET,indexes:[],colorPerVertex:!0};if(element.coordIndex){const indexes=element.coordIndex.trim().split(/ -1/);obj.indexes=indexes.map((index=>index.trim().split(/ +/).map((v=>parseFloat(v))))),obj.indexes=obj.indexes.filter((index=>index.length>1))}return element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},APPEARANCE:element=>{const obj={definition:x3dTypes_APPEARANCE,objects:[]};return obj},MATERIAL:element=>{const obj={definition:x3dTypes_MATERIAL,color:[.8,.8,.8,1]};let alpha=1;if(element.transparency&&(alpha=1-element.transparency),element.diffuseColor){const values=element.diffuseColor.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(values.length<4&&values.push(alpha),obj.color=values)}if(element.emissiveColor){const values=element.emissiveColor.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(values.length<4&&values.push(alpha),obj.color=values)}return obj}};let objectId=1;const createX3DParser=src=>{const parser=new SaxesParser_1;parser.on("error",(e=>{console.log(`error: line ${e.line}, column ${e.column}, bad character [${e.c}]`)})),parser.on("opentag",(node=>{const elementname=node.name.toUpperCase();let obj=nodeToObjectMap[elementname]?nodeToObjectMap[elementname](node.attributes,{x3dObjects:x3dObjects}):null;if(obj){if(obj.id=("0000"+objectId++).slice(-4),node.attributes.USE){const objectname=node.attributes.USE;if(x3dDefs.has(objectname)){const def=x3dDefs.get(objectname);def.definition!==obj.definition&&console.log(`WARNING: using a definition "${objectname}" of a different type; ${obj.definition} vs ${def.definition}`),obj=def}else console.log(`WARNING: definition "${objectname}" does not exist, using default for ${obj.definition}`)}else if(node.attributes.DEF){const objectname=node.attributes.DEF;x3dDefs.has(objectname)?console.log(`WARNING: redefintion of ${objectname} has been ignored`):x3dDefs.set(objectname,obj)}switch(obj.definition){case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:case x3dTypes_GROUP:x3dDefinition=obj.definition}switch(x3dDefinition){case x3dTypes_X3D:"objects"in obj&&x3dObjects.push(obj),obj.definition===x3dTypes_UNIT&&("length"===obj.category&&(x3dLength.factor=obj.conversionFactor,x3dLength.name=obj.name),"angle"===obj.category&&(x3dAngle.factor=obj.conversionFactor,x3dAngle.name=obj.name));break;case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_GROUP:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:if(x3dObjects.length>0){const group=x3dObjects.pop();"objects"in group&&group.objects.push(obj),x3dObjects.push(group),"objects"in obj&&x3dObjects.push(obj)}break;default:console.log("WARNING: invalid X3D definition")}x3dLast=obj}})),parser.on("closetag",(node=>{switch(node.name.toUpperCase()){case"X3D":case"SCENE":case"TRANSFORM":case"SHAPE":case"GROUP":case"STATICGROUP":case"APPEARANCE":case"TRIANGLESET":case"TRIANGLEFANSET":case"TRIANGLESTRIPSET":case"QUADSET":case"INDEXEDTRIANGLESET":case"INDEXEDTRIANGLEFANSET":case"INDEXEDTRIANGLESTRIPSET":case"INDEXEDQUADSET":case"INDEXEDFACESET":case"ELEVATIONGRID":case"LINESET":case"INDEXEDLINESET":break;default:return}const popDefinition=()=>{x3dObjects.length>0&&(x3dDefinition=x3dObjects[x3dObjects.length-1].definition)};let obj=null;switch(x3dDefinition){case x3dTypes_X3D:x3dObjects.length>0&&(obj=x3dObjects.pop(),popDefinition()),0===x3dObjects.length&&(obj.length=x3dLength,obj.angle=x3dAngle,x3dObj=obj);break;case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_GROUP:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:x3dObjects.length>0&&(obj=x3dObjects.pop(),popDefinition());break;default:console.log("WARNING: unhandled definition",x3dDefinition)}})),parser.on("text",(value=>{null!==value&&(value=value.trim()).length>0&&x3dLast&&0!==x3dDefinition&&(x3dLast.value=value)})),parser.on("end",(()=>{})),parser.write(src).close()},parse=src=>(createX3DParser(src),{x3dObj:x3dObj,x3dMaterials:x3dMaterials,x3dTextures:x3dTextures}),codify=(x3d,data)=>{if(x3d.definition!==x3dTypes_X3D||!x3d.objects)throw new Error("X3D malformed");if(x3d.objects.length<1||x3d.objects[0].definition!==x3dTypes_SCENE)throw new Error("X3D did not define a SCENE");const objects=x3d.objects[0].objects,length=x3d.length,angle=x3d.angle;let code="";code=`// Objects : ${objects.length}\n// Units : ${length.name} (${length.factor})\n// Angles : ${angle.name} (${angle.factor})\n\nimport * from '@jscad/modeling'\n\nexport const main = () => {\n let options = {}\n let objects = []\n`;for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),instantiatePrimitive=(options,objects)=>{let geometry,object=findNode(x3dTypes_BOX,objects);if(object)return geometry=(options=>{const{center:center,size:size}=Object.assign({},{center:[0,0,0],size:[2,2,2]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of width, depth and height values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");return 0===size[0]||0===size[1]||0===size[2]?create$8():create$8([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((info=>{const vertices=info[0].map((i=>[center[0]+size[0]/2*(2*!!(1&i)-1),center[1]+size[1]/2*(2*!!(2&i)-1),center[2]+size[2]/2*(2*!!(4&i)-1)]));return create$7(vertices)})))})({size:object.size}),geometry;if(object=findNode(x3dTypes_CONE,objects),object)return geometry=rotateX(-Math.PI/2,cylinderElliptic({startRadius:[object.bottomRadius,object.bottomRadius],height:object.height,segments:object.subdivision,endRadius:[object.topRadius,object.topRadius]})),geometry;if(object=findNode(x3dTypes_CYLINDER,objects),object)return geometry=rotateX(-Math.PI/2,(options=>{const{center:center,height:height,radius:radius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return 0===height||0===radius?create$8():cylinderElliptic({center:center,height:height,startRadius:[radius,radius],endRadius:[radius,radius],segments:segments})})({radius:object.radius,height:object.height,segments:object.subdivision})),geometry;if(object=findNode(x3dTypes_SPHERE,objects),object)return geometry=sphere({radius:object.radius,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_EXTRUSION,objects),object)return geometry=extrudeX3D(object),geometry;if(object=findNode(x3dTypes_ARC2D,objects),object)return geometry=arc({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_ARCCLOSE2D,objects),object)return geometry="PIE"===object.closureType?circle({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision}):index$a.create([index$5.toPoints(index$5.close(arc({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision})))]),geometry;if(object=findNode(x3dTypes_CIRCLE2D,objects),object)return geometry=arc({radius:object.radius,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_DISK2D,objects),object)return geometry=object.innerRadius===object.outerRadius?arc({radius:object.outerRadius,segments:object.subdivision}):0===object.innerRadius?circle({radius:object.outerRadius,segments:object.subdivision}):subtract(circle({radius:object.outerRadius,segments:object.subdivision}),circle({radius:object.innerRadius,segments:object.subdivision})),geometry;if(object=findNode(x3dTypes_POLYLINE2D,objects),object)return geometry=line([object.lineSegments]),geometry;if(object=findNode(x3dTypes_RECTANGLE2D,objects),object)return geometry=(options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])})({size:object.size}),geometry;if(object=findNode(x3dTypes_TRIANGLESET2D,objects),object){const vertices=object.vertices,numpoints=vertices.length,numfaces=Math.trunc(numpoints/3);geometry=[];for(let i=0;i{const geometries=object.objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));if(0===geometries.length)return null;const matrix=createTransform(object.center,object.rotation,object.scale,object.scaleOrientation,object.translation);return geometries.map((geometry=>{const color=geometry.color;return geometry=((matrix,...objects)=>{if(0===(objects=flatten$1(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results})(matrix,geometry),color&&(geometry.color=color),geometry}))},instantiateShape=(options,object)=>{const objects=object.objects,color=findColor(objects);let geometry=instantiatePrimitive(0,objects);return geometry||(geometry=instantiateMesh(0,objects)),geometry||(geometry=((options,objects)=>{let geometry;const components=convertLine(0,objects);if(components){const{pointsSet:pointsSet,segColors:segColors}=components;geometry=pointsSet.map(((points,i)=>{let l;return l=segColors?colorize(segColors[i],line(points)):line(points),l}))}return geometry})(0,objects)),geometry||(geometry=null),geometry&&color&&(geometry=colorize(color,geometry)),geometry},instantiateDefinition=(options,object)=>{let geometry;switch(object.definition){case x3dTypes_TRANSFORM:geometry=instantiateTransform(options,object);break;case x3dTypes_SHAPE:geometry=instantiateShape(0,object);break;case x3dTypes_GROUP:geometry=((options,object)=>{const geometries=object.objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));return 0===geometries.length?null:geometries})(options,object);break;default:console.log("WARNING: unknown definition: "+object.definition)}return geometry},instantiate=(options,src)=>{(options=Object.assign({},{},options))&&options.statusCallback&&options.statusCallback({progress:0});const{x3dObj:x3dObj}=parse(src);if(x3dObj.definition!==x3dTypes_X3D||!x3dObj.objects)throw new Error("X3D malformed");if(x3dObj.objects.length<1||x3dObj.objects[0].definition!==x3dTypes_SCENE)throw new Error("X3D did not define a SCENE");options&&options.statusCallback&&options.statusCallback({progress:50});let geometries=((options,objects)=>{const geometries=objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));return instantiatedList.clear(),geometries})(options,x3dObj.objects[0].objects);return options.flatten&&(geometries=flatten(geometries)),options&&options.statusCallback&&options.statusCallback({progress:100}),geometries},deserialize=(options,input)=>{const defaults={filename:"x3d",output:"script",version:"3.0.0-alpha.0",flatten:!0,addMetaData:!0};return"script"===(options=Object.assign({},defaults,options)).output?((options,src)=>{options=Object.assign({},{},options);const{version:version,addMetaData:addMetaData,filename:filename}=options;options&&options.statusCallback&&options.statusCallback({progress:0});const{x3dObj:x3dObj,x3dMaterials:x3dMaterials,x3dTextures:x3dTextures}=parse(src);let code=addMetaData?`//\n// Produced by JSCAD IO Library : X3D Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n`:"";if(!x3dObj)throw new Error("X3D parsing failed, no valid X3D data retrieved");return options&&options.statusCallback&&options.statusCallback({progress:50}),code+=codify(x3dObj),options&&options.statusCallback&&options.statusCallback({progress:100}),code})(options,input):instantiate(options,input)},mimeType="model/x3d+xml";export{deserialize,mimeType}; +Object.defineProperty(exports,"__esModule",{value:!0}),exports.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",exports.NC_NAME_CHAR="-"+exports.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",exports.NC_NAME_START_CHAR_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]$","u"),exports.NC_NAME_CHAR_RE=new RegExp("^["+exports.NC_NAME_CHAR+"]$","u"),exports.NC_NAME_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]["+exports.NC_NAME_CHAR+"]*$","u"),exports.isNCNameStartChar=isNCNameStartChar,exports.isNCNameChar=function(c){return isNCNameStartChar(c)||45===c||46===c||c>=48&&c<=57||183===c||c>=768&&c<=879||c>=8255&&c<=8256}}(ed3),Object.defineProperty(saxes,"__esModule",{value:!0});var SaxesParser_1=saxes.SaxesParser=saxes.EVENTS=void 0;var isS=ed5$1.isS,isChar10=ed5$1.isChar,isNameStartChar=ed5$1.isNameStartChar,isNameChar=ed5$1.isNameChar,S_LIST=ed5$1.S_LIST,NAME_RE=ed5$1.NAME_RE,isChar11=ed2$1.isChar,isNCNameStartChar=ed3.isNCNameStartChar,isNCNameChar=ed3.isNCNameChar,NC_NAME_RE=ed3.NC_NAME_RE;const XML_NAMESPACE="http://www.w3.org/XML/1998/namespace",XMLNS_NAMESPACE="http://www.w3.org/2000/xmlns/",rootNS={__proto__:null,xml:XML_NAMESPACE,xmlns:XMLNS_NAMESPACE},XML_ENTITIES={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},isQuote=c=>34===c||39===c,QUOTES=[34,39],DOCTYPE_TERMINATOR=[...QUOTES,91,62],DTD_TERMINATOR=[...QUOTES,60,93],XML_DECL_NAME_TERMINATOR=[61,63,...S_LIST],ATTRIB_VALUE_UNQUOTED_TERMINATOR=[...S_LIST,62,38,60];function nsPairCheck(parser,prefix,uri){switch(prefix){case"xml":uri!==XML_NAMESPACE&&parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);break;case"xmlns":uri!==XMLNS_NAMESPACE&&parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`)}switch(uri){case XMLNS_NAMESPACE:parser.fail(""===prefix?`the default namespace may not be set to ${uri}.`:`may not assign a prefix (even "xmlns") to the URI ${XMLNS_NAMESPACE}.`);break;case XML_NAMESPACE:switch(prefix){case"xml":break;case"":parser.fail(`the default namespace may not be set to ${uri}.`);break;default:parser.fail("may not assign the xml namespace to another prefix.")}}}const isNCName=name=>NC_NAME_RE.test(name),isName=name=>NAME_RE.test(name);saxes.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];const EVENT_NAME_TO_HANDLER_NAME={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};SaxesParser_1=saxes.SaxesParser=class{constructor(opt){this.opt=null!=opt?opt:{},this.fragmentOpt=!!this.opt.fragment;const xmlnsOpt=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=!1!==this.opt.position,this.fileName=this.opt.fileName,xmlnsOpt){this.nameStartCheck=isNCNameStartChar,this.nameCheck=isNCNameChar,this.isName=isNCName,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},rootNS);const additional=this.opt.additionalNamespaces;null!=additional&&(!function(parser,mapping){for(const local of Object.keys(mapping))nsPairCheck(parser,local,mapping[local])}(this,additional),Object.assign(this.ns,additional))}else this.nameStartCheck=isNameStartChar,this.nameCheck=isNameChar,this.isName=isName,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var _a;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=0,this.attribList=[];const{fragmentOpt:fragmentOpt}=this;this.state=fragmentOpt?13:0,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=fragmentOpt,this.xmlDeclPossible=!fragmentOpt,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:defaultXMLVersion}=this.opt;if(void 0===defaultXMLVersion){if(!0===this.opt.forceXMLVersion)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");defaultXMLVersion="1.0"}this.setXMLVersion(defaultXMLVersion),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(XML_ENTITIES),null===(_a=this.readyHandler)||void 0===_a||_a.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(name,handler){this[EVENT_NAME_TO_HANDLER_NAME[name]]=handler}off(name){this[EVENT_NAME_TO_HANDLER_NAME[name]]=void 0}makeError(message){var _a;let msg=null!==(_a=this.fileName)&&void 0!==_a?_a:"";return this.trackPosition&&(msg.length>0&&(msg+=":"),msg+=`${this.line}:${this.column}`),msg.length>0&&(msg+=": "),new Error(msg+message)}fail(message){const err=this.makeError(message),handler=this.errorHandler;if(void 0===handler)throw err;return handler(err),this}write(chunk){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let end=!1;null===chunk?(end=!0,chunk=""):"object"==typeof chunk&&(chunk=chunk.toString()),void 0!==this.carriedFromPrevious&&(chunk=`${this.carriedFromPrevious}${chunk}`,this.carriedFromPrevious=void 0);let limit=chunk.length;const lastCode=chunk.charCodeAt(limit-1);!end&&(13===lastCode||lastCode>=55296&&lastCode<=56319)&&(this.carriedFromPrevious=chunk[limit-1],limit--,chunk=chunk.slice(0,limit));const{stateTable:stateTable}=this;for(this.chunk=chunk,this.i=0;this.i=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>=32||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:return 10===chunk.charCodeAt(i+1)&&(this.i=i+2),this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCode11(){const{chunk:chunk,i:i}=this;if(this.prevI=i,this.i=i+1,i>=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>31&&code<127||code>159&&8232!==code||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:{const next=chunk.charCodeAt(i+1);10!==next&&133!==next||(this.i=i+2)}case 133:case 8232:return this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCodeNorm(){const c=this.getCode();return-2===c?10:c}unget(){this.i=this.prevI,this.column--}captureTo(chars){let{i:start}=this;const{chunk:chunk}=this;for(;;){const c=this.getCode(),isNLLike=-2===c,final=isNLLike?10:c;if(-1===final||chars.includes(final))return this.text+=chunk.slice(start,this.prevI),final;isNLLike&&(this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i)}}captureToChar(char){let{i:start}=this;const{chunk:chunk}=this;for(;;){let c=this.getCode();switch(c){case-2:this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i,c=10;break;case-1:return this.text+=chunk.slice(start),!1}if(c===char)return this.text+=chunk.slice(start,this.prevI),!0}}captureNameChars(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCode();if(-1===c)return this.name+=chunk.slice(start),-1;if(!isNameChar(c))return this.name+=chunk.slice(start,this.prevI),-2===c?10:c}}skipSpaces(){for(;;){const c=this.getCodeNorm();if(-1===c||!isS(c))return c}}setXMLVersion(version){this.currentXMLVersion=version,"1.0"===version?(this.isChar=isChar10,this.getCode=this.getCode10):(this.isChar=isChar11,this.getCode=this.getCode11)}sBegin(){65279===this.chunk.charCodeAt(0)&&(this.i++,this.column++),this.state=1}sBeginWhitespace(){const iBefore=this.i,c=this.skipSpaces();switch(this.prevI!==iBefore&&(this.xmlDeclPossible=!1),c){case 60:if(this.state=15,0!==this.text.length)throw new Error("no-empty text at start");break;case-1:break;default:this.unget(),this.state=13,this.xmlDeclPossible=!1}}sDoctype(){var _a;const c=this.captureTo(DOCTYPE_TERMINATOR);switch(c){case 62:null===(_a=this.doctypeHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13,this.doctype=!0;break;case-1:break;default:this.text+=String.fromCodePoint(c),91===c?this.state=4:isQuote(c)&&(this.state=3,this.q=c)}}sDoctypeQuote(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.q=null,this.state=2)}sDTD(){const c=this.captureTo(DTD_TERMINATOR);-1!==c&&(this.text+=String.fromCodePoint(c),93===c?this.state=2:60===c?this.state=6:isQuote(c)&&(this.state=5,this.q=c))}sDTDQuoted(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.state=4,this.q=null)}sDTDOpenWaka(){const c=this.getCodeNorm();switch(this.text+=String.fromCodePoint(c),c){case 33:this.state=7,this.openWakaBang="";break;case 63:this.state=11;break;default:this.state=4}}sDTDOpenWakaBang(){const char=String.fromCodePoint(this.getCodeNorm()),owb=this.openWakaBang+=char;this.text+=char,"-"!==owb&&(this.state="--"===owb?8:4,this.openWakaBang="")}sDTDComment(){this.captureToChar(45)&&(this.text+="-",this.state=9)}sDTDCommentEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),this.state=45===c?10:8}sDTDCommentEnded(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c?this.state=4:(this.fail("malformed comment."),this.state=8)}sDTDPI(){this.captureToChar(63)&&(this.text+="?",this.state=12)}sDTDPIEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c&&(this.state=4)}sText(){0!==this.tags.length?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:start}=this;const{chunk:chunk}=this;loop:for(;;)switch(this.getCode()){case-2:this.entity+=`${chunk.slice(start,this.prevI)}\n`,start=this.i;break;case 59:{const{entityReturnState:entityReturnState}=this,entity=this.entity+chunk.slice(start,this.prevI);let parsed;this.state=entityReturnState,""===entity?(this.fail("empty entity name."),parsed="&;"):(parsed=this.parseEntity(entity),this.entity=""),13===entityReturnState&&void 0===this.textHandler||(this.text+=parsed);break loop}case-1:this.entity+=chunk.slice(start);break loop}}sOpenWaka(){const c=this.getCode();if(isNameStartChar(c))this.state=34,this.unget(),this.xmlDeclPossible=!1;else switch(c){case 47:this.state=43,this.xmlDeclPossible=!1;break;case 33:this.state=16,this.openWakaBang="",this.xmlDeclPossible=!1;break;case 63:this.state=23;break;default:this.fail("disallowed character in tag name"),this.state=13,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=20,this.openWakaBang="";break;case"--":this.state=17,this.openWakaBang="";break;case"DOCTYPE":this.state=2,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(45)&&(this.state=18)}sCommentEnding(){var _a;const c=this.getCodeNorm();45===c?(this.state=19,null===(_a=this.commentHandler)||void 0===_a||_a.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(c)}`,this.state=17)}sCommentEnded(){const c=this.getCodeNorm();62!==c?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(c)}`,this.state=17):this.state=13}sCData(){this.captureToChar(93)&&(this.state=21)}sCDataEnding(){const c=this.getCodeNorm();93===c?this.state=22:(this.text+=`]${String.fromCodePoint(c)}`,this.state=20)}sCDataEnding2(){var _a;const c=this.getCodeNorm();switch(c){case 62:null===(_a=this.cdataHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13;break;case 93:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(c)}`,this.state=20}}sPIFirstChar(){const c=this.getCodeNorm();this.nameStartCheck(c)?(this.piTarget+=String.fromCodePoint(c),this.state=24):63===c||isS(c)?(this.fail("processing instruction without a target."),this.state=63===c?26:25):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c),this.state=24)}sPIRest(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCodeNorm();if(-1===c)return void(this.piTarget+=chunk.slice(start));if(!this.nameCheck(c)){this.piTarget+=chunk.slice(start,this.prevI);const isQuestion=63===c;isQuestion||isS(c)?"xml"===this.piTarget?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=isQuestion?33:27):this.state=isQuestion?26:25:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c));break}}}sPIBody(){if(0===this.text.length){const c=this.getCodeNorm();63===c?this.state=26:isS(c)||(this.text=String.fromCodePoint(c))}else this.captureToChar(63)&&(this.state=26)}sPIEnding(){var _a;const c=this.getCodeNorm();if(62===c){const{piTarget:piTarget}=this;"xml"===piTarget.toLowerCase()&&this.fail("the XML declaration must appear at the start of the document."),null===(_a=this.piHandler)||void 0===_a||_a.call(this,{target:piTarget,body:this.text}),this.piTarget=this.text="",this.state=13}else 63===c?this.text+="?":(this.text+=`?${String.fromCodePoint(c)}`,this.state=25);this.xmlDeclPossible=!1}sXMLDeclNameStart(){const c=this.skipSpaces();63!==c?-1!==c&&(this.state=28,this.name=String.fromCodePoint(c)):this.state=33}sXMLDeclName(){const c=this.captureTo(XML_DECL_NAME_TERMINATOR);if(63===c)return this.state=33,this.name+=this.text,this.text="",void this.fail("XML declaration is incomplete.");if(isS(c)||61===c){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=61===c?30:29}}sXMLDeclEq(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(61!==c&&this.fail("value required."),this.state=30)}sXMLDeclValueStart(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(isQuote(c)?this.q=c:(this.fail("value must be quoted."),this.q=32),this.state=31)}sXMLDeclValue(){const c=this.captureTo([this.q,63]);if(63===c)return this.state=33,this.text="",void this.fail("XML declaration is incomplete.");if(-1===c)return;const value=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];const version=value;this.xmlDecl.version=version,/^1\.[0-9]+$/.test(version)?this.opt.forceXMLVersion||this.setXMLVersion(version):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=value;break;case"standalone":"yes"!==value&&"no"!==value&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=value}this.name="",this.state=32}sXMLDeclSeparator(){const c=this.getCodeNorm();63!==c?(isS(c)||(this.fail("whitespace required."),this.unget()),this.state=27):this.state=33}sXMLDeclEnding(){var _a;62===this.getCodeNorm()?("xml"!==this.piTarget?this.fail("processing instructions are not allowed before root."):"version"!==this.name&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),null===(_a=this.xmldeclHandler)||void 0===_a||_a.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=13):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var _a;const c=this.captureNameChars();if(-1===c)return;const tag=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=tag.ns=Object.create(null)),null===(_a=this.openTagStartHandler)||void 0===_a||_a.call(this,tag),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),c){case 62:this.openTag();break;case 47:this.state=35;break;default:isS(c)||this.fail("disallowed character in tag name."),this.state=36}}sOpenTagSlash(){62===this.getCode()?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=36)}sAttrib(){const c=this.skipSpaces();-1!==c&&(isNameStartChar(c)?(this.unget(),this.state=37):62===c?this.openTag():47===c?this.state=35:this.fail("disallowed character in attribute name."))}sAttribName(){const c=this.captureNameChars();61===c?this.state=39:isS(c)?this.state=38:62===c?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):-1!==c&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){const c=this.skipSpaces();switch(c){case-1:return;case 61:this.state=39;break;default:this.fail("attribute without value."),this.text="",this.name="",62===c?this.openTag():isNameStartChar(c)?(this.unget(),this.state=37):(this.fail("disallowed character in attribute name."),this.state=36)}}sAttribValue(){const c=this.getCodeNorm();isQuote(c)?(this.q=c,this.state=40):isS(c)||(this.fail("unquoted attribute value."),this.state=42,this.unget())}sAttribValueQuoted(){const{q:q,chunk:chunk}=this;let{i:start}=this;for(;;)switch(this.getCode()){case q:return this.pushAttrib(this.name,this.text+chunk.slice(start,this.prevI)),this.name=this.text="",this.q=null,void(this.state=41);case 38:return this.text+=chunk.slice(start,this.prevI),this.state=14,void(this.entityReturnState=40);case 10:case-2:case 9:this.text+=`${chunk.slice(start,this.prevI)} `,start=this.i;break;case 60:return this.text+=chunk.slice(start,this.prevI),void this.fail("disallowed character.");case-1:return void(this.text+=chunk.slice(start))}}sAttribValueClosed(){const c=this.getCodeNorm();isS(c)?this.state=36:62===c?this.openTag():47===c?this.state=35:isNameStartChar(c)?(this.fail("no whitespace between attributes."),this.unget(),this.state=37):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){const c=this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);switch(c){case 38:this.state=14,this.entityReturnState=42;break;case 60:this.fail("disallowed character.");break;case-1:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",62===c?this.openTag():this.state=36}}sCloseTag(){const c=this.captureNameChars();62===c?this.closeTag():isS(c)?this.state=44:-1!==c&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case 62:this.closeTag();break;case-1:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:start,forbiddenState:forbiddenState}=this;const{chunk:chunk,textHandler:handler}=this;scanLoop:for(;;)switch(this.getCode()){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}forbiddenState=0;break scanLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),forbiddenState=0;break scanLoop;case 93:switch(forbiddenState){case 0:forbiddenState=1;break;case 1:forbiddenState=2;break;case 2:break;default:throw new Error("impossible state")}break;case 62:2===forbiddenState&&this.fail('the string "]]>" is disallowed in char data.'),forbiddenState=0;break;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i,forbiddenState=0;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break scanLoop;default:forbiddenState=0}this.forbiddenState=forbiddenState}handleTextOutsideRoot(){let{i:start}=this;const{chunk:chunk,textHandler:handler}=this;let nonSpace=!1;outRootLoop:for(;;){const code=this.getCode();switch(code){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}break outRootLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),nonSpace=!0;break outRootLoop;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break outRootLoop;default:isS(code)||(nonSpace=!0)}}nonSpace&&(this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(name,value){var _a;const{prefix:prefix,local:local}=this.qname(name),attr={name:name,prefix:prefix,local:local,value:value};if(this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr),"xmlns"===prefix){const trimmed=value.trim();"1.0"===this.currentXMLVersion&&""===trimmed&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[local]=trimmed,nsPairCheck(this,local,trimmed)}else if("xmlns"===name){const trimmed=value.trim();this.topNS[""]=trimmed,nsPairCheck(this,"",trimmed)}}pushAttribPlain(name,value){var _a;const attr={name:name,value:value};this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr)}end(){var _a,_b;this.sawRoot||this.fail("document must contain a root element.");const{tags:tags}=this;for(;tags.length>0;){const tag=tags.pop();this.fail(`unclosed tag: ${tag.name}`)}0!==this.state&&13!==this.state&&this.fail("unexpected end.");const{text:text}=this;return 0!==text.length&&(null===(_a=this.textHandler)||void 0===_a||_a.call(this,text),this.text=""),this._closed=!0,null===(_b=this.endHandler)||void 0===_b||_b.call(this),this._init(),this}resolve(prefix){var _a,_b;let uri=this.topNS[prefix];if(void 0!==uri)return uri;const{tags:tags}=this;for(let index=tags.length-1;index>=0;index--)if(uri=tags[index].ns[prefix],void 0!==uri)return uri;return uri=this.ns[prefix],void 0!==uri?uri:null===(_b=(_a=this.opt).resolvePrefix)||void 0===_b?void 0:_b.call(_a,prefix)}qname(name){const colon=name.indexOf(":");if(-1===colon)return{prefix:"",local:name};const local=name.slice(colon+1),prefix=name.slice(0,colon);return(""===prefix||""===local||local.includes(":"))&&this.fail(`malformed name: ${name}.`),{prefix:prefix,local:local}}processAttribsNS(){var _a;const{attribList:attribList}=this,tag=this.tag;{const{prefix:prefix,local:local}=this.qname(tag.name);tag.prefix=prefix,tag.local=local;const uri=tag.uri=null!==(_a=this.resolve(prefix))&&void 0!==_a?_a:"";""!==prefix&&("xmlns"===prefix&&this.fail('tags may not have "xmlns" as prefix.'),""===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),tag.uri=prefix))}if(0===attribList.length)return;const{attributes:attributes}=tag,seen=new Set;for(const attr of attribList){const{name:name,prefix:prefix,local:local}=attr;let uri,eqname;""===prefix?(uri="xmlns"===name?XMLNS_NAMESPACE:"",eqname=name):(uri=this.resolve(prefix),void 0===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),uri=prefix),eqname=`{${uri}}${local}`),seen.has(eqname)&&this.fail(`duplicate attribute: ${eqname}.`),seen.add(eqname),attr.uri=uri,attributes[name]=attr}this.attribList=[]}processAttribsPlain(){const{attribList:attribList}=this,attributes=this.tag.attributes;for(const{name:name,value:value}of attribList)void 0!==attributes[name]&&this.fail(`duplicate attribute: ${name}.`),attributes[name]=value;this.attribList=[]}openTag(){var _a;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!1,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),tags.push(tag),this.state=13,this.name=""}openSelfClosingTag(){var _a,_b,_c;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!0,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),null===(_b=this.closeTagHandler)||void 0===_b||_b.call(this,tag);null===(this.tag=null!==(_c=tags[tags.length-1])&&void 0!==_c?_c:null)&&(this.closedRoot=!0),this.state=13,this.name=""}closeTag(){const{tags:tags,name:name}=this;if(this.state=13,this.name="",""===name)return this.fail("weird empty close tag."),void(this.text+="");const handler=this.closeTagHandler;let l=tags.length;for(;l-- >0;){const tag=this.tag=tags.pop();if(this.topNS=tag.ns,null==handler||handler(tag),tag.name===name)break;this.fail("unexpected close tag.")}0===l?this.closedRoot=!0:l<0&&(this.fail(`unmatched closing tag: ${name}.`),this.text+=``)}parseEntity(entity){if("#"!==entity[0]){const defined=this.ENTITIES[entity];return void 0!==defined?defined:(this.fail(this.isName(entity)?"undefined entity.":"disallowed character in entity name."),`&${entity};`)}let num=NaN;return"x"===entity[1]&&/^#x[0-9a-f]+$/i.test(entity)?num=parseInt(entity.slice(2),16):/^#[0-9]+$/.test(entity)&&(num=parseInt(entity.slice(1),10)),this.isChar(num)?String.fromCodePoint(num):(this.fail("malformed character entity."),`&${entity};`)}};const nodeToObjectMap={X3D:element=>{const obj={definition:x3dTypes_X3D,objects:[]};return obj},UNIT:element=>{const obj={definition:x3dTypes_UNIT,category:"",name:"",conversionFactor:1};return element.category&&(obj.category=element.category),element.name&&(obj.name=element.name),element.conversionfactor&&(obj.conversionFactor=element.conversionfactor),obj},META:element=>{const obj={definition:x3dTypes_META,content:"",name:""};return element.content&&(obj.content=element.content),element.name&&(obj.name=element.name),obj},SCENE:element=>{const obj={definition:x3dTypes_SCENE,objects:[]};return obj},TRANSFORM:element=>{const obj={definition:x3dTypes_TRANSFORM,center:[0,0,0],rotation:[0,0,1,0],scale:[1,1,1],scaleOrientation:[0,0,1,0],translation:[0,0,0]};if(element.center){const values=parseNumbers(element.center);values.length>2&&(obj.center=values)}if(element.rotation){const values=parseNumbers(element.rotation);values.length>3&&(obj.rotation=values)}if(element.scale){const values=parseNumbers(element.scale);values.length>2&&(obj.scale=values)}if(element.scaleorientation){const values=parseNumbers(element.scaleorientation);values.length>3&&(obj.scaleOrientation=values)}if(element.translation){const values=parseNumbers(element.translation);values.length>2&&(obj.translation=values)}return obj.objects=[],obj},SHAPE:element=>{const obj={definition:x3dTypes_SHAPE,objects:[]};return obj},GROUP:x3dGroup,STATICGROUP:x3dGroup,BOX:element=>{const obj={definition:x3dTypes_BOX,size:[2,2,2]};if(element.size){const values=parseNumbers(element.size);values.length>2&&(obj.size=values)}return obj},CONE:element=>{const obj={definition:x3dTypes_CONE,bottomRadius:1,height:2,subdivision:32,topRadius:1e-5};return element.bottomRadius&&(obj.bottomRadius=Math.max(parseFloat(element.bottomRadius),1e-5)),element.height&&(obj.height=parseFloat(element.height)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),element.topRadius&&(obj.topRadius=Math.max(parseFloat(element.topRadius),1e-5)),obj},CYLINDER:element=>{const obj={definition:x3dTypes_CYLINDER,height:2,radius:1,subdivision:32};return element.height&&(obj.height=parseFloat(element.height)),element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},SPHERE:element=>{const obj={definition:x3dTypes_SPHERE,radius:1,subdivision:24};if(element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision){const values=parseNumbers(element.subdivision);values.length>1&&(obj.subdivision=Math.max(...values))}return obj},EXTRUSION:element=>{const obj={definition:x3dTypes_EXTRUSION,ccw:!0,beginCap:!0,endCap:!0,crossSection:[[1,1],[1,-1],[-1,-1],[-1,1],[1,1]],orientations:[[0,0,1,0]],scales:[[1,1]],spine:[[0,0,0],[0,1,0]]};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.beginCap&&(obj.beginCap=element.beginCap.includes("TRUE")||element.beginCap.includes("true")),element.endCap&&(obj.endCap=element.endCap.includes("TRUE")||element.endCap.includes("true")),element.crossSection){const values=parseNumbers(element.crossSection),numpoints=Math.trunc(values.length/2),points=[];for(let i=0;i{const obj={definition:x3dTypes_ARC2D,endAngle:Math.PI/2,radius:1,startAngle:0,subdivision:32};return element.endAngle&&(obj.endAngle=parseFloat(element.endAngle)),element.radius&&(obj.radius=parseFloat(element.radius)),element.startAngle&&(obj.startAngle=parseFloat(element.startAngle)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},ARCCLOSE2D:element=>{const obj={definition:x3dTypes_ARCCLOSE2D,closureType:"PIE",endAngle:Math.PI/2,radius:1,startAngle:0,subdivision:32};return element.closureType&&(obj.closureType=element.closureType),element.endAngle&&(obj.endAngle=parseFloat(element.endAngle)),element.radius&&(obj.radius=parseFloat(element.radius)),element.startAngle&&(obj.startAngle=parseFloat(element.startAngle)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},CIRCLE2D:element=>{const obj={definition:x3dTypes_CIRCLE2D,radius:1,subdivision:32};return element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},DISK2D:element=>{const obj={definition:x3dTypes_DISK2D,innerRadius:0,outerRadius:1,subdivision:32};return element.innerRadius&&(obj.innerRadius=parseFloat(element.innerRadius)),element.outerRadius&&(obj.outerRadius=parseFloat(element.outerRadius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},POLYLINE2D:element=>{const obj={definition:x3dTypes_POLYLINE2D,lineSegments:[]};if(element.lineSegments){const values=parseNumbers(element.lineSegments);for(let i=0;i{const obj={definition:x3dTypes_RECTANGLE2D,size:[2,2]};if(element.size){const values=parseNumbers(element.size);values.length>1&&(obj.size=values)}return obj},TRIANGLESET2D:element=>{const obj={definition:x3dTypes_TRIANGLESET2D,vertices:[]};if(element.vertices){const values=parseNumbers(element.vertices);for(let i=0;i{const obj={definition:x3dTypes_COLOR,colors:[]};if(element.color){const values=parseNumbers(element.color),numvalues=values.length,numcolors=Math.trunc(numvalues/3);for(let i=0;i{const obj={definition:x3dTypes_COORDINATE,points:[]};if(element.point){const values=parseNumbers(element.point),numvalues=values.length,numpoints=Math.trunc(numvalues/3);for(let i=0;i{const obj={definition:x3dTypes_TRIANGLESET,ccw:!0,colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),obj.objects=[],obj},TRIANGLEFANSET:element=>{const obj={definition:x3dTypes_TRIANGLEFANSET,ccw:!0,fanCount:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.fanCount&&(obj.fanCount=parseNumbers(element.fanCount)),obj.objects=[],obj},TRIANGLESTRIPSET:element=>{const obj={definition:x3dTypes_TRIANGLESTRIPSET,ccw:!0,stripCount:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.stripCount&&(obj.stripCount=parseNumbers(element.stripCount)),obj.objects=[],obj},QUADSET:element=>{const obj={definition:x3dTypes_QUADSET,ccw:!0,colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),obj.objects=[],obj},INDEXEDTRIANGLESET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLESET,ccw:!0,index:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index&&(obj.index=parseNumbers(element.index)),obj.objects=[],obj},INDEXEDTRIANGLEFANSET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLEFANSET,ccw:!0,fans:[],colorPerVertex:!0};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index){const indexes=parseIndices(element.index);obj.fans=indexes.filter((index=>index.length>2))}return obj.objects=[],obj},INDEXEDTRIANGLESTRIPSET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLESTRIPSET,ccw:!0,strips:[],colorPerVertex:!0,objects:[]};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index){const indexes=parseIndices(element.index);obj.strips=indexes.filter((index=>index.length>2))}return obj},INDEXEDQUADSET:element=>{const obj={definition:x3dTypes_INDEXEDQUADSET,ccw:!0,index:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index&&(obj.index=parseNumbers(element.index)),obj.objects=[],obj},INDEXEDFACESET:element=>{const obj={definition:x3dTypes_INDEXEDFACESET,ccw:!0,convex:!0,faces:[],colorPerVertex:!0,colorIndex:null};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.convex&&(obj.convex=element.convex.includes("TRUE")||element.convex.includes("true")),element.coordIndex){const indexes=parseIndices(element.coordIndex);obj.faces=indexes.filter((index=>index.length>2))}if(element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),element.colorIndex)if(obj.colorPerVertex){const indexes=parseIndices(element.colorIndex);obj.colorIndex=indexes.filter((index=>index.length>2))}else obj.colorIndex=parseNumbers(element.colorIndex);else obj.colorIndex=obj.faces;return obj.objects=[],obj},ELEVATIONGRID:element=>{const obj={definition:x3dTypes_ELEVATIONGRID,xDimension:2,zDimension:2,xSpacing:1,zSpacing:1,height:[0,0,0,0],ccw:!0,solid:!1,colorPerVertex:!0};return element.xDimension&&(obj.xDimension=parseFloat(element.xDimension)),element.zDimension&&(obj.zDimension=parseFloat(element.zDimension)),element.xSpacing&&(obj.xSpacing=parseFloat(element.xSpacing)),element.zSpacing&&(obj.zSpacing=parseFloat(element.zSpacing)),element.height&&(obj.height=parseNumbers(element.height)),element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.solid&&(obj.solid=element.solid.includes("TRUE")||element.solid.includes("true")),element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},LINESET:element=>{const obj={definition:x3dTypes_LINESET,vertexCount:[],colorPerVertex:!0};return element.vertexCount&&(obj.vertexCount=parseNumbers(element.vertexCount)),element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},INDEXEDLINESET:element=>{const obj={definition:x3dTypes_INDEXEDLINESET,indexes:[],colorPerVertex:!0};if(element.coordIndex){const indexes=parseIndices(element.coordIndex);obj.indexes=indexes.filter((index=>index.length>1))}return element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},APPEARANCE:element=>{const obj={definition:x3dTypes_APPEARANCE,objects:[]};return obj},MATERIAL:element=>{const obj={definition:x3dTypes_MATERIAL,color:[.8,.8,.8,1]};let alpha=1;if(element.transparency&&(alpha=1-element.transparency),element.diffuseColor){const values=parseNumbers(element.diffuseColor);values.length>2&&(values.length<4&&values.push(alpha),obj.color=values)}if(element.emissiveColor){const values=parseNumbers(element.emissiveColor);values.length>2&&(values.length<4&&values.push(alpha),obj.color=values)}return obj}};let objectId=1;const parse=src=>{const parser=new SaxesParser_1;let x3dLast=null,x3dDefinition=x3dTypes_X3D;const x3dObjects=[],x3dDefs=new Map,x3dLength={factor:1,name:"meters"},x3dAngle={factor:1,name:"radians"};let x3dObj=null;return parser.on("error",(e=>{console.log(`error: line ${e.line}, column ${e.column}, bad character [${e.c}]`)})),parser.on("opentag",(node=>{const elementname=node.name.toUpperCase();let obj=nodeToObjectMap[elementname]?nodeToObjectMap[elementname](node.attributes,{x3dObjects:x3dObjects}):null;if(obj){if(obj.id=("0000"+objectId++).slice(-4),node.attributes.USE){const objectname=node.attributes.USE;if(x3dDefs.has(objectname)){const def=x3dDefs.get(objectname);def.definition!==obj.definition&&console.log(`WARNING: using a definition "${objectname}" of a different type; ${obj.definition} vs ${def.definition}`),obj=def}else console.log(`WARNING: definition "${objectname}" does not exist, using default for ${obj.definition}`)}else if(node.attributes.DEF){const objectname=node.attributes.DEF;x3dDefs.has(objectname)?console.log(`WARNING: redefintion of ${objectname} has been ignored`):x3dDefs.set(objectname,obj)}switch(obj.definition){case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:case x3dTypes_GROUP:x3dDefinition=obj.definition}switch(x3dDefinition){case x3dTypes_X3D:"objects"in obj&&x3dObjects.push(obj),obj.definition===x3dTypes_UNIT&&("length"===obj.category&&(x3dLength.factor=obj.conversionFactor,x3dLength.name=obj.name),"angle"===obj.category&&(x3dAngle.factor=obj.conversionFactor,x3dAngle.name=obj.name));break;case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_GROUP:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:if(x3dObjects.length>0){const group=x3dObjects.pop();"objects"in group&&group.objects.push(obj),x3dObjects.push(group),"objects"in obj&&x3dObjects.push(obj)}break;default:console.log("WARNING: invalid X3D definition")}x3dLast=obj}})),parser.on("closetag",(node=>{switch(node.name.toUpperCase()){case"X3D":case"SCENE":case"TRANSFORM":case"SHAPE":case"GROUP":case"STATICGROUP":case"APPEARANCE":case"TRIANGLESET":case"TRIANGLEFANSET":case"TRIANGLESTRIPSET":case"QUADSET":case"INDEXEDTRIANGLESET":case"INDEXEDTRIANGLEFANSET":case"INDEXEDTRIANGLESTRIPSET":case"INDEXEDQUADSET":case"INDEXEDFACESET":case"ELEVATIONGRID":case"LINESET":case"INDEXEDLINESET":break;default:return}const popDefinition=()=>{x3dObjects.length>0&&(x3dDefinition=x3dObjects[x3dObjects.length-1].definition)};let obj=null;switch(x3dDefinition){case x3dTypes_X3D:x3dObjects.length>0&&(obj=x3dObjects.pop(),popDefinition()),0===x3dObjects.length&&(obj.length=x3dLength,obj.angle=x3dAngle,x3dObj=obj);break;case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_GROUP:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:x3dObjects.length>0&&(obj=x3dObjects.pop(),popDefinition());break;default:console.log("WARNING: unhandled definition",x3dDefinition)}})),parser.on("text",(value=>{null!==value&&(value=value.trim()).length>0&&x3dLast&&0!==x3dDefinition&&(x3dLast.value=value)})),parser.on("end",(()=>{})),parser.write(src).close(),{x3dObj:x3dObj,x3dMaterials:[],x3dTextures:[]}},codify=(x3d,data)=>{if(x3d.definition!==x3dTypes_X3D||!x3d.objects)throw new Error("X3D malformed");if(x3d.objects.length<1||x3d.objects[0].definition!==x3dTypes_SCENE)throw new Error("X3D did not define a SCENE");const objects=x3d.objects[0].objects,length=x3d.length,angle=x3d.angle;let code="";code=`// Objects : ${objects.length}\n// Units : ${length.name} (${length.factor})\n// Angles : ${angle.name} (${angle.factor})\n\nimport * from '@jscad/modeling'\n\nexport const main = () => {\n let options = {}\n let objects = []\n`;for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),instantiatePrimitive=(options,objects)=>{let geometry,object=findNode(x3dTypes_BOX,objects);if(object)return geometry=(options=>{const{center:center,size:size}=Object.assign({},{center:[0,0,0],size:[2,2,2]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of width, depth and height values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");return 0===size[0]||0===size[1]||0===size[2]?create$8():create$8([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((info=>{const vertices=info[0].map((i=>[center[0]+size[0]/2*(2*!!(1&i)-1),center[1]+size[1]/2*(2*!!(2&i)-1),center[2]+size[2]/2*(2*!!(4&i)-1)]));return create$7(vertices)})))})({size:object.size}),geometry;if(object=findNode(x3dTypes_CONE,objects),object)return geometry=rotateX(-Math.PI/2,cylinderElliptic({startRadius:[object.bottomRadius,object.bottomRadius],height:object.height,segments:object.subdivision,endRadius:[object.topRadius,object.topRadius]})),geometry;if(object=findNode(x3dTypes_CYLINDER,objects),object)return geometry=rotateX(-Math.PI/2,(options=>{const{center:center,height:height,radius:radius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return 0===height||0===radius?create$8():cylinderElliptic({center:center,height:height,startRadius:[radius,radius],endRadius:[radius,radius],segments:segments})})({radius:object.radius,height:object.height,segments:object.subdivision})),geometry;if(object=findNode(x3dTypes_SPHERE,objects),object)return geometry=sphere({radius:object.radius,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_EXTRUSION,objects),object)return geometry=extrudeX3D(object),geometry;if(object=findNode(x3dTypes_ARC2D,objects),object)return geometry=arc({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_ARCCLOSE2D,objects),object)return geometry="PIE"===object.closureType?circle({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision}):index$a.create([index$5.toPoints(index$5.close(arc({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision})))]),geometry;if(object=findNode(x3dTypes_CIRCLE2D,objects),object)return geometry=arc({radius:object.radius,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_DISK2D,objects),object)return geometry=object.innerRadius===object.outerRadius?arc({radius:object.outerRadius,segments:object.subdivision}):0===object.innerRadius?circle({radius:object.outerRadius,segments:object.subdivision}):subtract(circle({radius:object.outerRadius,segments:object.subdivision}),circle({radius:object.innerRadius,segments:object.subdivision})),geometry;if(object=findNode(x3dTypes_POLYLINE2D,objects),object)return geometry=line([object.lineSegments]),geometry;if(object=findNode(x3dTypes_RECTANGLE2D,objects),object)return geometry=(options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])})({size:object.size}),geometry;if(object=findNode(x3dTypes_TRIANGLESET2D,objects),object){const vertices=object.vertices,numpoints=vertices.length,numfaces=Math.trunc(numpoints/3);geometry=[];for(let i=0;i{const objects=object.objects,color=findColor(objects);let geometry=instantiatePrimitive(0,objects);return geometry||(geometry=instantiateMesh(0,objects)),geometry||(geometry=((options,objects)=>{let geometry;const components=convertLine(0,objects);if(components){const{pointsSet:pointsSet,segColors:segColors}=components;geometry=pointsSet.map(((points,i)=>{let l;return l=segColors?colorize(segColors[i],line(points)):line(points),l}))}return geometry})(0,objects)),geometry||(geometry=null),geometry&&color&&(geometry=colorize(color,geometry)),geometry},instantiateDefinition=(options,object)=>{let geometry;switch(object.definition){case x3dTypes_TRANSFORM:geometry=((options,object)=>{const geometries=object.objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));if(0===geometries.length)return null;const matrix=createTransform(object.center,object.rotation,object.scale,object.scaleOrientation,object.translation);return geometries.map((geometry=>{const color=geometry.color;return geometry=transform(matrix,geometry),color&&(geometry.color=color),geometry}))})(options,object);break;case x3dTypes_SHAPE:geometry=instantiateShape(0,object);break;case x3dTypes_GROUP:geometry=((options,object)=>{const geometries=object.objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));return 0===geometries.length?null:geometries})(options,object);break;default:console.log("WARNING: unknown definition: "+object.definition)}return geometry},instantiate=(options,src)=>{(options=Object.assign({},{},options))&&options.statusCallback&&options.statusCallback({progress:0});const{x3dObj:x3dObj}=parse(src);if(x3dObj.definition!==x3dTypes_X3D||!x3dObj.objects)throw new Error("X3D malformed");if(x3dObj.objects.length<1||x3dObj.objects[0].definition!==x3dTypes_SCENE)throw new Error("X3D did not define a SCENE");options&&options.statusCallback&&options.statusCallback({progress:50});let geometries=((options,objects)=>{const geometries=objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));return instantiatedList.clear(),geometries})(options,x3dObj.objects[0].objects);return options.flatten&&(geometries=flatten(geometries)),options&&options.statusCallback&&options.statusCallback({progress:100}),geometries},deserialize=(options,input)=>{const defaults={filename:"x3d",output:"script",version:"3.0.1-alpha.0",flatten:!0,addMetaData:!0};return options=Object.assign({},defaults,options),input=((stringOrArrayBuffer,defaultBinaryEncoding="utf-8")=>"string"==typeof stringOrArrayBuffer?stringOrArrayBuffer:new TextDecoder(defaultBinaryEncoding).decode(new Uint8Array(stringOrArrayBuffer)))(input),"script"===options.output?((options,src)=>{options=Object.assign({},{},options);const{version:version,addMetaData:addMetaData,filename:filename}=options;options&&options.statusCallback&&options.statusCallback({progress:0});const{x3dObj:x3dObj,x3dMaterials:x3dMaterials,x3dTextures:x3dTextures}=parse(src);let code=addMetaData?`//\n// Produced by JSCAD IO Library : X3D Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n`:"";if(!x3dObj)throw new Error("X3D parsing failed, no valid X3D data retrieved");return options&&options.statusCallback&&options.statusCallback({progress:50}),code+=codify(x3dObj),options&&options.statusCallback&&options.statusCallback({progress:100}),code})(options,input):instantiate(options,input)},mimeType="model/x3d+xml";export{deserialize,mimeType}; diff --git a/packages/io/x3d-deserializer/dist/jscad-x3d-deserializer.min.js b/packages/io/x3d-deserializer/dist/jscad-x3d-deserializer.min.js index da7dc41cd..885655170 100644 --- a/packages/io/x3d-deserializer/dist/jscad-x3d-deserializer.min.js +++ b/packages/io/x3d-deserializer/dist/jscad-x3d-deserializer.min.js @@ -1,17 +1,16 @@ /** * X3D Deserializer for JSCAD * @module @jscad/x3d-deserializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -var global,factory;global=this,factory=function(exports){ +var global,factory;global=this,factory=function(exports){const clone$b=geometry=>Object.assign({},geometry),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues$4=(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out}; /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT - */ -const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$b=geometry=>Object.assign({},geometry),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues$4=(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:fromValues$4,fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,measureBoundingSphere$1=polygon=>{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$6=Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");if(3===color.length&&(color=[color[0],color[1],color[2],1]),0===(objects=flatten$1(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):(object.color=color,object)));return 1===results.length?results[0]:results},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),equals$3=(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices=vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours)),toEdges=slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges};class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}const toPolygons=slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)};var index$2=Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:equals$3,fromGeom2:fromGeom2,fromVertices:fromVertices,isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:toEdges,toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:toPolygons,toString:slice=>{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:transform$3,validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGT=(value,constant)=>Number.isFinite(value)&&value>constant,isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGT(radius,0))throw new Error("radius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS*EPS)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps)),point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},circle=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],(options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:TAU,segments:32};let{center:center,height:height,startRadius:startRadius,startAngle:startAngle,endRadius:endRadius,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGT(height,0))throw new Error("height must be greater then zero");if(!isNumberArray(startRadius,2))throw new Error("startRadius must be an array of X and Y values");if(!startRadius.every((n=>n>=0)))throw new Error("startRadius values must be positive");if(!isNumberArray(endRadius,2))throw new Error("endRadius must be an array of X and Y values");if(!endRadius.every((n=>n>=0)))throw new Error("endRadius values must be positive");if(endRadius.every((n=>0===n))&&startRadius.every((n=>0===n)))throw new Error("at least one radius must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(startRadius[0],startRadius[1],endRadius[0],endRadius[1]),minAngle=Math.acos((minRadius*minRadius+minRadius*minRadius-EPS*EPS)/(2*minRadius*minRadius));if(rotation{const angle=slice*rotation+startAngle;return scale$3(v1,axisX,radius[0]*cos(angle)),scale$3(v2,axisY,radius[1]*sin(angle)),add$1(v1,v1,v2),scale$3(v3,ray,stack),add$1(v3,v3,start),add$1([0,0,0],v1,v3)},fromVertices=(...vertices)=>{const newVertices=vertices.map((vertex=>add$1([0,0,0],vertex,center)));return create$7(newVertices)},polygons=[];for(let i=0;i0&&startRadius[1]>0&&polygons.push(fromVertices(start,genVertex(0,t1,startRadius),genVertex(0,t0,startRadius))),(startRadius[0]>0||startRadius[1]>0)&&polygons.push(fromVertices(genVertex(0,t0,startRadius),genVertex(0,t1,startRadius),genVertex(1,t0,endRadius))),endRadius[0]>0&&endRadius[1]>0&&polygons.push(fromVertices(end,genVertex(1,t0,endRadius),genVertex(1,t1,endRadius))),(endRadius[0]>0||endRadius[1]>0)&&polygons.push(fromVertices(genVertex(1,t0,endRadius),genVertex(0,t1,startRadius),genVertex(1,t1,endRadius))))}return rotation{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},sphere=options=>{let{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius,radius],(options=>{const{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(radius,3))throw new Error("radius must be an array of X, Y and Z values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===radius[0]||0===radius[1]||0===radius[2])return create$8();const xVector=scale$3([0,0,0],normalize$1([0,0,0],axes[0]),radius[0]),yVector=scale$3([0,0,0],normalize$1([0,0,0],axes[1]),radius[1]),zVector=scale$3([0,0,0],normalize$1([0,0,0],axes[2]),radius[2]),qSegments=Math.round(segments/4);let prevCylinderVertex;const polygons=[],p1=[0,0,0],p2=[0,0,0];for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(p1,xVector,cos(angle)),scale$3(p2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch;for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);if(slice2>0){let vertex,vertices=[];vertex=subtract$3([0,0,0],scale$3(p1,prevCylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),vertex=subtract$3([0,0,0],scale$3(p1,cylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),slice2a===b?a:a{const multiple=newLength/edges.length;if(1===multiple)return edges;const divisor=fromValues$3(multiple,multiple,multiple),newEdges=[];return edges.forEach((edge=>{const increment=subtract$3([0,0,0],edge[1],edge[0]);divide$1(increment,increment,divisor);let prev=edge[0];for(let i=1;i<=multiple;++i){const next=add$1([0,0,0],prev,increment);newEdges.push([prev,next]),prev=next}})),newEdges},EPSAREA=EPS*EPS/2*Math.sin(Math.PI/3),extrudeWalls=(slice0,slice1)=>{let edges0=toEdges(slice0),edges1=toEdges(slice1);if(edges0.length!==edges1.length){const newLength=(a=edges0.length)*(b=edges1.length)/gcd(a,b);newLength!==edges0.length&&(edges0=repartitionEdges(newLength,edges0)),newLength!==edges1.length&&(edges1=repartitionEdges(newLength,edges1))}var a,b;const walls=[];return edges0.forEach(((edge0,i)=>{const edge1=edges1[i],poly0=create$7([edge0[0],edge0[1],edge1[1]]),poly0area=measureArea$2(poly0);Number.isFinite(poly0area)&&poly0area>EPSAREA&&walls.push(poly0);const poly1=create$7([edge0[0],edge1[1],edge1[0]]),poly1area=measureArea$2(poly1);Number.isFinite(poly1area)&&poly1area>EPSAREA&&walls.push(poly1)})),walls},defaultCallback=(progress,index,base)=>{let baseSlice=null;return isA$5(base)&&(baseSlice=fromGeom2(base)),isA$4(base)&&(baseSlice=fromVertices(toVertices$1(base))),0===progress||1===progress?transform$3(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[0,0,progress]),baseSlice):null},rotateX=(angle,...objects)=>((angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");if(0===(objects=flatten$1(objects)).length)throw new Error("wrong number of arguments");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results})([angle,0,0],objects),DEFAULT_COMPARE=(a,b)=>a>b?1:a{const N=new Node$1(null,null);let l=N,r=N;for(;;){const cmp=comparator(i,t.key);if(cmp<0){if(null===t.left)break;if(comparator(i,t.left.key)<0){const y=t.left;if(t.left=y.right,y.right=t,null===(t=y).left)break}r.left=t,r=t,t=t.left}else{if(!(cmp>0))break;if(null===t.right)break;if(comparator(i,t.right.key)>0){const y=t.right;if(t.right=y.left,y.left=t,null===(t=y).right)break}l.right=t,l=t,t=t.right}}return l.right=t.left,r.left=t.right,t.left=N.right,t.right=N.left,t},insert=(i,data,t,comparator)=>{const node=new Node$1(i,data);if(null===t)return node.left=node.right=null,node;const cmp=comparator(i,(t=splay(i,t,comparator)).key);return cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>=0&&(node.right=t.right,node.left=t,t.right=null),node},split=(key,v,comparator)=>{let left=null,right=null;if(v){const cmp=comparator((v=splay(key,v,comparator)).key,key);0===cmp?(left=v.left,right=v.right):cmp<0?(right=v.right,v.right=null,left=v):(left=v.left,v.left=null,right=v)}return{left:left,right:right}},printRow=(root,prefix,isTail,out,printNode)=>{if(root){out(`${prefix}${isTail?"└── ":"├── "}${printNode(root)}\n`);const indent=prefix+(isTail?" ":"│ ");root.left&&printRow(root.left,indent,!1,out,printNode),root.right&&printRow(root.right,indent,!0,out,printNode)}};class Tree$1{constructor(comparator=DEFAULT_COMPARE){this._comparator=comparator,this._root=null,this._size=0}insert(key,data){return this._size++,this._root=insert(key,data,this._root,this._comparator),this._root}add(key,data){const node=new Node$1(key,data);null===this._root&&(node.left=node.right=null,this._size++,this._root=node);const comparator=this._comparator,t=splay(key,this._root,comparator),cmp=comparator(key,t.key);return 0===cmp?this._root=t:(cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>0&&(node.right=t.right,node.left=t,t.right=null),this._size++,this._root=node),this._root}remove(key){this._root=this._remove(key,this._root,this._comparator)}_remove(i,t,comparator){let x;return null===t?null:0===comparator(i,(t=splay(i,t,comparator)).key)?(null===t.left?x=t.right:(x=splay(i,t.left,comparator),x.right=t.right),this._size--,x):t}pop(){let node=this._root;if(node){for(;node.left;)node=node.left;return this._root=splay(node.key,this._root,this._comparator),this._root=this._remove(node.key,this._root,this._comparator),{key:node.key,data:node.data}}return null}findStatic(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return current;current=cmp<0?current.left:current.right}return null}find(key){return this._root&&(this._root=splay(key,this._root,this._comparator),0!==this._comparator(key,this._root.key))?null:this._root}contains(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return!0;current=cmp<0?current.left:current.right}return!1}forEach(visitor,ctx){let current=this._root;const Q=[];let done=!1;for(;!done;)null!==current?(Q.push(current),current=current.left):0!==Q.length?(current=Q.pop(),visitor.call(ctx,current),current=current.right):done=!0;return this}range(low,high,fn,ctx){const Q=[],compare=this._comparator;let cmp,node=this._root;for(;0!==Q.length||node;)if(node)Q.push(node),node=node.left;else{if(node=Q.pop(),cmp=compare(node.key,high),cmp>0)break;if(compare(node.key,low)>=0&&fn.call(ctx,node))return this;node=node.right}return this}keys(){const keys=[];return this.forEach((({key:key})=>keys.push(key))),keys}values(){const values=[];return this.forEach((({data:data})=>values.push(data))),values}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(index){let current=this._root,done=!1,i=0;const Q=[];for(;!done;)if(current)Q.push(current),current=current.left;else if(Q.length>0){if(current=Q.pop(),i===index)return current;i++,current=current.right}else done=!0;return null}next(d){let root=this._root,successor=null;if(d.right){for(successor=d.right;successor.left;)successor=successor.left;return successor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?(successor=root,root=root.left):root=root.right}return successor}prev(d){let root=this._root,predecessor=null;if(null!==d.left){for(predecessor=d.left;predecessor.right;)predecessor=predecessor.right;return predecessor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?root=root.left:(predecessor=root,root=root.right)}return predecessor}clear(){return this._root=null,this._size=0,this}toList(){return toList(this._root)}load(keys,values=[],presort=!1){let size=keys.length;const comparator=this._comparator;if(presort&&sort(keys,values,0,size-1,comparator),null===this._root)this._root=loadRecursive(keys,values,0,size),this._size=size;else{const mergedList=mergeLists(this.toList(),createList(keys,values),comparator);size=this._size+size,this._root=sortedListToBST({head:mergedList},0,size)}return this}isEmpty(){return null===this._root}size(){return this._size}root(){return this._root}toString(printNode=(n=>String(n.key))){const out=[];return printRow(this._root,"",!0,(v=>out.push(v)),printNode),out.join("")}update(key,newKey,newData){const comparator=this._comparator;let{left:left,right:right}=split(key,this._root,comparator);comparator(key,newKey)<0?right=insert(newKey,newData,right,comparator):left=insert(newKey,newData,left,comparator),this._root=((left,right,comparator)=>null===right?left:(null===left||((right=splay(left.key,right,comparator)).left=left),right))(left,right,comparator)}split(key){return split(key,this._root,this._comparator)}*[Symbol.iterator](){let n=this.minNode();for(;n;)yield n,n=this.next(n)}}const loadRecursive=(keys,values,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),key=keys[middle],data=values[middle],node=new Node$1(key,data);return node.left=loadRecursive(keys,values,start,middle),node.right=loadRecursive(keys,values,middle+1,end),node}return null},createList=(keys,values)=>{const head=new Node$1(null,null);let p=head;for(let i=0;i{let current=root;const Q=[];let done=!1;const head=new Node$1(null,null);let p=head;for(;!done;)current?(Q.push(current),current=current.left):Q.length>0?(current=p=p.next=Q.pop(),current=current.right):done=!0;return p.next=null,head.next},sortedListToBST=(list,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),left=sortedListToBST(list,start,middle),root=list.head;return root.left=left,list.head=list.head.next,root.right=sortedListToBST(list,middle+1,end),root}return null},mergeLists=(l1,l2,compare)=>{const head=new Node$1(null,null);let p=head,p1=l1,p2=l2;for(;null!==p1&&null!==p2;)compare(p1.key,p2.key)<0?(p.next=p1,p1=p1.next):(p.next=p2,p2=p2.next),p=p.next;return null!==p1?p.next=p1:null!==p2&&(p.next=p2),head.next},sort=(keys,values,left,right,compare)=>{if(left>=right)return;const pivot=keys[left+right>>1];let i=left-1,j=right+1;for(;;){do{i++}while(compare(keys[i],pivot)<0);do{j--}while(compare(keys[j],pivot)>0);if(i>=j)break;let tmp=keys[i];keys[i]=keys[j],keys[j]=tmp,tmp=values[i],values[i]=values[j],values[j]=tmp}sort(keys,values,left,j,compare),sort(keys,values,j+1,right,compare)},computeFields=(event,prev,operation)=>{null===prev?(event.inOut=!1,event.otherInOut=!0):(event.isSubject===prev.isSubject?(event.inOut=!prev.inOut,event.otherInOut=prev.otherInOut):(event.inOut=!prev.otherInOut,event.otherInOut=prev.isVertical()?!prev.inOut:prev.inOut),prev&&(event.prevInResult=!inResult(prev,operation)||prev.isVertical()?prev.prevInResult:prev));const isInResult=inResult(event,operation);event.resultTransition=isInResult?determineResultTransition(event,operation):0},inResult=(event,operation)=>{switch(event.type){case 0:switch(operation){case 0:return!event.otherInOut;case 1:return event.otherInOut;case 2:return event.isSubject&&event.otherInOut||!event.isSubject&&!event.otherInOut;case 3:return!0}break;case 2:return 0===operation||1===operation;case 3:return 2===operation;case 1:return!1}return!1},determineResultTransition=(event,operation)=>{const thisIn=!event.inOut,thatIn=!event.otherInOut;let isIn;switch(operation){case 0:isIn=thisIn&&thatIn;break;case 1:isIn=thisIn||thatIn;break;case 3:isIn=thisIn^thatIn;break;case 2:isIn=event.isSubject?thisIn&&!thatIn:thatIn&&!thisIn}return isIn?1:-1};class SweepEvent{constructor(point,left,otherEvent,isSubject,edgeType){this.left=left,this.point=point,this.otherEvent=otherEvent,this.isSubject=isSubject,this.type=edgeType||0,this.inOut=!1,this.otherInOut=!1,this.prevInResult=null,this.resultTransition=0,this.otherPos=-1,this.outputContourId=-1,this.isExteriorRing=!0}isBelow(p){const p0=this.point,p1=this.otherEvent.point;return this.left?(p0[0]-p[0])*(p1[1]-p[1])-(p1[0]-p[0])*(p0[1]-p[1])>0:(p1[0]-p[0])*(p0[1]-p[1])-(p0[0]-p[0])*(p1[1]-p[1])>0}isAbove(p){return!this.isBelow(p)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return 0!==this.resultTransition}clone(){const copy=new SweepEvent(this.point,this.left,this.otherEvent,this.isSubject,this.type);return copy.contourId=this.contourId,copy.resultTransition=this.resultTransition,copy.prevInResult=this.prevInResult,copy.isExteriorRing=this.isExteriorRing,copy.inOut=this.inOut,copy.otherInOut=this.otherInOut,copy}}const signedArea=(p0,p1,p2)=>{const res=(ax=p0[0],ay=p0[1],bx=p1[0],by=p1[1],cx=p2[0],(ay-(cy=p2[1]))*(bx-cx)-(ax-cx)*(by-cy));var ax,ay,bx,by,cx,cy;return res>0?-1:res<0?1:0},compareEvents=(e1,e2)=>{const p1=e1.point,p2=e2.point;return p1[0]>p2[0]?1:p1[0]p2[1]?1:-1:specialCases(e1,e2,p1)},specialCases=(e1,e2,p1,p2)=>e1.left!==e2.left?e1.left?1:-1:0!==signedArea(p1,e1.otherEvent.point,e2.otherEvent.point)?e1.isBelow(e2.otherEvent.point)?-1:1:!e1.isSubject&&e2.isSubject?1:-1,divideSegment=(se,p,queue)=>{const r=new SweepEvent(p,!1,se,se.isSubject),l=new SweepEvent(p,!0,se.otherEvent,se.isSubject);return r.contourId=l.contourId=se.contourId,compareEvents(l,se.otherEvent)>0&&(se.otherEvent.left=!0,l.left=!1),se.otherEvent.otherEvent=l,se.otherEvent=r,queue.push(l),queue.push(r),queue},crossProduct=(a,b)=>a[0]*b[1]-a[1]*b[0],possibleIntersection=(se1,se2,queue)=>{const inter=((a1,a2,b1,b2,noEndpointTouch)=>{const va=[a2[0]-a1[0],a2[1]-a1[1]],vb=[b2[0]-b1[0],b2[1]-b1[1]],toPoint=(p,s,d)=>[p[0]+s*d[0],p[1]+s*d[1]],e=[b1[0]-a1[0],b1[1]-a1[1]];let kross=crossProduct(va,vb),sqrKross=kross*kross;const sqrLenA=dot$1(va,va);if(sqrKross>0){const s=crossProduct(e,vb)/kross;if(s<0||s>1)return null;const t=crossProduct(e,va)/kross;return t<0||t>1?null:0===s||1===s?[toPoint(a1,s,va)]:0===t||1===t?[toPoint(b1,t,vb)]:[toPoint(a1,s,va)]}if(kross=crossProduct(e,va),sqrKross=kross*kross,sqrKross>0)return null;const sa=dot$1(va,e)/sqrLenA,sb=sa+dot$1(va,vb)/sqrLenA,smin=Math.min(sa,sb),smax=Math.max(sa,sb);return smin<=1&&smax>=0?1===smin?[toPoint(a1,smin>0?smin:0,va)]:0===smax?[toPoint(a1,smax<1?smax:1,va)]:[toPoint(a1,smin>0?smin:0,va),toPoint(a1,smax<1?smax:1,va)]:null})(se1.point,se1.otherEvent.point,se2.point,se2.otherEvent.point),nIntersections=inter?inter.length:0;if(0===nIntersections)return 0;if(1===nIntersections&&(equals$6(se1.point,se2.point)||equals$6(se1.otherEvent.point,se2.otherEvent.point)))return 0;if(2===nIntersections&&se1.isSubject===se2.isSubject)return 0;if(1===nIntersections)return equals$6(se1.point,inter[0])||equals$6(se1.otherEvent.point,inter[0])||divideSegment(se1,inter[0],queue),equals$6(se2.point,inter[0])||equals$6(se2.otherEvent.point,inter[0])||divideSegment(se2,inter[0],queue),1;const events=[];let leftCoincide=!1,rightCoincide=!1;return equals$6(se1.point,se2.point)?leftCoincide=!0:1===compareEvents(se1,se2)?events.push(se2,se1):events.push(se1,se2),equals$6(se1.otherEvent.point,se2.otherEvent.point)?rightCoincide=!0:1===compareEvents(se1.otherEvent,se2.otherEvent)?events.push(se2.otherEvent,se1.otherEvent):events.push(se1.otherEvent,se2.otherEvent),leftCoincide&&rightCoincide||leftCoincide?(se2.type=1,se1.type=se2.inOut===se1.inOut?2:3,leftCoincide&&!rightCoincide&÷Segment(events[1].otherEvent,events[0].point,queue),2):rightCoincide?(divideSegment(events[0],events[1].point,queue),3):events[0]!==events[3].otherEvent?(divideSegment(events[0],events[1].point,queue),divideSegment(events[1],events[2].point,queue),3):(divideSegment(events[0],events[1].point,queue),divideSegment(events[3].otherEvent,events[2].point,queue),3)},compareSegments=(le1,le2)=>{if(le1===le2)return 0;if(0!==signedArea(le1.point,le1.otherEvent.point,le2.point)||0!==signedArea(le1.point,le1.otherEvent.point,le2.otherEvent.point))return equals$6(le1.point,le2.point)?le1.isBelow(le2.otherEvent.point)?-1:1:le1.point[0]===le2.point[0]?le1.point[1]le2.contourId?1:-1}return 1===compareEvents(le1,le2)?1:-1};class Contour{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return null==this.holeOf}}const nextPos=(pos,resultEvents,processed,origPos)=>{let newPos=pos+1;const p=resultEvents[pos].point;let p1;const length=resultEvents.length;for(newPosorigPos;)newPos--;return newPos},initializeContourFromContext=(event,contours,contourId)=>{const contour=new Contour;if(null!=event.prevInResult){const prevInResult=event.prevInResult,lowerContourId=prevInResult.outputContourId,lowerResultTransition=prevInResult.resultTransition;if(lowerContourId<0)contour.holeOf=null,contour.depth=0;else if(lowerResultTransition>0){const lowerContour=contours[lowerContourId];if(null!=lowerContour.holeOf){const parentContourId=lowerContour.holeOf;contours[parentContourId].holeIds.push(contourId),contour.holeOf=parentContourId,contour.depth=contours[lowerContourId].depth}else contours[lowerContourId].holeIds.push(contourId),contour.holeOf=lowerContourId,contour.depth=contours[lowerContourId].depth+1}else contour.holeOf=null,contour.depth=contours[lowerContourId].depth}else contour.holeOf=null,contour.depth=0;return contour};class Queue{constructor(data,compare){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this._up(this.length++)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return--this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos=0)break;data[pos]=data[bestChild],pos=bestChild}data[pos]=item}}const max=Math.max,min=Math.min;let contourId=0;const processPolygon=(contourOrHole,isSubject,depth,queue,bbox,isExteriorRing)=>{const len=contourOrHole.length-1;let s1,s2,e1,e2;for(let i=0;i0?e2.left=!0:e1.left=!0;const x=s1[0],y=s1[1];bbox[0]=min(bbox[0],x),bbox[1]=min(bbox[1],y),bbox[2]=max(bbox[2],x),bbox[3]=max(bbox[3],y),queue.push(e1),queue.push(e2)}},EMPTY=[],toMartinez=geometry=>{const outlines=[];return toOutlines(geometry).forEach((outline=>{equals$6(outline[0],outline[outline.length-1])?outlines.push(outline):outlines.push([...outline,outline[0]])})),[outlines]},fromOutlines=outlines=>(outlines.forEach((outline=>{equals$6(outline[0],outline[outline.length-1])&&outline.pop()})),outlines=outlines.filter((o=>o.length>=3)),create$a(outlines)),boolean=(subjectGeom,clippingGeom,operation)=>{const subject=toMartinez(subjectGeom),clipping=toMartinez(clippingGeom);let trivial=((subject,clipping,operation)=>{let result=null;if(subject.length*clipping.length==0){if(0===operation)return EMPTY;2===operation?result=subject:1!==operation&&3!==operation||(result=0===subject.length?clipping:subject)}return result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,operation);if(trivial)return trivial;const sbbox=[1/0,1/0,-1/0,-1/0],cbbox=[1/0,1/0,-1/0,-1/0],eventQueue=((subject,clipping,sbbox,cbbox,operation)=>{const eventQueue=new Queue([],compareEvents);let polygonSet,isExteriorRing,i,ii,j,jj;for(i=0,ii=subject.length;i{let result=null;return(sbbox[0]>cbbox[2]||cbbox[0]>sbbox[2]||sbbox[1]>cbbox[3]||cbbox[1]>sbbox[3])&&(0===operation?result=EMPTY:2===operation?result=subject:1!==operation&&3!==operation||(result=subject.concat(clipping))),result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,sbbox,cbbox,operation),trivial)return trivial;const sortedEvents=((eventQueue,subject,clipping,sbbox,cbbox,operation)=>{const sweepLine=new Tree$1(compareSegments),sortedEvents=[],rightBound=Math.min(sbbox[2],cbbox[2]);let prev,next,begin;for(;0!==eventQueue.length;){let event=eventQueue.pop();if(sortedEvents.push(event),0===operation&&event.point[0]>rightBound||2===operation&&event.point[0]>sbbox[2])break;if(event.left){next=prev=sweepLine.insert(event),begin=sweepLine.minNode(),prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next);const prevEvent=prev?prev.key:null;let prevprevEvent;if(computeFields(event,prevEvent,operation),next&&2===possibleIntersection(event,next.key,eventQueue)&&(computeFields(event,prevEvent,operation),computeFields(next.key,event,operation)),prev&&2===possibleIntersection(prev.key,event,eventQueue)){let prevprev=prev;prevprev=prevprev!==begin?sweepLine.prev(prevprev):null,prevprevEvent=prevprev?prevprev.key:null,computeFields(prevEvent,prevprevEvent,operation),computeFields(event,prevEvent,operation)}}else event=event.otherEvent,next=prev=sweepLine.find(event),prev&&next&&(prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next),sweepLine.remove(event),next&&prev&&possibleIntersection(prev.key,next.key,eventQueue))}return sortedEvents})(eventQueue,0,0,sbbox,cbbox,operation),contours=(sortedEvents=>{const resultEvents=(sortedEvents=>{let event,i,len,tmp;const resultEvents=[];for(i=0,len=sortedEvents.length;i{processed[pos]=!0,pos=resultEvents.length)&&resultEvents[pos];);contours.push(contour)}return contours})(sortedEvents),polygons=[];for(let i=0;i=0;k--)hole.push(holePoints[k]);rings.push(hole)}polygons.push(rings)}}return polygons?fromOutlines(polygons.flat()):create$a()},interpolateBetween2DPointsForY=(point1,point2,y)=>{let t,f1=y-point1[1],f2=point2[1]-point1[1];return f2<0&&(f1=-f1,f2=-f2),t=f1<=0?0:f1>=f2?1:f2<1e-10?.5:f1/f2,point1[0]+t*(point2[0]-point1[0])};class OrthonormalFormula{constructor(plane){this.plane=plane;const rightVector=orthogonal([0,0,0],plane);this.v=normalize$1(rightVector,cross$1(rightVector,plane,rightVector)),this.u=cross$1([0,0,0],this.v,plane),this.planeOrigin=scale$3([0,0,0],plane,plane[3]),this.basisMap=new Map}getProjectionMatrix(){return fromValues$4(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)}getInverseProjectionMatrix(){return fromValues$4(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,this.planeOrigin[0],this.planeOrigin[1],this.planeOrigin[2],1)}to2D(vertex){const point=fromValues$2(dot$2(vertex,this.u),dot$2(vertex,this.v));return this.basisMap.set(point,vertex),point}to3D(point){const original=this.basisMap.get(point);if(original)return original;const v1=scale$3([0,0,0],this.u,point[0]),v2=scale$3([0,0,0],this.v,point[1]),v3=add$1(v1,v1,this.planeOrigin);return add$1(v2,v2,v3)}}const insertSorted=(array,element,compareFunc)=>{let leftBound=0,rightBound=array.length;for(;rightBound>leftBound;){const testIndex=Math.floor((leftBound+rightBound)/2);compareFunc(element,array[testIndex])>0?leftBound=testIndex+1:rightBound=testIndex}array.splice(leftBound,0,element)},fnNumberSort=(a,b)=>a-b,classifyPolygons=polygons=>{let clusters=[polygons];const nonCoplanar=[];for(let component=3;component>=0;component--){const maybeCoplanar=[],tolerance=3===component?15e-9:1e-13;clusters.forEach((cluster=>{cluster.sort(byPlaneComponent(component,tolerance));let startIndex=0;for(let i=1;itolerance&&(i-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex,i)),startIndex=i);cluster.length-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex))})),clusters=maybeCoplanar}const result=[];return clusters.forEach((cluster=>{cluster[0]&&(result[cluster[0].index]=cluster)})),nonCoplanar.forEach((polygon=>{result[polygon.index]=polygon})),result},byPlaneComponent=(component,tolerance)=>(a,b)=>a.plane[component]-b.plane[component]>tolerance?1:b.plane[component]-a.plane[component]>tolerance?-1:0;class Node{constructor(parent){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=parent}invert(){const queue=[this];let node;for(let i=0;i{treeNode.isRemoved()||treeNode.splitByPlane(plane,coplanarFrontNodes,backNodes,frontNodes,backNodes)})),node.front&&frontNodes.length>0&&stack.push({node:node.front,polygonTreeNodes:frontNodes});const numBackNodes=backNodes.length;if(node.back&&numBackNodes>0)stack.push({node:node.back,polygonTreeNodes:backNodes});else for(let i=0;i0&&tree.rootnode.clipPolygons(node.polygontreenodes,alsoRemoveCoplanarFront),node.front&&stack.push(node.front),node.back&&stack.push(node.back),node=stack.pop()}while(void 0!==node)}addPolygonTreeNodes(newPolygonTreeNodes){let current={node:this,polygonTreeNodes:newPolygonTreeNodes};const stack=[];do{const node=current.node,polygonTreeNodes=current.polygonTreeNodes,len=polygonTreeNodes.length;if(0===len){current=stack.pop();continue}if(!node.plane){let index=0;index=Math.floor(len/2);const bestPoly=polygonTreeNodes[index].getPolygon();node.plane=plane(bestPoly)}const frontNodes=[],backNodes=[];for(let i=0;i0&&(node.front||(node.front=new Node(node)),len===frontNodes.length&&0===backNodes.length?node.front.polygontreenodes=frontNodes:stack.push({node:node.front,polygonTreeNodes:frontNodes})),backNodes.length>0&&(node.back||(node.back=new Node(node)),len===backNodes.length&&0===frontNodes.length?node.back.polygontreenodes=backNodes:stack.push({node:node.back,polygonTreeNodes:backNodes})),current=stack.pop()}while(void 0!==current)}}const splitLineSegmentByPlane=(plane,p1,p2)=>{const direction=subtract$3([0,0,0],p2,p1);let lambda=(plane[3]-dot$2(plane,p1))/dot$2(plane,direction);return Number.isNaN(lambda)&&(lambda=0),lambda>1&&(lambda=1),lambda<0&&(lambda=0),scale$3(direction,direction,lambda),add$1(direction,p1,direction),direction};class PolygonTreeNode{constructor(parent,polygon){this.parent=parent,this.children=[],this.polygon=polygon,this.removed=!1}addPolygons(polygons){if(!this.isRootNode())throw new Error("Assertion failed");const _this=this;polygons.forEach((polygon=>{_this.addChild(polygon)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const parentschildren=this.parent.children,i=parentschildren.indexOf(this);if(i<0)throw new Error("Assertion failed");parentschildren.splice(i,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(result){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){if(this.children.length){const queue=[this.children];let i,j,l,node,nodes;for(i=0;i0?queue.push(node.children):node._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}else this._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}_splitByPlane(splane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){const polygon=this.polygon;if(polygon){const bound=measureBoundingSphere$1(polygon),sphereRadius=bound[3]+EPS,d=dot$2(splane,bound)-splane[3];if(d>sphereRadius)frontNodes.push(this);else if(d<-sphereRadius)backNodes.push(this);else{const splitResult=((splane,polygon)=>{const result={type:null,front:null,back:null},vertices=polygon.vertices,numVertices=vertices.length,pplane=plane(polygon);if(equals$5(pplane,splane))result.type=0;else{let hasFront=!1,hasBack=!1;const vertexIsBack=[],MINEPS=-EPS;for(let i=0;iEPS&&(hasFront=!0),t=numVertices&&(nextVertexIndex=0);const nextIsBack=vertexIsBack[nextVertexIndex];if(isback===nextIsBack)isback?backVertices.push(vertex):frontVertices.push(vertex);else{const nextPoint=vertices[nextVertexIndex],intersectionPoint=splitLineSegmentByPlane(splane,vertex,nextPoint);isback?(backVertices.push(vertex),backVertices.push(intersectionPoint),frontVertices.push(intersectionPoint)):(frontVertices.push(vertex),frontVertices.push(intersectionPoint),backVertices.push(intersectionPoint))}isback=nextIsBack}const EPS_SQUARED=EPS*EPS;if(backVertices.length>=3){let prevVertex=backVertices[backVertices.length-1];for(let vertexIndex=0;vertexIndex=3){let prevVertex=frontVertices[frontVertices.length-1];for(let vertexIndex=0;vertexIndex=3&&(result.front=fromVerticesAndPlane(frontVertices,pplane)),backVertices.length>=3&&(result.back=fromVerticesAndPlane(backVertices,pplane))}else result.type=3;else result.type=2;else{const t=dot$2(splane,pplane);result.type=t>=0?0:1}}return result})(splane,polygon);switch(splitResult.type){case 0:coplanarFrontNodes.push(this);break;case 1:coplanarBackNodes.push(this);break;case 2:frontNodes.push(this);break;case 3:backNodes.push(this);break;case 4:if(splitResult.front){const frontNode=this.addChild(splitResult.front);frontNodes.push(frontNode)}if(splitResult.back){const backNode=this.addChild(splitResult.back);backNodes.push(backNode)}}}}}addChild(polygon){const newChild=new PolygonTreeNode(this,polygon);return this.children.push(newChild),newChild}invertSub(){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let children=[this];const queue=[children];for(let i=0;i0&&queue.push(node.children),node.children=[]}}}toString(){let result="",children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}return result}}class Tree{constructor(polygons){this.polygonTree=new PolygonTreeNode,this.rootnode=new Node(null),polygons&&this.addPolygons(polygons)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(tree,alsoRemoveCoplanarFront=!1){this.rootnode.clipTo(tree,alsoRemoveCoplanarFront)}allPolygons(){const result=[];return this.polygonTree.getPolygons(result),result}addPolygons(polygons){const polygonTreeNodes=new Array(polygons.length);for(let i=0;i{let newGeometry=(geometries=flatten$1(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!((geometry1,geometry2)=>{if(0===geometry1.polygons.length||0===geometry2.polygons.length)return!1;const bounds1=measureBoundingBox(geometry1),min1=bounds1[0],max1=bounds1[1],bounds2=measureBoundingBox(geometry2),min2=bounds2[0],max2=bounds2[1];return!(min2[0]-max1[0]>EPS||min1[0]-max2[0]>EPS||min2[1]-max1[1]>EPS||min1[1]-max2[1]>EPS||min2[2]-max1[2]>EPS||min1[2]-max2[2]>EPS)})(geometry1,geometry2))return clone$7(geometry1);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),a.clipTo(b),b.clipTo(a,!0),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=(geometry=>{if(geometry.isRetesselated)return geometry;const polygons=toPolygons$1(geometry).map(((polygon,index)=>({vertices:polygon.vertices,plane:plane(polygon),index:index}))),classified=classifyPolygons(polygons),destPolygons=[];classified.forEach((group=>{if(Array.isArray(group)){const reTessellateCoplanarPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const destPolygons=[],numPolygons=sourcePolygons.length,plane$1=plane(sourcePolygons[0]),orthonormalFormula=new OrthonormalFormula(plane$1),polygonVertices2d=[],polygonTopVertexIndexes=[],topy2polygonIndexes=new Map,yCoordinateToPolygonIndexes=new Map,yCoordinateBins=new Map;for(let polygonIndex=0;polygonIndex0){let miny,maxy;for(let i=0;imaxy)&&(maxy=y);let polygonIndexes=yCoordinateToPolygonIndexes.get(y);polygonIndexes||(polygonIndexes={},yCoordinateToPolygonIndexes.set(y,polygonIndexes)),polygonIndexes[polygonIndex]=!0}if(miny>=maxy)vertices2d=[],numVertices=0,minIndex=-1;else{let polygonIndexes=topy2polygonIndexes.get(miny);polygonIndexes||(polygonIndexes=[],topy2polygonIndexes.set(miny,polygonIndexes)),polygonIndexes.push(polygonIndex)}}vertices2d.reverse(),minIndex=numVertices-minIndex-1,polygonVertices2d.push(vertices2d),polygonTopVertexIndexes.push(minIndex)}const yCoordinates=[];yCoordinateToPolygonIndexes.forEach(((polylist,y)=>yCoordinates.push(y))),yCoordinates.sort(fnNumberSort);let activePolygons=[],prevOutPolygonRow=[];for(let yIndex=0;yIndex=numVertices&&(nextLeftVertexIndex=0),vertices2d[nextLeftVertexIndex][1]!==yCoordinate)break;newLeftVertexIndex=nextLeftVertexIndex}let nextRightVertexIndex=newRightVertexIndex-1;if(nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),vertices2d[nextRightVertexIndex][1]===yCoordinate&&(newRightVertexIndex=nextRightVertexIndex),newLeftVertexIndex!==activePolygon.leftVertexIndex&&newLeftVertexIndex===newRightVertexIndex)activePolygons.splice(activePolygonIndex,1),--activePolygonIndex;else{activePolygon.leftVertexIndex=newLeftVertexIndex,activePolygon.rightVertexIndex=newRightVertexIndex,activePolygon.topLeft=vertices2d[newLeftVertexIndex],activePolygon.topRight=vertices2d[newRightVertexIndex];let nextLeftVertexIndex=newLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0),activePolygon.bottomLeft=vertices2d[nextLeftVertexIndex];let nextRightVertexIndex=newRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),activePolygon.bottomRight=vertices2d[nextRightVertexIndex]}}}let nextYcoordinate;if(yIndex>=yCoordinates.length-1)activePolygons=[],nextYcoordinate=null;else{nextYcoordinate=Number(yCoordinates[yIndex+1]);const middleYcoordinate=.5*(yCoordinate+nextYcoordinate),startingPolygonIndexes=topy2polygonIndexes.get(yCoordinate);for(const polygonIndexKey in startingPolygonIndexes){const polygonIndex=startingPolygonIndexes[polygonIndexKey],vertices2d=polygonVertices2d[polygonIndex],numVertices=vertices2d.length,topVertexIndex=polygonTopVertexIndexes[polygonIndex];let topLeftVertexIndex=topVertexIndex;for(;;){let i=topLeftVertexIndex+1;if(i>=numVertices&&(i=0),vertices2d[i][1]!==yCoordinate)break;if(i===topVertexIndex)break;topLeftVertexIndex=i}let topRightVertexIndex=topVertexIndex;for(;;){let i=topRightVertexIndex-1;if(i<0&&(i=numVertices-1),vertices2d[i][1]!==yCoordinate)break;if(i===topLeftVertexIndex)break;topRightVertexIndex=i}let nextLeftVertexIndex=topLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0);let nextRightVertexIndex=topRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1);const newActivePolygon={polygonIndex:polygonIndex,leftVertexIndex:topLeftVertexIndex,rightVertexIndex:topRightVertexIndex,topLeft:vertices2d[topLeftVertexIndex],topRight:vertices2d[topRightVertexIndex],bottomLeft:vertices2d[nextLeftVertexIndex],bottomRight:vertices2d[nextRightVertexIndex]};insertSorted(activePolygons,newActivePolygon,((el1,el2)=>{const x1=interpolateBetween2DPointsForY(el1.topLeft,el1.bottomLeft,middleYcoordinate),x2=interpolateBetween2DPointsForY(el2.topLeft,el2.bottomLeft,middleYcoordinate);return x1>x2?1:x10){const prevOutPolygon=newOutPolygonRow[newOutPolygonRow.length-1],d1=distance(outPolygon.topLeft,prevOutPolygon.topRight),d2=distance(outPolygon.bottomLeft,prevOutPolygon.bottomRight);d10){const prevContinuedIndexes=new Set,matchedIndexes=new Set;for(let i=0;i=0)&&(rightLineContinues||d2>=0)&&(thisPolygon.outPolygon=prevPolygon.outPolygon,thisPolygon.leftLineContinues=leftLineContinues,thisPolygon.rightLineContinues=rightLineContinues,prevContinuedIndexes.add(ii));break}}}for(let ii=0;iiEPS&&prevPolygon.outPolygon.leftPoints.push(prevPolygon.bottomLeft),prevPolygon.outPolygon.leftPoints.reverse();const vertices3d=prevPolygon.outPolygon.rightPoints.concat(prevPolygon.outPolygon.leftPoints).map((point2d=>orthonormalFormula.to3D(point2d))),polygon=fromVerticesAndPlane(vertices3d,plane$1);polygon.vertices.length&&destPolygons.push(polygon)}}for(let i=0;iEPS&&thisPolygon.outPolygon.rightPoints.push(thisPolygon.topRight))}prevOutPolygonRow=newOutPolygonRow}return destPolygons})(group);destPolygons.push(...reTessellateCoplanarPolygons)}else destPolygons.push(group)}));const result=create$8(destPolygons);return result.isRetesselated=!0,result})(newGeometry),newGeometry},subtract=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("subtract wrong number of arguments");if(!(shapes=>{let previousType;for(const shape of shapes){let currentType=0;if(isA$5(shape)&&(currentType=1),isA$3(shape)&&(currentType=2),isA$2(shape)&&(currentType=3),previousType&¤tType!==previousType)return!1;previousType=currentType}return!0})(geometries))throw new Error("subtract arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return((...geometries)=>{let newGeometry=(geometries=flatten$1(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,2)})),newGeometry})(geometries);if(isA$3(geometry))return subtractGeom3(geometries);throw new Error("subtract unsupported geometry type")},createTransform=(center,rotation,scale,scaleOrientation,translation)=>{const matrix=index$c.create(),temp=index$c.create();return index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,translation)),index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,center)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,rotation[3],rotation)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,scaleOrientation[3],scaleOrientation)),index$c.multiply(matrix,matrix,index$c.fromScaling(temp,scale)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,scaleOrientation[3],index$d.negate(index$d.create(),scaleOrientation))),index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,index$d.negate(index$d.create(),center))),matrix},x3dTypes_X3D=0,x3dTypes_UNIT=1,x3dTypes_META=2,x3dTypes_SCENE=3,x3dTypes_TRANSFORM=4,x3dTypes_SHAPE=5,x3dTypes_GROUP=6,x3dTypes_APPEARANCE=7,x3dTypes_TRIANGLESET=10,x3dTypes_TRIANGLEFANSET=11,x3dTypes_TRIANGLESTRIPSET=12,x3dTypes_QUADSET=13,x3dTypes_INDEXEDTRIANGLESET=14,x3dTypes_INDEXEDTRIANGLEFANSET=15,x3dTypes_INDEXEDTRIANGLESTRIPSET=16,x3dTypes_INDEXEDQUADSET=17,x3dTypes_ELEVATIONGRID=18,x3dTypes_INDEXEDFACESET=19,x3dTypes_LINESET=20,x3dTypes_INDEXEDLINESET=21,x3dTypes_BOX=50,x3dTypes_CONE=51,x3dTypes_CYLINDER=52,x3dTypes_SPHERE=53,x3dTypes_EXTRUSION=54,x3dTypes_ARC2D=61,x3dTypes_ARCCLOSE2D=62,x3dTypes_CIRCLE2D=63,x3dTypes_DISK2D=64,x3dTypes_POLYLINE2D=65,x3dTypes_RECTANGLE2D=66,x3dTypes_TRIANGLESET2D=67,x3dTypes_COLOR=91,x3dTypes_COORDINATE=92,x3dTypes_MATERIAL=93,x3dGroup=element=>{const obj={definition:x3dTypes_GROUP,objects:[]};return obj},isZeroVector=vector=>vector[0]+0===0&&vector[1]+0===0&&vector[2]+0===0,calculateZaxis=(z,p,i,n)=>{const a=index$d.subtract(index$d.create(),n,i),b=index$d.subtract(index$d.create(),p,i);return index$d.normalize(z,index$d.cross(z,a,b))},extrudeX3D=x3dshape=>{let{beginCap:beginCap,endCap:endCap,crossSection:crossSection,orientations:orientations,scales:scales,spine:spine}=Object.assign({},x3dshape);if(index$3.measureArea(index$3.create(crossSection))<0&&crossSection.reverse(),1===scales.length&&(scales=spine.map((s=>scales[0]))),1===orientations.length&&(orientations=spine.map((s=>orientations[0]))),spine.length!==scales.length||spine.length!==orientations.length)throw new Error(`invalid X3D specification; spine scale orientaion length must be the same; ${spine.length}`);const initialShape=index$a.create([crossSection]),initialSlice=index$2.fromGeom2(initialShape);let yaxes=(spine=>{const slength=spine.length,closed=index$d.equals(spine[0],spine[slength-1]),yaxes=[];for(let i=0;i{const slength=spine.length,closed=index$d.equals(spine[0],spine[slength-1]),zaxes=[];let previousZaxis;for(let i=0;i2&&calculateZaxis(zaxis,spine[0],spine[1],spine[2]):i===slength-1?closed?calculateZaxis(zaxis,spine[slength-2],spine[0],spine[1]):slength>2&&calculateZaxis(zaxis,spine[slength-3],spine[slength-2],spine[slength-1]):calculateZaxis(zaxis,spine[i-1],spine[i],spine[i+1]),previousZaxis&&index$d.dot(previousZaxis,zaxis)<0&&index$d.negate(zaxis,zaxis),zaxes.push(zaxis),previousZaxis=zaxis}if(isZeroVector(zaxes[0]))for(let i=1;i{const xaxes=[];for(let i=0;iacc&&isZeroVector(axis)),!0)&&(index$d.subtract(y0direction,spine[1],spine[0]),index$c.fromVectorRotation(y0matrix,index$d.fromValues(0,0,1),y0direction),xaxes=xaxes.map((axis=>[1,0,0])),yaxes=yaxes.map((axis=>[0,1,0])),zaxes=zaxes.map((axis=>[0,0,1]))),((options,base)=>{const defaults={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,callback:defaultCallback},{numberOfSlices:numberOfSlices,capStart:capStart,capEnd:capEnd,close:close,callback:generate}=Object.assign({},defaults,options);if(numberOfSlices<2)throw new Error("numberOfSlices must be 2 or more");const sMax=numberOfSlices-1;let startSlice=null,endSlice=null,prevSlice=null,polygons=[];for(let s=0;s(out[0]=xaxis[0],out[1]=yaxis[0],out[2]=zaxis[0],out[3]=0,out[4]=xaxis[1],out[5]=yaxis[1],out[6]=zaxis[1],out[7]=0,out[8]=xaxis[2],out[9]=yaxis[2],out[10]=zaxis[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out))(index$c.create(),xaxis,yaxis,zaxis),orientationMatrix=index$c.fromRotation(index$c.create(),orientation[3],orientation),rotationMatrix=index$c.create();index$c.multiply(rotationMatrix,y0matrix,rotationMatrix),index$c.multiply(rotationMatrix,scpMatrix,rotationMatrix),index$c.multiply(rotationMatrix,orientationMatrix,rotationMatrix),index$c.multiply(rotationMatrix,translationMatrix,rotationMatrix);let newslice=base;return newslice=index$2.transform(scaleMatrix,newslice),newslice=index$2.transform(rotationMatrix,newslice),newslice}},initialSlice)},findNode=(x3dtype,objects)=>objects.find((object=>object.definition===x3dtype)),findColor=(objects,options)=>{const appearance=findNode(x3dTypes_APPEARANCE,objects);let material;return appearance&&(material=findNode(x3dTypes_MATERIAL,appearance.objects),material)?material.color?material.color:null:(material=findNode(x3dTypes_MATERIAL,objects),material&&material.color?material.color:null)},pointsToString=triangle=>`[\n ${triangle.map((point=>(point=>`[${point}]`)(point))).join(",\n ")}\n ]`,createColors=(shape,color)=>{if(!color)return null;if(!Array.isArray(shape.colorIndex))return null;let colors=null;var colorIndex,faceColors;return!0===shape.colorPerVertex?colors=((colorIndex,vertexColors)=>{if(!Array.isArray(colorIndex)||!Array.isArray(vertexColors))return null;if(colorIndex.length<0||!Array.isArray(colorIndex[0]))return console.log("ERROR: WRONG FORMAT FOR VERTEXCOLORS"),null;const colors=[];for(let i=0;ifaceColors[index]?faceColors[index]:null)):null),colors},convertLine=(options,objects)=>{let shape=findNode(x3dTypes_INDEXEDLINESET,objects);if(shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),indexes=shape.indexes,color=findNode(x3dTypes_COLOR,shape.objects);if(coordinate&&indexes){const pointsSet=indexes.map((index=>{let points=index.map((i=>coordinate.points[i]));return points.findIndex((p=>0!==p[2]))>=0&&(console.warn("WARNING: unsupported 3D indexed line set was ignored"),points=[]),points}));return!0===shape.colorPerVertex?shape.colorIndex=indexes:shape.colorIndex=indexes.map(((index,i)=>i)),{pointsSet:pointsSet,colors:createColors(shape,color)}}}if(shape=findNode(x3dTypes_LINESET,objects),shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),color=findNode(x3dTypes_COLOR,shape.objects),counts=shape.vertexCount;if(coordinate&&counts){let vi=0;const pointsSet=counts.map((count=>{let points=[];for(let i=0;i0!==p[2]))>=0&&(console.warn("WARNING: unsupported 3D line set was ignored"),points=[]),points}));if(!0===shape.colorPerVertex){let ci=0;shape.colorIndex=counts.map((count=>{const index=[];for(let i=0;ii));return{pointsSet:pointsSet,colors:createColors(shape,color)}}}return null},convertMesh=(options,objects)=>{let shape=findNode(x3dTypes_TRIANGLESET,objects);if(shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),color=findNode(x3dTypes_COLOR,shape.objects);if(coordinate){const points=coordinate.points,numpoints=points.length,numfaces=Math.trunc(numpoints/3),faces=[];for(let ti=0;ti2){const points=coordinate.points,numfaces=Math.trunc(index.length/3),faces=[];for(let fi=0;fi0){const points=coordinate.points,numfans=fans.length,faces=[];for(let fi=0;fi0){const points=coordinate.points,numstrips=strips.length,faces=[];for(let si=0;si3){const points=coordinate.points,numquads=Math.trunc(index.length/4),faces=[];for(let qi=0;qi0){const points=coordinate.points;return{type:`indexed faces (${faces.length})`,points:points,faces:faces,colors:createColors(shape,color),orientation:shape.ccw?"outward":"inward"}}}if(shape=findNode(x3dTypes_ELEVATIONGRID,objects),shape){const height=shape.height,color=findNode(x3dTypes_COLOR,shape.objects);if(height&&height.length>0){const xDimension=shape.xDimension,xSpacing=shape.xSpacing,zDimension=shape.zDimension,zSpacing=shape.zSpacing,points=[];let vi=0;for(let z0=0;z0=distances[0]&&distances[1]>=distances[2]&&distances[1]>=distances[3]&&(apexi=1),distances[2]>=distances[0]&&distances[2]>=distances[1]&&distances[2]>=distances[3]&&(apexi=2),distances[3]>=distances[0]&&distances[3]>=distances[1]&&distances[3]>=distances[2]&&(apexi=3),0===apexi&&faces.push([iTL,iBR,iTR],[iTL,iBL,iBR]),1===apexi&&faces.push([iTR,iBL,iBR],[iTR,iTL,iBL]),2===apexi&&faces.push([iBL,iTR,iTL],[iBL,iBR,iTR]),3===apexi&&faces.push([iBR,iTL,iBL],[iBR,iTR,iTL])}const orientation=shape.ccw?"outward":"inward";return!0===shape.colorPerVertex&&(shape.colorIndex=faces),{type:`elevation grid (${xDimension} X ${zDimension})`,points:points,faces:faces,colors:createColors(shape,color),orientation:orientation}}}return null},instantiateMesh=(options,objects)=>{let geometry;const components=convertMesh(0,objects);return components&&(geometry=(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})(components)),geometry},translateMesh=(options,objects)=>{const components=convertMesh(0,objects);if(components){const{type:type,points:points,faces:faces,colors:colors,orientation:orientation}=components;return((type,points,faces,colors,orientation)=>{const colorsCode=Array.isArray(colors)?pointsToString(colors):"null";return{primitive:"polyhedron({points, faces, colors, orientation})",code:`\n // 3D ${type} set: ${points.length} points, ${faces.length} faces\n const points = ${pointsToString(points)}\n const faces = ${pointsToString(faces)}\n const colors = ${colorsCode}\n const orientation = '${orientation}'\n`}})(type,points,faces,colors,orientation)}return null},translateShape=(options,object)=>{let code=`\n// shape\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects,color=findColor(objects);let primitive,shape=findNode(x3dTypes_BOX,objects);if(shape)primitive=`cuboid({size: [${shape.size}]})`;else if(shape=findNode(x3dTypes_CONE,objects),shape)code+=` const shape = rotateX(-Math.PI/2, cylinderElliptic({startRadius: [${shape.bottomRadius},${shape.bottomRadius}], height: ${shape.height}, segments: ${shape.subdivision}, endRadius: [${shape.topRadius}, ${shape.topRadius}]}))\n`,primitive="shape";else if(shape=findNode(x3dTypes_CYLINDER,objects),shape)code+=` const shape = rotateX(-Math.PI/2, cylinder({radius: ${shape.radius}, height: ${shape.height}, segments: ${shape.subdivision}}))\n`,primitive="shape";else if(shape=findNode(x3dTypes_SPHERE,objects),shape)primitive=`sphere({radius: ${shape.radius}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_EXTRUSION,objects),shape){const geometry=extrudeX3D(shape);code+=` const polygons = [\n ${index$6.toPolygons(geometry).map((polygon=>pointsToString(index$7.toVertices(polygon)))).join(",\n ")}\n]\n`,primitive="geom3.fromPoints(polygons)"}if(!primitive)if(shape=findNode(x3dTypes_ARC2D,objects),shape)primitive=`arc({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_ARCCLOSE2D,objects),shape)primitive="PIE"===shape.closureType?`circle({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})`:`geom2.create([path2.toPoints(path2.close(arc({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})))])`;else if(shape=findNode(x3dTypes_CIRCLE2D,objects),shape)primitive=`arc({radius: ${shape.radius}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_DISK2D,objects),shape)primitive=shape.innerRadius===shape.outerRadius?`arc({radius: ${shape.outerRadius}, segments: ${shape.subdivision}})`:0===shape.innerRadius?`circle({radius: ${shape.outerRadius}, segments: ${shape.subdivision}})`:`subtract(circle({radius: ${shape.outerRadius}, segments: ${shape.subdivision}}), primitives.circle({radius: ${shape.innerRadius}, segments: ${shape.subdivision}}))`;else if(shape=findNode(x3dTypes_POLYLINE2D,objects),shape)primitive=`line([[${shape.lineSegments.join("], [")}]])`;else if(shape=findNode(x3dTypes_RECTANGLE2D,objects),shape)primitive=`rectangle({size: [${shape.size}]})`;else if(shape=findNode(x3dTypes_TRIANGLESET2D,objects),shape){const numpoints=shape.vertices.length,numfaces=Math.trunc(numpoints/3);code+=`\n // 2D triangle set: ${numpoints} points, ${numfaces} faces\n const vertices = ${pointsToString(shape.vertices)}\n const triangles = []\n for (let i = 0; i < ${numfaces}; i = i + 3) {\n triangles.push(geom2.create([[vertices[i], vertices[i + 1], vertices[i + 2]]]))\n }\n`,primitive="triangles"}let results=translateMesh(0,objects);return results&&(primitive=results.primitive,code+=results.code),results=((options,objects)=>{const components=convertLine(0,objects);if(components){const{pointsSet:pointsSet,colors:colors}=components;let code=" let lines = []\n";return pointsSet.forEach(((points,i)=>{if(colors){const lineColor=colors[i];code+=` const line${i} = colorize([${lineColor}], primitives.line(${pointsToString(points)}))\n lines.push(line${i})\n`}else code+=` const line${i} = primitives.line(${pointsToString(points)})\n lines.push(line${i})\n`})),{primitive:"...lines",code:code}}return null})(0,objects),results&&(primitive=results.primitive,code+=results.code),primitive&&(code+=color?` objects.push(colorize([${color}], ${primitive}))`:` objects.push(${primitive})`),code+="\n return objects\n}\n",code},translatedList=[],translateDefinition=(options,object)=>{if(translatedList.includes(object.id))return"";translatedList.push(object.id);let code="";switch(object.definition){case x3dTypes_TRANSFORM:code+=((options,object)=>{let code=`\n// transform\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects;for(let i=0;i{let code=`\n// group\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects;for(let i=0;iobjects.reduce(((code,object,index)=>code+translateDefinition(options,object)),"");var saxes={},ed5$1={};!function(exports){function isNameStartChar(c){return c>=65&&c<=90||c>=97&&c<=122||58===c||95===c||8204===c||8205===c||c>=192&&c<=214||c>=216&&c<=246||c>=248&&c<=767||c>=880&&c<=893||c>=895&&c<=8191||c>=8304&&c<=8591||c>=11264&&c<=12271||c>=12289&&c<=55295||c>=63744&&c<=64975||c>=65008&&c<=65533||c>=65536&&c<=983039} + */var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:fromValues$4,fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,measureBoundingSphere$1=polygon=>{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$6=Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");3===color.length&&(color=[color[0],color[1],color[2],1]);const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):Array.isArray(object)?colorize(color,...object):(object.color=color,object)));return 1===results.length?results[0]:results},flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),equals$3=(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices=vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours)),toEdges=slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges};class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}const toPolygons=slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)};var index$2=Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:equals$3,fromGeom2:fromGeom2,fromVertices:fromVertices,isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:toEdges,toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:toPolygons,toString:slice=>{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:transform$3,validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGT=(value,constant)=>Number.isFinite(value)&&value>constant,isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGT(radius,0))throw new Error("radius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS*EPS)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps)),point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},circle=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],(options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:TAU,segments:32};let{center:center,height:height,startRadius:startRadius,startAngle:startAngle,endRadius:endRadius,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGT(height,0))throw new Error("height must be greater then zero");if(!isNumberArray(startRadius,2))throw new Error("startRadius must be an array of X and Y values");if(!startRadius.every((n=>n>=0)))throw new Error("startRadius values must be positive");if(!isNumberArray(endRadius,2))throw new Error("endRadius must be an array of X and Y values");if(!endRadius.every((n=>n>=0)))throw new Error("endRadius values must be positive");if(endRadius.every((n=>0===n))&&startRadius.every((n=>0===n)))throw new Error("at least one radius must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(startRadius[0],startRadius[1],endRadius[0],endRadius[1]),minAngle=Math.acos((minRadius*minRadius+minRadius*minRadius-EPS*EPS)/(2*minRadius*minRadius));if(rotation{const angle=slice*rotation+startAngle;return scale$3(v1,axisX,radius[0]*cos(angle)),scale$3(v2,axisY,radius[1]*sin(angle)),add$1(v1,v1,v2),scale$3(v3,ray,stack),add$1(v3,v3,start),add$1([0,0,0],v1,v3)},fromVertices=(...vertices)=>{const newVertices=vertices.map((vertex=>add$1([0,0,0],vertex,center)));return create$7(newVertices)},polygons=[];for(let i=0;i0&&startRadius[1]>0&&polygons.push(fromVertices(start,genVertex(0,t1,startRadius),genVertex(0,t0,startRadius))),(startRadius[0]>0||startRadius[1]>0)&&polygons.push(fromVertices(genVertex(0,t0,startRadius),genVertex(0,t1,startRadius),genVertex(1,t0,endRadius))),endRadius[0]>0&&endRadius[1]>0&&polygons.push(fromVertices(end,genVertex(1,t0,endRadius),genVertex(1,t1,endRadius))),(endRadius[0]>0||endRadius[1]>0)&&polygons.push(fromVertices(genVertex(1,t0,endRadius),genVertex(0,t1,startRadius),genVertex(1,t1,endRadius))))}return rotation{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},sphere=options=>{let{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius,radius],(options=>{const{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(radius,3))throw new Error("radius must be an array of X, Y and Z values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===radius[0]||0===radius[1]||0===radius[2])return create$8();const xVector=scale$3([0,0,0],normalize$1([0,0,0],axes[0]),radius[0]),yVector=scale$3([0,0,0],normalize$1([0,0,0],axes[1]),radius[1]),zVector=scale$3([0,0,0],normalize$1([0,0,0],axes[2]),radius[2]),qSegments=Math.round(segments/4);let prevCylinderVertex;const polygons=[],p1=[0,0,0],p2=[0,0,0];for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(p1,xVector,cos(angle)),scale$3(p2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch;for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);if(slice2>0){let vertex,vertices=[];vertex=subtract$3([0,0,0],scale$3(p1,prevCylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),vertex=subtract$3([0,0,0],scale$3(p1,cylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),slice2a===b?a:a{const multiple=newLength/edges.length;if(1===multiple)return edges;const divisor=fromValues$3(multiple,multiple,multiple),newEdges=[];return edges.forEach((edge=>{const increment=subtract$3([0,0,0],edge[1],edge[0]);divide$1(increment,increment,divisor);let prev=edge[0];for(let i=1;i<=multiple;++i){const next=add$1([0,0,0],prev,increment);newEdges.push([prev,next]),prev=next}})),newEdges},EPSAREA=EPS*EPS/2*Math.sin(Math.PI/3),extrudeWalls=(slice0,slice1)=>{let edges0=toEdges(slice0),edges1=toEdges(slice1);if(edges0.length!==edges1.length){const newLength=(a=edges0.length)*(b=edges1.length)/gcd(a,b);newLength!==edges0.length&&(edges0=repartitionEdges(newLength,edges0)),newLength!==edges1.length&&(edges1=repartitionEdges(newLength,edges1))}var a,b;const walls=[];return edges0.forEach(((edge0,i)=>{const edge1=edges1[i],poly0=create$7([edge0[0],edge0[1],edge1[1]]),poly0area=measureArea$2(poly0);Number.isFinite(poly0area)&&poly0area>EPSAREA&&walls.push(poly0);const poly1=create$7([edge0[0],edge1[1],edge1[0]]),poly1area=measureArea$2(poly1);Number.isFinite(poly1area)&&poly1area>EPSAREA&&walls.push(poly1)})),walls},defaultCallback=(progress,index,base)=>{let baseSlice=null;return isA$5(base)&&(baseSlice=fromGeom2(base)),isA$4(base)&&(baseSlice=fromVertices(toVertices$1(base))),0===progress||1===progress?transform$3(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[0,0,progress]),baseSlice):null},rotate=(angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?rotate(angles,...object):object));return 1===results.length?results[0]:results},rotateX=(angle,...objects)=>rotate([angle,0,0],...objects),flattenHelper=(arr,out)=>(Array.isArray(arr)?arr.forEach((child=>flattenHelper(child,out))):null!=arr&&void 0!==arr&&out.push(arr),out),DEFAULT_COMPARE=(a,b)=>a>b?1:a{const N=new Node$1(null,null);let l=N,r=N;for(;;){const cmp=comparator(i,t.key);if(cmp<0){if(null===t.left)break;if(comparator(i,t.left.key)<0){const y=t.left;if(t.left=y.right,y.right=t,null===(t=y).left)break}r.left=t,r=t,t=t.left}else{if(!(cmp>0))break;if(null===t.right)break;if(comparator(i,t.right.key)>0){const y=t.right;if(t.right=y.left,y.left=t,null===(t=y).right)break}l.right=t,l=t,t=t.right}}return l.right=t.left,r.left=t.right,t.left=N.right,t.right=N.left,t},insert=(i,data,t,comparator)=>{const node=new Node$1(i,data);if(null===t)return node.left=node.right=null,node;const cmp=comparator(i,(t=splay(i,t,comparator)).key);return cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>=0&&(node.right=t.right,node.left=t,t.right=null),node},split=(key,v,comparator)=>{let left=null,right=null;if(v){const cmp=comparator((v=splay(key,v,comparator)).key,key);0===cmp?(left=v.left,right=v.right):cmp<0?(right=v.right,v.right=null,left=v):(left=v.left,v.left=null,right=v)}return{left:left,right:right}},printRow=(root,prefix,isTail,out,printNode)=>{if(root){out(`${prefix}${isTail?"└── ":"├── "}${printNode(root)}\n`);const indent=prefix+(isTail?" ":"│ ");root.left&&printRow(root.left,indent,!1,out,printNode),root.right&&printRow(root.right,indent,!0,out,printNode)}};class Tree$1{constructor(comparator=DEFAULT_COMPARE){this._comparator=comparator,this._root=null,this._size=0}insert(key,data){return this._size++,this._root=insert(key,data,this._root,this._comparator),this._root}add(key,data){const node=new Node$1(key,data);null===this._root&&(node.left=node.right=null,this._size++,this._root=node);const comparator=this._comparator,t=splay(key,this._root,comparator),cmp=comparator(key,t.key);return 0===cmp?this._root=t:(cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>0&&(node.right=t.right,node.left=t,t.right=null),this._size++,this._root=node),this._root}remove(key){this._root=this._remove(key,this._root,this._comparator)}_remove(i,t,comparator){let x;return null===t?null:0===comparator(i,(t=splay(i,t,comparator)).key)?(null===t.left?x=t.right:(x=splay(i,t.left,comparator),x.right=t.right),this._size--,x):t}pop(){let node=this._root;if(node){for(;node.left;)node=node.left;return this._root=splay(node.key,this._root,this._comparator),this._root=this._remove(node.key,this._root,this._comparator),{key:node.key,data:node.data}}return null}findStatic(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return current;current=cmp<0?current.left:current.right}return null}find(key){return this._root&&(this._root=splay(key,this._root,this._comparator),0!==this._comparator(key,this._root.key))?null:this._root}contains(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return!0;current=cmp<0?current.left:current.right}return!1}forEach(visitor,ctx){let current=this._root;const Q=[];let done=!1;for(;!done;)null!==current?(Q.push(current),current=current.left):0!==Q.length?(current=Q.pop(),visitor.call(ctx,current),current=current.right):done=!0;return this}range(low,high,fn,ctx){const Q=[],compare=this._comparator;let cmp,node=this._root;for(;0!==Q.length||node;)if(node)Q.push(node),node=node.left;else{if(node=Q.pop(),cmp=compare(node.key,high),cmp>0)break;if(compare(node.key,low)>=0&&fn.call(ctx,node))return this;node=node.right}return this}keys(){const keys=[];return this.forEach((({key:key})=>keys.push(key))),keys}values(){const values=[];return this.forEach((({data:data})=>values.push(data))),values}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(index){let current=this._root,done=!1,i=0;const Q=[];for(;!done;)if(current)Q.push(current),current=current.left;else if(Q.length>0){if(current=Q.pop(),i===index)return current;i++,current=current.right}else done=!0;return null}next(d){let root=this._root,successor=null;if(d.right){for(successor=d.right;successor.left;)successor=successor.left;return successor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?(successor=root,root=root.left):root=root.right}return successor}prev(d){let root=this._root,predecessor=null;if(null!==d.left){for(predecessor=d.left;predecessor.right;)predecessor=predecessor.right;return predecessor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?root=root.left:(predecessor=root,root=root.right)}return predecessor}clear(){return this._root=null,this._size=0,this}toList(){return toList(this._root)}load(keys,values=[],presort=!1){let size=keys.length;const comparator=this._comparator;if(presort&&sort(keys,values,0,size-1,comparator),null===this._root)this._root=loadRecursive(keys,values,0,size),this._size=size;else{const mergedList=mergeLists(this.toList(),createList(keys,values),comparator);size=this._size+size,this._root=sortedListToBST({head:mergedList},0,size)}return this}isEmpty(){return null===this._root}size(){return this._size}root(){return this._root}toString(printNode=(n=>String(n.key))){const out=[];return printRow(this._root,"",!0,(v=>out.push(v)),printNode),out.join("")}update(key,newKey,newData){const comparator=this._comparator;let{left:left,right:right}=split(key,this._root,comparator);comparator(key,newKey)<0?right=insert(newKey,newData,right,comparator):left=insert(newKey,newData,left,comparator),this._root=((left,right,comparator)=>null===right?left:(null===left||((right=splay(left.key,right,comparator)).left=left),right))(left,right,comparator)}split(key){return split(key,this._root,this._comparator)}*[Symbol.iterator](){let n=this.minNode();for(;n;)yield n,n=this.next(n)}}const loadRecursive=(keys,values,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),key=keys[middle],data=values[middle],node=new Node$1(key,data);return node.left=loadRecursive(keys,values,start,middle),node.right=loadRecursive(keys,values,middle+1,end),node}return null},createList=(keys,values)=>{const head=new Node$1(null,null);let p=head;for(let i=0;i{let current=root;const Q=[];let done=!1;const head=new Node$1(null,null);let p=head;for(;!done;)current?(Q.push(current),current=current.left):Q.length>0?(current=p=p.next=Q.pop(),current=current.right):done=!0;return p.next=null,head.next},sortedListToBST=(list,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),left=sortedListToBST(list,start,middle),root=list.head;return root.left=left,list.head=list.head.next,root.right=sortedListToBST(list,middle+1,end),root}return null},mergeLists=(l1,l2,compare)=>{const head=new Node$1(null,null);let p=head,p1=l1,p2=l2;for(;null!==p1&&null!==p2;)compare(p1.key,p2.key)<0?(p.next=p1,p1=p1.next):(p.next=p2,p2=p2.next),p=p.next;return null!==p1?p.next=p1:null!==p2&&(p.next=p2),head.next},sort=(keys,values,left,right,compare)=>{if(left>=right)return;const pivot=keys[left+right>>1];let i=left-1,j=right+1;for(;;){do{i++}while(compare(keys[i],pivot)<0);do{j--}while(compare(keys[j],pivot)>0);if(i>=j)break;let tmp=keys[i];keys[i]=keys[j],keys[j]=tmp,tmp=values[i],values[i]=values[j],values[j]=tmp}sort(keys,values,left,j,compare),sort(keys,values,j+1,right,compare)},computeFields=(event,prev,operation)=>{null===prev?(event.inOut=!1,event.otherInOut=!0):(event.isSubject===prev.isSubject?(event.inOut=!prev.inOut,event.otherInOut=prev.otherInOut):(event.inOut=!prev.otherInOut,event.otherInOut=prev.isVertical()?!prev.inOut:prev.inOut),prev&&(event.prevInResult=!inResult(prev,operation)||prev.isVertical()?prev.prevInResult:prev));const isInResult=inResult(event,operation);event.resultTransition=isInResult?determineResultTransition(event,operation):0},inResult=(event,operation)=>{switch(event.type){case 0:switch(operation){case 0:return!event.otherInOut;case 1:return event.otherInOut;case 2:return event.isSubject&&event.otherInOut||!event.isSubject&&!event.otherInOut;case 3:return!0}break;case 2:return 0===operation||1===operation;case 3:return 2===operation;case 1:return!1}return!1},determineResultTransition=(event,operation)=>{const thisIn=!event.inOut,thatIn=!event.otherInOut;let isIn;switch(operation){case 0:isIn=thisIn&&thatIn;break;case 1:isIn=thisIn||thatIn;break;case 3:isIn=thisIn^thatIn;break;case 2:isIn=event.isSubject?thisIn&&!thatIn:thatIn&&!thisIn}return isIn?1:-1};class SweepEvent{constructor(point,left,otherEvent,isSubject,edgeType){this.left=left,this.point=point,this.otherEvent=otherEvent,this.isSubject=isSubject,this.type=edgeType||0,this.inOut=!1,this.otherInOut=!1,this.prevInResult=null,this.resultTransition=0,this.otherPos=-1,this.outputContourId=-1,this.isExteriorRing=!0}isBelow(p){const p0=this.point,p1=this.otherEvent.point;return this.left?(p0[0]-p[0])*(p1[1]-p[1])-(p1[0]-p[0])*(p0[1]-p[1])>0:(p1[0]-p[0])*(p0[1]-p[1])-(p0[0]-p[0])*(p1[1]-p[1])>0}isAbove(p){return!this.isBelow(p)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return 0!==this.resultTransition}clone(){const copy=new SweepEvent(this.point,this.left,this.otherEvent,this.isSubject,this.type);return copy.contourId=this.contourId,copy.resultTransition=this.resultTransition,copy.prevInResult=this.prevInResult,copy.isExteriorRing=this.isExteriorRing,copy.inOut=this.inOut,copy.otherInOut=this.otherInOut,copy}}const signedArea=(p0,p1,p2)=>{const res=(ax=p0[0],ay=p0[1],bx=p1[0],by=p1[1],cx=p2[0],(ay-(cy=p2[1]))*(bx-cx)-(ax-cx)*(by-cy));var ax,ay,bx,by,cx,cy;return res>0?-1:res<0?1:0},compareEvents=(e1,e2)=>{const p1=e1.point,p2=e2.point;return p1[0]>p2[0]?1:p1[0]p2[1]?1:-1:specialCases(e1,e2,p1)},specialCases=(e1,e2,p1,p2)=>e1.left!==e2.left?e1.left?1:-1:0!==signedArea(p1,e1.otherEvent.point,e2.otherEvent.point)?e1.isBelow(e2.otherEvent.point)?-1:1:!e1.isSubject&&e2.isSubject?1:-1,divideSegment=(se,p,queue)=>{const r=new SweepEvent(p,!1,se,se.isSubject),l=new SweepEvent(p,!0,se.otherEvent,se.isSubject);return r.contourId=l.contourId=se.contourId,compareEvents(l,se.otherEvent)>0&&(se.otherEvent.left=!0,l.left=!1),se.otherEvent.otherEvent=l,se.otherEvent=r,queue.push(l),queue.push(r),queue},crossProduct=(a,b)=>a[0]*b[1]-a[1]*b[0],possibleIntersection=(se1,se2,queue)=>{const inter=((a1,a2,b1,b2,noEndpointTouch)=>{const va=[a2[0]-a1[0],a2[1]-a1[1]],vb=[b2[0]-b1[0],b2[1]-b1[1]],toPoint=(p,s,d)=>[p[0]+s*d[0],p[1]+s*d[1]],e=[b1[0]-a1[0],b1[1]-a1[1]];let kross=crossProduct(va,vb),sqrKross=kross*kross;const sqrLenA=dot$1(va,va);if(sqrKross>0){const s=crossProduct(e,vb)/kross;if(s<0||s>1)return null;const t=crossProduct(e,va)/kross;return t<0||t>1?null:0===s||1===s?[toPoint(a1,s,va)]:0===t||1===t?[toPoint(b1,t,vb)]:[toPoint(a1,s,va)]}if(kross=crossProduct(e,va),sqrKross=kross*kross,sqrKross>0)return null;const sa=dot$1(va,e)/sqrLenA,sb=sa+dot$1(va,vb)/sqrLenA,smin=Math.min(sa,sb),smax=Math.max(sa,sb);return smin<=1&&smax>=0?1===smin?[toPoint(a1,smin>0?smin:0,va)]:0===smax?[toPoint(a1,smax<1?smax:1,va)]:[toPoint(a1,smin>0?smin:0,va),toPoint(a1,smax<1?smax:1,va)]:null})(se1.point,se1.otherEvent.point,se2.point,se2.otherEvent.point),nIntersections=inter?inter.length:0;if(0===nIntersections)return 0;if(1===nIntersections&&(equals$6(se1.point,se2.point)||equals$6(se1.otherEvent.point,se2.otherEvent.point)))return 0;if(2===nIntersections&&se1.isSubject===se2.isSubject)return 0;if(1===nIntersections)return equals$6(se1.point,inter[0])||equals$6(se1.otherEvent.point,inter[0])||divideSegment(se1,inter[0],queue),equals$6(se2.point,inter[0])||equals$6(se2.otherEvent.point,inter[0])||divideSegment(se2,inter[0],queue),1;const events=[];let leftCoincide=!1,rightCoincide=!1;return equals$6(se1.point,se2.point)?leftCoincide=!0:1===compareEvents(se1,se2)?events.push(se2,se1):events.push(se1,se2),equals$6(se1.otherEvent.point,se2.otherEvent.point)?rightCoincide=!0:1===compareEvents(se1.otherEvent,se2.otherEvent)?events.push(se2.otherEvent,se1.otherEvent):events.push(se1.otherEvent,se2.otherEvent),leftCoincide&&rightCoincide||leftCoincide?(se2.type=1,se1.type=se2.inOut===se1.inOut?2:3,leftCoincide&&!rightCoincide&÷Segment(events[1].otherEvent,events[0].point,queue),2):rightCoincide?(divideSegment(events[0],events[1].point,queue),3):events[0]!==events[3].otherEvent?(divideSegment(events[0],events[1].point,queue),divideSegment(events[1],events[2].point,queue),3):(divideSegment(events[0],events[1].point,queue),divideSegment(events[3].otherEvent,events[2].point,queue),3)},compareSegments=(le1,le2)=>{if(le1===le2)return 0;if(0!==signedArea(le1.point,le1.otherEvent.point,le2.point)||0!==signedArea(le1.point,le1.otherEvent.point,le2.otherEvent.point))return equals$6(le1.point,le2.point)?le1.isBelow(le2.otherEvent.point)?-1:1:le1.point[0]===le2.point[0]?le1.point[1]le2.contourId?1:-1}return 1===compareEvents(le1,le2)?1:-1};class Contour{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return null==this.holeOf}}const nextPos=(pos,resultEvents,processed,origPos)=>{let newPos=pos+1;const p=resultEvents[pos].point;let p1;const length=resultEvents.length;for(newPosorigPos;)newPos--;return newPos},initializeContourFromContext=(event,contours,contourId)=>{const contour=new Contour;if(null!=event.prevInResult){const prevInResult=event.prevInResult,lowerContourId=prevInResult.outputContourId,lowerResultTransition=prevInResult.resultTransition;if(lowerContourId<0)contour.holeOf=null,contour.depth=0;else if(lowerResultTransition>0){const lowerContour=contours[lowerContourId];if(null!=lowerContour.holeOf){const parentContourId=lowerContour.holeOf;contours[parentContourId].holeIds.push(contourId),contour.holeOf=parentContourId,contour.depth=contours[lowerContourId].depth}else contours[lowerContourId].holeIds.push(contourId),contour.holeOf=lowerContourId,contour.depth=contours[lowerContourId].depth+1}else contour.holeOf=null,contour.depth=contours[lowerContourId].depth}else contour.holeOf=null,contour.depth=0;return contour};class Queue{constructor(data,compare){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this._up(this.length++)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return--this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos=0)break;data[pos]=data[bestChild],pos=bestChild}data[pos]=item}}const max=Math.max,min=Math.min;let contourId=0;const processPolygon=(contourOrHole,isSubject,depth,queue,bbox,isExteriorRing)=>{const len=contourOrHole.length-1;let s1,s2,e1,e2;for(let i=0;i0?e2.left=!0:e1.left=!0;const x=s1[0],y=s1[1];bbox[0]=min(bbox[0],x),bbox[1]=min(bbox[1],y),bbox[2]=max(bbox[2],x),bbox[3]=max(bbox[3],y),queue.push(e1),queue.push(e2)}},EMPTY=[],toMartinez=geometry=>{const outlines=[];return toOutlines(geometry).forEach((outline=>{equals$6(outline[0],outline[outline.length-1])?outlines.push(outline):outlines.push([...outline,outline[0]])})),[outlines]},fromOutlines=outlines=>(outlines.forEach((outline=>{equals$6(outline[0],outline[outline.length-1])&&outline.pop()})),outlines=outlines.filter((o=>o.length>=3)),create$a(outlines)),boolean=(subjectGeom,clippingGeom,operation)=>{const subject=toMartinez(subjectGeom),clipping=toMartinez(clippingGeom);let trivial=((subject,clipping,operation)=>{let result=null;if(subject.length*clipping.length==0){if(0===operation)return EMPTY;2===operation?result=subject:1!==operation&&3!==operation||(result=0===subject.length?clipping:subject)}return result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,operation);if(trivial)return trivial;const sbbox=[1/0,1/0,-1/0,-1/0],cbbox=[1/0,1/0,-1/0,-1/0],eventQueue=((subject,clipping,sbbox,cbbox,operation)=>{const eventQueue=new Queue([],compareEvents);let polygonSet,isExteriorRing,i,ii,j,jj;for(i=0,ii=subject.length;i{let result=null;return(sbbox[0]>cbbox[2]||cbbox[0]>sbbox[2]||sbbox[1]>cbbox[3]||cbbox[1]>sbbox[3])&&(0===operation?result=EMPTY:2===operation?result=subject:1!==operation&&3!==operation||(result=subject.concat(clipping))),result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,sbbox,cbbox,operation),trivial)return trivial;const sortedEvents=((eventQueue,subject,clipping,sbbox,cbbox,operation)=>{const sweepLine=new Tree$1(compareSegments),sortedEvents=[],rightBound=Math.min(sbbox[2],cbbox[2]);let prev,next,begin;for(;0!==eventQueue.length;){let event=eventQueue.pop();if(sortedEvents.push(event),0===operation&&event.point[0]>rightBound||2===operation&&event.point[0]>sbbox[2])break;if(event.left){next=prev=sweepLine.insert(event),begin=sweepLine.minNode(),prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next);const prevEvent=prev?prev.key:null;let prevprevEvent;if(computeFields(event,prevEvent,operation),next&&2===possibleIntersection(event,next.key,eventQueue)&&(computeFields(event,prevEvent,operation),computeFields(next.key,event,operation)),prev&&2===possibleIntersection(prev.key,event,eventQueue)){let prevprev=prev;prevprev=prevprev!==begin?sweepLine.prev(prevprev):null,prevprevEvent=prevprev?prevprev.key:null,computeFields(prevEvent,prevprevEvent,operation),computeFields(event,prevEvent,operation)}}else event=event.otherEvent,next=prev=sweepLine.find(event),prev&&next&&(prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next),sweepLine.remove(event),next&&prev&&possibleIntersection(prev.key,next.key,eventQueue))}return sortedEvents})(eventQueue,0,0,sbbox,cbbox,operation),contours=(sortedEvents=>{const resultEvents=(sortedEvents=>{let event,i,len,tmp;const resultEvents=[];for(i=0,len=sortedEvents.length;i{processed[pos]=!0,pos=resultEvents.length)&&resultEvents[pos];);contours.push(contour)}return contours})(sortedEvents),polygons=[];for(let i=0;i=0;k--)hole.push(holePoints[k]);rings.push(hole)}polygons.push(rings)}}return polygons?fromOutlines(polygons.flat()):create$a()},interpolateBetween2DPointsForY=(point1,point2,y)=>{let t,f1=y-point1[1],f2=point2[1]-point1[1];return f2<0&&(f1=-f1,f2=-f2),t=f1<=0?0:f1>=f2?1:f2<1e-10?.5:f1/f2,point1[0]+t*(point2[0]-point1[0])};class OrthonormalFormula{constructor(plane){this.plane=plane;const rightVector=orthogonal([0,0,0],plane);this.v=normalize$1(rightVector,cross$1(rightVector,plane,rightVector)),this.u=cross$1([0,0,0],this.v,plane),this.planeOrigin=scale$3([0,0,0],plane,plane[3]),this.basisMap=new Map}getProjectionMatrix(){return fromValues$4(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)}getInverseProjectionMatrix(){return fromValues$4(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,this.planeOrigin[0],this.planeOrigin[1],this.planeOrigin[2],1)}to2D(vertex){const point=fromValues$2(dot$2(vertex,this.u),dot$2(vertex,this.v));return this.basisMap.set(point,vertex),point}to3D(point){const original=this.basisMap.get(point);if(original)return original;const v1=scale$3([0,0,0],this.u,point[0]),v2=scale$3([0,0,0],this.v,point[1]),v3=add$1(v1,v1,this.planeOrigin);return add$1(v2,v2,v3)}}const insertSorted=(array,element,compareFunc)=>{let leftBound=0,rightBound=array.length;for(;rightBound>leftBound;){const testIndex=Math.floor((leftBound+rightBound)/2);compareFunc(element,array[testIndex])>0?leftBound=testIndex+1:rightBound=testIndex}array.splice(leftBound,0,element)},fnNumberSort=(a,b)=>a-b,classifyPolygons=polygons=>{let clusters=[polygons];const nonCoplanar=[];for(let component=3;component>=0;component--){const maybeCoplanar=[],tolerance=3===component?15e-9:1e-13;clusters.forEach((cluster=>{cluster.sort(byPlaneComponent(component,tolerance));let startIndex=0;for(let i=1;itolerance&&(i-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex,i)),startIndex=i);cluster.length-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex))})),clusters=maybeCoplanar}const result=[];return clusters.forEach((cluster=>{cluster[0]&&(result[cluster[0].index]=cluster)})),nonCoplanar.forEach((polygon=>{result[polygon.index]=polygon})),result},byPlaneComponent=(component,tolerance)=>(a,b)=>a.plane[component]-b.plane[component]>tolerance?1:b.plane[component]-a.plane[component]>tolerance?-1:0;class Node{constructor(parent){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=parent}invert(){const queue=[this];let node;for(let i=0;i{treeNode.isRemoved()||treeNode.splitByPlane(plane,coplanarFrontNodes,backNodes,frontNodes,backNodes)})),node.front&&frontNodes.length>0&&stack.push({node:node.front,polygonTreeNodes:frontNodes});const numBackNodes=backNodes.length;if(node.back&&numBackNodes>0)stack.push({node:node.back,polygonTreeNodes:backNodes});else for(let i=0;i0&&tree.rootnode.clipPolygons(node.polygontreenodes,alsoRemoveCoplanarFront),node.front&&stack.push(node.front),node.back&&stack.push(node.back),node=stack.pop()}while(void 0!==node)}addPolygonTreeNodes(newPolygonTreeNodes){let current={node:this,polygonTreeNodes:newPolygonTreeNodes};const stack=[];do{const node=current.node,polygonTreeNodes=current.polygonTreeNodes,len=polygonTreeNodes.length;if(0===len){current=stack.pop();continue}if(!node.plane){let index=0;index=Math.floor(len/2);const bestPoly=polygonTreeNodes[index].getPolygon();node.plane=plane(bestPoly)}const frontNodes=[],backNodes=[];for(let i=0;i0&&(node.front||(node.front=new Node(node)),len===frontNodes.length&&0===backNodes.length?node.front.polygontreenodes=frontNodes:stack.push({node:node.front,polygonTreeNodes:frontNodes})),backNodes.length>0&&(node.back||(node.back=new Node(node)),len===backNodes.length&&0===frontNodes.length?node.back.polygontreenodes=backNodes:stack.push({node:node.back,polygonTreeNodes:backNodes})),current=stack.pop()}while(void 0!==current)}}const splitLineSegmentByPlane=(plane,p1,p2)=>{const direction=subtract$3([0,0,0],p2,p1);let lambda=(plane[3]-dot$2(plane,p1))/dot$2(plane,direction);return Number.isNaN(lambda)&&(lambda=0),lambda>1&&(lambda=1),lambda<0&&(lambda=0),scale$3(direction,direction,lambda),add$1(direction,p1,direction),direction};class PolygonTreeNode{constructor(parent,polygon){this.parent=parent,this.children=[],this.polygon=polygon,this.removed=!1}addPolygons(polygons){if(!this.isRootNode())throw new Error("Assertion failed");const _this=this;polygons.forEach((polygon=>{_this.addChild(polygon)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const parentschildren=this.parent.children,i=parentschildren.indexOf(this);if(i<0)throw new Error("Assertion failed");parentschildren.splice(i,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(result){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){if(this.children.length){const queue=[this.children];let i,j,l,node,nodes;for(i=0;i0?queue.push(node.children):node._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}else this._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}_splitByPlane(splane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){const polygon=this.polygon;if(polygon){const bound=measureBoundingSphere$1(polygon),sphereRadius=bound[3]+EPS,d=dot$2(splane,bound)-splane[3];if(d>sphereRadius)frontNodes.push(this);else if(d<-sphereRadius)backNodes.push(this);else{const splitResult=((splane,polygon)=>{const result={type:null,front:null,back:null},vertices=polygon.vertices,numVertices=vertices.length,pplane=plane(polygon);if(equals$5(pplane,splane))result.type=0;else{let hasFront=!1,hasBack=!1;const vertexIsBack=[],MINEPS=-EPS;for(let i=0;iEPS&&(hasFront=!0),t=numVertices&&(nextVertexIndex=0);const nextIsBack=vertexIsBack[nextVertexIndex];if(isback===nextIsBack)isback?backVertices.push(vertex):frontVertices.push(vertex);else{const nextPoint=vertices[nextVertexIndex],intersectionPoint=splitLineSegmentByPlane(splane,vertex,nextPoint);isback?(backVertices.push(vertex),backVertices.push(intersectionPoint),frontVertices.push(intersectionPoint)):(frontVertices.push(vertex),frontVertices.push(intersectionPoint),backVertices.push(intersectionPoint))}isback=nextIsBack}const EPS_SQUARED=EPS*EPS;if(backVertices.length>=3){let prevVertex=backVertices[backVertices.length-1];for(let vertexIndex=0;vertexIndex=3){let prevVertex=frontVertices[frontVertices.length-1];for(let vertexIndex=0;vertexIndex=3&&(result.front=fromVerticesAndPlane(frontVertices,pplane)),backVertices.length>=3&&(result.back=fromVerticesAndPlane(backVertices,pplane))}else result.type=3;else result.type=2;else{const t=dot$2(splane,pplane);result.type=t>=0?0:1}}return result})(splane,polygon);switch(splitResult.type){case 0:coplanarFrontNodes.push(this);break;case 1:coplanarBackNodes.push(this);break;case 2:frontNodes.push(this);break;case 3:backNodes.push(this);break;case 4:if(splitResult.front){const frontNode=this.addChild(splitResult.front);frontNodes.push(frontNode)}if(splitResult.back){const backNode=this.addChild(splitResult.back);backNodes.push(backNode)}}}}}addChild(polygon){const newChild=new PolygonTreeNode(this,polygon);return this.children.push(newChild),newChild}invertSub(){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let children=[this];const queue=[children];for(let i=0;i0&&queue.push(node.children),node.children=[]}}}toString(){let result="",children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}return result}}class Tree{constructor(polygons){this.polygonTree=new PolygonTreeNode,this.rootnode=new Node(null),polygons&&this.addPolygons(polygons)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(tree,alsoRemoveCoplanarFront=!1){this.rootnode.clipTo(tree,alsoRemoveCoplanarFront)}allPolygons(){const result=[];return this.polygonTree.getPolygons(result),result}addPolygons(polygons){const polygonTreeNodes=new Array(polygons.length);for(let i=0;i{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!((geometry1,geometry2)=>{if(0===geometry1.polygons.length||0===geometry2.polygons.length)return!1;const bounds1=measureBoundingBox(geometry1),min1=bounds1[0],max1=bounds1[1],bounds2=measureBoundingBox(geometry2),min2=bounds2[0],max2=bounds2[1];return!(min2[0]-max1[0]>EPS||min1[0]-max2[0]>EPS||min2[1]-max1[1]>EPS||min1[1]-max2[1]>EPS||min2[2]-max1[2]>EPS||min1[2]-max2[2]>EPS)})(geometry1,geometry2))return clone$7(geometry1);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),a.clipTo(b),b.clipTo(a,!0),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=(geometry=>{if(geometry.isRetesselated)return geometry;const polygons=toPolygons$1(geometry).map(((polygon,index)=>({vertices:polygon.vertices,plane:plane(polygon),index:index}))),classified=classifyPolygons(polygons),destPolygons=[];classified.forEach((group=>{if(Array.isArray(group)){const reTessellateCoplanarPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const destPolygons=[],numPolygons=sourcePolygons.length,plane$1=plane(sourcePolygons[0]),orthonormalFormula=new OrthonormalFormula(plane$1),polygonVertices2d=[],polygonTopVertexIndexes=[],topy2polygonIndexes=new Map,yCoordinateToPolygonIndexes=new Map,yCoordinateBins=new Map;for(let polygonIndex=0;polygonIndex0){let miny,maxy;for(let i=0;imaxy)&&(maxy=y);let polygonIndexes=yCoordinateToPolygonIndexes.get(y);polygonIndexes||(polygonIndexes={},yCoordinateToPolygonIndexes.set(y,polygonIndexes)),polygonIndexes[polygonIndex]=!0}if(miny>=maxy)vertices2d=[],numVertices=0,minIndex=-1;else{let polygonIndexes=topy2polygonIndexes.get(miny);polygonIndexes||(polygonIndexes=[],topy2polygonIndexes.set(miny,polygonIndexes)),polygonIndexes.push(polygonIndex)}}vertices2d.reverse(),minIndex=numVertices-minIndex-1,polygonVertices2d.push(vertices2d),polygonTopVertexIndexes.push(minIndex)}const yCoordinates=[];yCoordinateToPolygonIndexes.forEach(((polylist,y)=>yCoordinates.push(y))),yCoordinates.sort(fnNumberSort);let activePolygons=[],prevOutPolygonRow=[];for(let yIndex=0;yIndex=numVertices&&(nextLeftVertexIndex=0),vertices2d[nextLeftVertexIndex][1]!==yCoordinate)break;newLeftVertexIndex=nextLeftVertexIndex}let nextRightVertexIndex=newRightVertexIndex-1;if(nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),vertices2d[nextRightVertexIndex][1]===yCoordinate&&(newRightVertexIndex=nextRightVertexIndex),newLeftVertexIndex!==activePolygon.leftVertexIndex&&newLeftVertexIndex===newRightVertexIndex)activePolygons.splice(activePolygonIndex,1),--activePolygonIndex;else{activePolygon.leftVertexIndex=newLeftVertexIndex,activePolygon.rightVertexIndex=newRightVertexIndex,activePolygon.topLeft=vertices2d[newLeftVertexIndex],activePolygon.topRight=vertices2d[newRightVertexIndex];let nextLeftVertexIndex=newLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0),activePolygon.bottomLeft=vertices2d[nextLeftVertexIndex];let nextRightVertexIndex=newRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),activePolygon.bottomRight=vertices2d[nextRightVertexIndex]}}}let nextYcoordinate;if(yIndex>=yCoordinates.length-1)activePolygons=[],nextYcoordinate=null;else{nextYcoordinate=Number(yCoordinates[yIndex+1]);const middleYcoordinate=.5*(yCoordinate+nextYcoordinate),startingPolygonIndexes=topy2polygonIndexes.get(yCoordinate);for(const polygonIndexKey in startingPolygonIndexes){const polygonIndex=startingPolygonIndexes[polygonIndexKey],vertices2d=polygonVertices2d[polygonIndex],numVertices=vertices2d.length,topVertexIndex=polygonTopVertexIndexes[polygonIndex];let topLeftVertexIndex=topVertexIndex;for(;;){let i=topLeftVertexIndex+1;if(i>=numVertices&&(i=0),vertices2d[i][1]!==yCoordinate)break;if(i===topVertexIndex)break;topLeftVertexIndex=i}let topRightVertexIndex=topVertexIndex;for(;;){let i=topRightVertexIndex-1;if(i<0&&(i=numVertices-1),vertices2d[i][1]!==yCoordinate)break;if(i===topLeftVertexIndex)break;topRightVertexIndex=i}let nextLeftVertexIndex=topLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0);let nextRightVertexIndex=topRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1);const newActivePolygon={polygonIndex:polygonIndex,leftVertexIndex:topLeftVertexIndex,rightVertexIndex:topRightVertexIndex,topLeft:vertices2d[topLeftVertexIndex],topRight:vertices2d[topRightVertexIndex],bottomLeft:vertices2d[nextLeftVertexIndex],bottomRight:vertices2d[nextRightVertexIndex]};insertSorted(activePolygons,newActivePolygon,((el1,el2)=>{const x1=interpolateBetween2DPointsForY(el1.topLeft,el1.bottomLeft,middleYcoordinate),x2=interpolateBetween2DPointsForY(el2.topLeft,el2.bottomLeft,middleYcoordinate);return x1>x2?1:x10){const prevOutPolygon=newOutPolygonRow[newOutPolygonRow.length-1],d1=distance(outPolygon.topLeft,prevOutPolygon.topRight),d2=distance(outPolygon.bottomLeft,prevOutPolygon.bottomRight);d10){const prevContinuedIndexes=new Set,matchedIndexes=new Set;for(let i=0;i=0)&&(rightLineContinues||d2>=0)&&(thisPolygon.outPolygon=prevPolygon.outPolygon,thisPolygon.leftLineContinues=leftLineContinues,thisPolygon.rightLineContinues=rightLineContinues,prevContinuedIndexes.add(ii));break}}}for(let ii=0;iiEPS&&prevPolygon.outPolygon.leftPoints.push(prevPolygon.bottomLeft),prevPolygon.outPolygon.leftPoints.reverse();const vertices3d=prevPolygon.outPolygon.rightPoints.concat(prevPolygon.outPolygon.leftPoints).map((point2d=>orthonormalFormula.to3D(point2d))),polygon=fromVerticesAndPlane(vertices3d,plane$1);polygon.vertices.length&&destPolygons.push(polygon)}}for(let i=0;iEPS&&thisPolygon.outPolygon.rightPoints.push(thisPolygon.topRight))}prevOutPolygonRow=newOutPolygonRow}return destPolygons})(group);destPolygons.push(...reTessellateCoplanarPolygons)}else destPolygons.push(group)}));const result=create$8(destPolygons);return result.isRetesselated=!0,result})(newGeometry),newGeometry},subtract=(...geometries)=>{if(0===(arr=geometries,geometries=flattenHelper(arr,[])).length)return;var arr;if(!(shapes=>{let previousType;for(const shape of shapes){let currentType=0;if(isA$5(shape)&&(currentType=1),isA$3(shape)&&(currentType=2),isA$2(shape)&&(currentType=3),previousType&¤tType!==previousType)return!1;previousType=currentType}return!0})(geometries))throw new Error("subtract arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return(geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,2)})),newGeometry})(geometries);if(isA$3(geometry))return subtractGeom3(geometries);throw new Error("subtract unsupported geometry type")},transform=(matrix,...objects)=>{const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?transform(matrix,...object):object));return 1===results.length?results[0]:results},createTransform=(center,rotation,scale,scaleOrientation,translation)=>{const matrix=index$c.create(),temp=index$c.create();return index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,translation)),index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,center)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,rotation[3],rotation)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,scaleOrientation[3],scaleOrientation)),index$c.multiply(matrix,matrix,index$c.fromScaling(temp,scale)),index$c.multiply(matrix,matrix,index$c.fromRotation(temp,scaleOrientation[3],index$d.negate(index$d.create(),scaleOrientation))),index$c.multiply(matrix,matrix,index$c.fromTranslation(temp,index$d.negate(index$d.create(),center))),matrix},x3dTypes_X3D=0,x3dTypes_UNIT=1,x3dTypes_META=2,x3dTypes_SCENE=3,x3dTypes_TRANSFORM=4,x3dTypes_SHAPE=5,x3dTypes_GROUP=6,x3dTypes_APPEARANCE=7,x3dTypes_TRIANGLESET=10,x3dTypes_TRIANGLEFANSET=11,x3dTypes_TRIANGLESTRIPSET=12,x3dTypes_QUADSET=13,x3dTypes_INDEXEDTRIANGLESET=14,x3dTypes_INDEXEDTRIANGLEFANSET=15,x3dTypes_INDEXEDTRIANGLESTRIPSET=16,x3dTypes_INDEXEDQUADSET=17,x3dTypes_ELEVATIONGRID=18,x3dTypes_INDEXEDFACESET=19,x3dTypes_LINESET=20,x3dTypes_INDEXEDLINESET=21,x3dTypes_BOX=50,x3dTypes_CONE=51,x3dTypes_CYLINDER=52,x3dTypes_SPHERE=53,x3dTypes_EXTRUSION=54,x3dTypes_ARC2D=61,x3dTypes_ARCCLOSE2D=62,x3dTypes_CIRCLE2D=63,x3dTypes_DISK2D=64,x3dTypes_POLYLINE2D=65,x3dTypes_RECTANGLE2D=66,x3dTypes_TRIANGLESET2D=67,x3dTypes_COLOR=91,x3dTypes_COORDINATE=92,x3dTypes_MATERIAL=93,x3dGroup=element=>{const obj={definition:x3dTypes_GROUP,objects:[]};return obj},parseNumbers=attribute=>attribute.trim().replace(/,/g," ").split(/ +/).map((v=>parseFloat(v))),parseIndices=attribute=>attribute.replace(/,/g," ").trim().split(/ -1/).map((index=>parseNumbers(index))),isZeroVector=vector=>vector[0]+0===0&&vector[1]+0===0&&vector[2]+0===0,calculateZaxis=(z,p,i,n)=>{const a=index$d.subtract(index$d.create(),n,i),b=index$d.subtract(index$d.create(),p,i);return index$d.normalize(z,index$d.cross(z,a,b))},extrudeX3D=x3dshape=>{let{beginCap:beginCap,endCap:endCap,crossSection:crossSection,orientations:orientations,scales:scales,spine:spine}=Object.assign({},x3dshape);if(index$3.measureArea(index$3.create(crossSection))<0&&crossSection.reverse(),1===scales.length&&(scales=spine.map((s=>scales[0]))),1===orientations.length&&(orientations=spine.map((s=>orientations[0]))),spine.length!==scales.length||spine.length!==orientations.length)throw new Error(`invalid X3D specification; spine scale orientaion length must be the same; ${spine.length}`);const initialShape=index$a.create([crossSection]),initialSlice=index$2.fromGeom2(initialShape);let yaxes=(spine=>{const slength=spine.length,closed=index$d.equals(spine[0],spine[slength-1]),yaxes=[];for(let i=0;i{const slength=spine.length,closed=index$d.equals(spine[0],spine[slength-1]),zaxes=[];let previousZaxis;for(let i=0;i2&&calculateZaxis(zaxis,spine[0],spine[1],spine[2]):i===slength-1?closed?calculateZaxis(zaxis,spine[slength-2],spine[0],spine[1]):slength>2&&calculateZaxis(zaxis,spine[slength-3],spine[slength-2],spine[slength-1]):calculateZaxis(zaxis,spine[i-1],spine[i],spine[i+1]),previousZaxis&&index$d.dot(previousZaxis,zaxis)<0&&index$d.negate(zaxis,zaxis),zaxes.push(zaxis),previousZaxis=zaxis}if(isZeroVector(zaxes[0]))for(let i=1;i{const xaxes=[];for(let i=0;iacc&&isZeroVector(axis)),!0)&&(index$d.subtract(y0direction,spine[1],spine[0]),index$c.fromVectorRotation(y0matrix,index$d.fromValues(0,0,1),y0direction),xaxes=xaxes.map((axis=>[1,0,0])),yaxes=yaxes.map((axis=>[0,1,0])),zaxes=zaxes.map((axis=>[0,0,1]))),((options,base)=>{const defaults={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,callback:defaultCallback},{numberOfSlices:numberOfSlices,capStart:capStart,capEnd:capEnd,close:close,callback:generate}=Object.assign({},defaults,options);if(numberOfSlices<2)throw new Error("numberOfSlices must be 2 or more");const sMax=numberOfSlices-1;let startSlice=null,endSlice=null,prevSlice=null,polygons=[];for(let s=0;s(out[0]=xaxis[0],out[1]=yaxis[0],out[2]=zaxis[0],out[3]=0,out[4]=xaxis[1],out[5]=yaxis[1],out[6]=zaxis[1],out[7]=0,out[8]=xaxis[2],out[9]=yaxis[2],out[10]=zaxis[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out))(index$c.create(),xaxis,yaxis,zaxis),orientationMatrix=index$c.fromRotation(index$c.create(),orientation[3],orientation),rotationMatrix=index$c.create();index$c.multiply(rotationMatrix,y0matrix,rotationMatrix),index$c.multiply(rotationMatrix,scpMatrix,rotationMatrix),index$c.multiply(rotationMatrix,orientationMatrix,rotationMatrix),index$c.multiply(rotationMatrix,translationMatrix,rotationMatrix);let newslice=base;return newslice=index$2.transform(scaleMatrix,newslice),newslice=index$2.transform(rotationMatrix,newslice),newslice}},initialSlice)},findNode=(x3dtype,objects)=>objects.find((object=>object.definition===x3dtype)),findColor=(objects,options)=>{const appearance=findNode(x3dTypes_APPEARANCE,objects);let material;return appearance&&(material=findNode(x3dTypes_MATERIAL,appearance.objects),material)?material.color?material.color:null:(material=findNode(x3dTypes_MATERIAL,objects),material&&material.color?material.color:null)},pointsToString=triangle=>`[\n ${triangle.map((point=>(point=>`[${point}]`)(point))).join(",\n ")}\n ]`,createColors=(shape,color)=>{if(!color)return null;if(!Array.isArray(shape.colorIndex))return null;let colors=null;var colorIndex,faceColors;return!0===shape.colorPerVertex?colors=((colorIndex,vertexColors)=>{if(!Array.isArray(colorIndex)||!Array.isArray(vertexColors))return null;if(colorIndex.length<0||!Array.isArray(colorIndex[0]))return console.log("ERROR: WRONG FORMAT FOR VERTEXCOLORS"),null;const colors=[];for(let i=0;ifaceColors[index]?faceColors[index]:null)):null),colors},convertLine=(options,objects)=>{let shape=findNode(x3dTypes_INDEXEDLINESET,objects);if(shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),indexes=shape.indexes,color=findNode(x3dTypes_COLOR,shape.objects);if(coordinate&&indexes){const pointsSet=indexes.map((index=>{let points=index.map((i=>coordinate.points[i]));return points.findIndex((p=>0!==p[2]))>=0&&(console.warn("WARNING: unsupported 3D indexed line set was ignored"),points=[]),points}));return!0===shape.colorPerVertex?shape.colorIndex=indexes:shape.colorIndex=indexes.map(((index,i)=>i)),{pointsSet:pointsSet,colors:createColors(shape,color)}}}if(shape=findNode(x3dTypes_LINESET,objects),shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),color=findNode(x3dTypes_COLOR,shape.objects),counts=shape.vertexCount;if(coordinate&&counts){let vi=0;const pointsSet=counts.map((count=>{let points=[];for(let i=0;i0!==p[2]))>=0&&(console.warn("WARNING: unsupported 3D line set was ignored"),points=[]),points}));if(!0===shape.colorPerVertex){let ci=0;shape.colorIndex=counts.map((count=>{const index=[];for(let i=0;ii));return{pointsSet:pointsSet,colors:createColors(shape,color)}}}return null},convertMesh=(options,objects)=>{let shape=findNode(x3dTypes_TRIANGLESET,objects);if(shape){const coordinate=findNode(x3dTypes_COORDINATE,shape.objects),color=findNode(x3dTypes_COLOR,shape.objects);if(coordinate){const points=coordinate.points,numpoints=points.length,numfaces=Math.trunc(numpoints/3),faces=[];for(let ti=0;ti2){const points=coordinate.points,numfaces=Math.trunc(index.length/3),faces=[];for(let fi=0;fi0){const points=coordinate.points,numfans=fans.length,faces=[];for(let fi=0;fi0){const points=coordinate.points,numstrips=strips.length,faces=[];for(let si=0;si3){const points=coordinate.points,numquads=Math.trunc(index.length/4),faces=[];for(let qi=0;qi0){const points=coordinate.points;return{type:`indexed faces (${faces.length})`,points:points,faces:faces,colors:createColors(shape,color),orientation:shape.ccw?"outward":"inward"}}}if(shape=findNode(x3dTypes_ELEVATIONGRID,objects),shape){const height=shape.height,color=findNode(x3dTypes_COLOR,shape.objects);if(height&&height.length>0){const xDimension=shape.xDimension,xSpacing=shape.xSpacing,zDimension=shape.zDimension,zSpacing=shape.zSpacing,points=[];let vi=0;for(let z0=0;z0=distances[0]&&distances[1]>=distances[2]&&distances[1]>=distances[3]&&(apexi=1),distances[2]>=distances[0]&&distances[2]>=distances[1]&&distances[2]>=distances[3]&&(apexi=2),distances[3]>=distances[0]&&distances[3]>=distances[1]&&distances[3]>=distances[2]&&(apexi=3),0===apexi&&faces.push([iTL,iBR,iTR],[iTL,iBL,iBR]),1===apexi&&faces.push([iTR,iBL,iBR],[iTR,iTL,iBL]),2===apexi&&faces.push([iBL,iTR,iTL],[iBL,iBR,iTR]),3===apexi&&faces.push([iBR,iTL,iBL],[iBR,iTR,iTL])}const orientation=shape.ccw?"outward":"inward";return!0===shape.colorPerVertex&&(shape.colorIndex=faces),{type:`elevation grid (${xDimension} X ${zDimension})`,points:points,faces:faces,colors:createColors(shape,color),orientation:orientation}}}return null},instantiateMesh=(options,objects)=>{let geometry;const components=convertMesh(0,objects);return components&&(geometry=(options=>{const{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)})(components)),geometry},translateMesh=(options,objects)=>{const components=convertMesh(0,objects);if(components){const{type:type,points:points,faces:faces,colors:colors,orientation:orientation}=components;return((type,points,faces,colors,orientation)=>{const colorsCode=Array.isArray(colors)?pointsToString(colors):"null";return{primitive:"polyhedron({points, faces, colors, orientation})",code:`\n // 3D ${type} set: ${points.length} points, ${faces.length} faces\n const points = ${pointsToString(points)}\n const faces = ${pointsToString(faces)}\n const colors = ${colorsCode}\n const orientation = '${orientation}'\n`}})(type,points,faces,colors,orientation)}return null},translateShape=(options,object)=>{let code=`\n// shape\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects,color=findColor(objects);let primitive,shape=findNode(x3dTypes_BOX,objects);if(shape)primitive=`cuboid({size: [${shape.size}]})`;else if(shape=findNode(x3dTypes_CONE,objects),shape)code+=` const shape = rotateX(-Math.PI/2, cylinderElliptic({startRadius: [${shape.bottomRadius},${shape.bottomRadius}], height: ${shape.height}, segments: ${shape.subdivision}, endRadius: [${shape.topRadius}, ${shape.topRadius}]}))\n`,primitive="shape";else if(shape=findNode(x3dTypes_CYLINDER,objects),shape)code+=` const shape = rotateX(-Math.PI/2, cylinder({radius: ${shape.radius}, height: ${shape.height}, segments: ${shape.subdivision}}))\n`,primitive="shape";else if(shape=findNode(x3dTypes_SPHERE,objects),shape)primitive=`sphere({radius: ${shape.radius}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_EXTRUSION,objects),shape){const geometry=extrudeX3D(shape);code+=` const polygons = [\n ${index$6.toPolygons(geometry).map((polygon=>pointsToString(index$7.toVertices(polygon)))).join(",\n ")}\n]\n`,primitive="geom3.fromPoints(polygons)"}if(!primitive)if(shape=findNode(x3dTypes_ARC2D,objects),shape)primitive=`arc({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_ARCCLOSE2D,objects),shape)primitive="PIE"===shape.closureType?`circle({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})`:`geom2.create([path2.toPoints(path2.close(arc({radius: ${shape.radius}, startAngle: ${shape.startAngle}, endAngle: ${shape.endAngle}, segments: ${shape.subdivision}})))])`;else if(shape=findNode(x3dTypes_CIRCLE2D,objects),shape)primitive=`arc({radius: ${shape.radius}, segments: ${shape.subdivision}})`;else if(shape=findNode(x3dTypes_DISK2D,objects),shape)primitive=shape.innerRadius===shape.outerRadius?`arc({radius: ${shape.outerRadius}, segments: ${shape.subdivision}})`:0===shape.innerRadius?`circle({radius: ${shape.outerRadius}, segments: ${shape.subdivision}})`:`subtract(circle({radius: ${shape.outerRadius}, segments: ${shape.subdivision}}), primitives.circle({radius: ${shape.innerRadius}, segments: ${shape.subdivision}}))`;else if(shape=findNode(x3dTypes_POLYLINE2D,objects),shape)primitive=`line([[${shape.lineSegments.join("], [")}]])`;else if(shape=findNode(x3dTypes_RECTANGLE2D,objects),shape)primitive=`rectangle({size: [${shape.size}]})`;else if(shape=findNode(x3dTypes_TRIANGLESET2D,objects),shape){const numpoints=shape.vertices.length,numfaces=Math.trunc(numpoints/3);code+=`\n // 2D triangle set: ${numpoints} points, ${numfaces} faces\n const vertices = ${pointsToString(shape.vertices)}\n const triangles = []\n for (let i = 0; i < ${numfaces}; i = i + 3) {\n triangles.push(geom2.create([[vertices[i], vertices[i + 1], vertices[i + 2]]]))\n }\n`,primitive="triangles"}let results=translateMesh(0,objects);return results&&(primitive=results.primitive,code+=results.code),results=((options,objects)=>{const components=convertLine(0,objects);if(components){const{pointsSet:pointsSet,colors:colors}=components;let code=" let lines = []\n";return pointsSet.forEach(((points,i)=>{if(colors){const lineColor=colors[i];code+=` const line${i} = colorize([${lineColor}], primitives.line(${pointsToString(points)}))\n lines.push(line${i})\n`}else code+=` const line${i} = primitives.line(${pointsToString(points)})\n lines.push(line${i})\n`})),{primitive:"...lines",code:code}}return null})(0,objects),results&&(primitive=results.primitive,code+=results.code),primitive&&(code+=color?` objects.push(colorize([${color}], ${primitive}))`:` objects.push(${primitive})`),code+="\n return objects\n}\n",code},translatedList=[],translateDefinition=(options,object)=>{if(translatedList.includes(object.id))return"";translatedList.push(object.id);let code="";switch(object.definition){case x3dTypes_TRANSFORM:code+=((options,object)=>{let code=`\n// transform\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects;for(let i=0;i{let code=`\n// group\nconst createObjects${object.id} = (options) => {\n let objects = []\n`;const objects=object.objects;for(let i=0;iobjects.reduce(((code,object,index)=>code+translateDefinition(options,object)),"");var saxes={},ed5$1={};!function(exports){function isNameStartChar(c){return c>=65&&c<=90||c>=97&&c<=122||58===c||95===c||8204===c||8205===c||c>=192&&c<=214||c>=216&&c<=246||c>=248&&c<=767||c>=880&&c<=893||c>=895&&c<=8191||c>=8304&&c<=8591||c>=11264&&c<=12271||c>=12289&&c<=55295||c>=63744&&c<=64975||c>=65008&&c<=65533||c>=65536&&c<=983039} /** * Character classes and associated utilities for the 5th edition of XML 1.0. * @@ -35,4 +34,4 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.CHAR="-퟿- * @license MIT * @copyright Louis-Dominique Dubeau */ -Object.defineProperty(exports,"__esModule",{value:!0}),exports.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",exports.NC_NAME_CHAR="-"+exports.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",exports.NC_NAME_START_CHAR_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]$","u"),exports.NC_NAME_CHAR_RE=new RegExp("^["+exports.NC_NAME_CHAR+"]$","u"),exports.NC_NAME_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]["+exports.NC_NAME_CHAR+"]*$","u"),exports.isNCNameStartChar=isNCNameStartChar,exports.isNCNameChar=function(c){return isNCNameStartChar(c)||45===c||46===c||c>=48&&c<=57||183===c||c>=768&&c<=879||c>=8255&&c<=8256}}(ed3),Object.defineProperty(saxes,"__esModule",{value:!0});var SaxesParser_1=saxes.SaxesParser=saxes.EVENTS=void 0,isS=ed5$1.isS,isChar10=ed5$1.isChar,isNameStartChar=ed5$1.isNameStartChar,isNameChar=ed5$1.isNameChar,S_LIST=ed5$1.S_LIST,NAME_RE=ed5$1.NAME_RE,isChar11=ed2$1.isChar,isNCNameStartChar=ed3.isNCNameStartChar,isNCNameChar=ed3.isNCNameChar,NC_NAME_RE=ed3.NC_NAME_RE;const XML_NAMESPACE="http://www.w3.org/XML/1998/namespace",XMLNS_NAMESPACE="http://www.w3.org/2000/xmlns/",rootNS={__proto__:null,xml:XML_NAMESPACE,xmlns:XMLNS_NAMESPACE},XML_ENTITIES={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},isQuote=c=>34===c||39===c,QUOTES=[34,39],DOCTYPE_TERMINATOR=[...QUOTES,91,62],DTD_TERMINATOR=[...QUOTES,60,93],XML_DECL_NAME_TERMINATOR=[61,63,...S_LIST],ATTRIB_VALUE_UNQUOTED_TERMINATOR=[...S_LIST,62,38,60];function nsPairCheck(parser,prefix,uri){switch(prefix){case"xml":uri!==XML_NAMESPACE&&parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);break;case"xmlns":uri!==XMLNS_NAMESPACE&&parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`)}switch(uri){case XMLNS_NAMESPACE:parser.fail(""===prefix?`the default namespace may not be set to ${uri}.`:`may not assign a prefix (even "xmlns") to the URI ${XMLNS_NAMESPACE}.`);break;case XML_NAMESPACE:switch(prefix){case"xml":break;case"":parser.fail(`the default namespace may not be set to ${uri}.`);break;default:parser.fail("may not assign the xml namespace to another prefix.")}}}const isNCName=name=>NC_NAME_RE.test(name),isName=name=>NAME_RE.test(name);saxes.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];const EVENT_NAME_TO_HANDLER_NAME={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};SaxesParser_1=saxes.SaxesParser=class{constructor(opt){this.opt=null!=opt?opt:{},this.fragmentOpt=!!this.opt.fragment;const xmlnsOpt=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=!1!==this.opt.position,this.fileName=this.opt.fileName,xmlnsOpt){this.nameStartCheck=isNCNameStartChar,this.nameCheck=isNCNameChar,this.isName=isNCName,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},rootNS);const additional=this.opt.additionalNamespaces;null!=additional&&(function(parser,mapping){for(const local of Object.keys(mapping))nsPairCheck(parser,local,mapping[local])}(this,additional),Object.assign(this.ns,additional))}else this.nameStartCheck=isNameStartChar,this.nameCheck=isNameChar,this.isName=isName,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var _a;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=0,this.attribList=[];const{fragmentOpt:fragmentOpt}=this;this.state=fragmentOpt?13:0,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=fragmentOpt,this.xmlDeclPossible=!fragmentOpt,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:defaultXMLVersion}=this.opt;if(void 0===defaultXMLVersion){if(!0===this.opt.forceXMLVersion)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");defaultXMLVersion="1.0"}this.setXMLVersion(defaultXMLVersion),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(XML_ENTITIES),null===(_a=this.readyHandler)||void 0===_a||_a.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(name,handler){this[EVENT_NAME_TO_HANDLER_NAME[name]]=handler}off(name){this[EVENT_NAME_TO_HANDLER_NAME[name]]=void 0}makeError(message){var _a;let msg=null!==(_a=this.fileName)&&void 0!==_a?_a:"";return this.trackPosition&&(msg.length>0&&(msg+=":"),msg+=`${this.line}:${this.column}`),msg.length>0&&(msg+=": "),new Error(msg+message)}fail(message){const err=this.makeError(message),handler=this.errorHandler;if(void 0===handler)throw err;return handler(err),this}write(chunk){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let end=!1;null===chunk?(end=!0,chunk=""):"object"==typeof chunk&&(chunk=chunk.toString()),void 0!==this.carriedFromPrevious&&(chunk=`${this.carriedFromPrevious}${chunk}`,this.carriedFromPrevious=void 0);let limit=chunk.length;const lastCode=chunk.charCodeAt(limit-1);!end&&(13===lastCode||lastCode>=55296&&lastCode<=56319)&&(this.carriedFromPrevious=chunk[limit-1],limit--,chunk=chunk.slice(0,limit));const{stateTable:stateTable}=this;for(this.chunk=chunk,this.i=0;this.i=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>=32||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:return 10===chunk.charCodeAt(i+1)&&(this.i=i+2),this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCode11(){const{chunk:chunk,i:i}=this;if(this.prevI=i,this.i=i+1,i>=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>31&&code<127||code>159&&8232!==code||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:{const next=chunk.charCodeAt(i+1);10!==next&&133!==next||(this.i=i+2)}case 133:case 8232:return this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCodeNorm(){const c=this.getCode();return-2===c?10:c}unget(){this.i=this.prevI,this.column--}captureTo(chars){let{i:start}=this;const{chunk:chunk}=this;for(;;){const c=this.getCode(),isNLLike=-2===c,final=isNLLike?10:c;if(-1===final||chars.includes(final))return this.text+=chunk.slice(start,this.prevI),final;isNLLike&&(this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i)}}captureToChar(char){let{i:start}=this;const{chunk:chunk}=this;for(;;){let c=this.getCode();switch(c){case-2:this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i,c=10;break;case-1:return this.text+=chunk.slice(start),!1}if(c===char)return this.text+=chunk.slice(start,this.prevI),!0}}captureNameChars(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCode();if(-1===c)return this.name+=chunk.slice(start),-1;if(!isNameChar(c))return this.name+=chunk.slice(start,this.prevI),-2===c?10:c}}skipSpaces(){for(;;){const c=this.getCodeNorm();if(-1===c||!isS(c))return c}}setXMLVersion(version){this.currentXMLVersion=version,"1.0"===version?(this.isChar=isChar10,this.getCode=this.getCode10):(this.isChar=isChar11,this.getCode=this.getCode11)}sBegin(){65279===this.chunk.charCodeAt(0)&&(this.i++,this.column++),this.state=1}sBeginWhitespace(){const iBefore=this.i,c=this.skipSpaces();switch(this.prevI!==iBefore&&(this.xmlDeclPossible=!1),c){case 60:if(this.state=15,0!==this.text.length)throw new Error("no-empty text at start");break;case-1:break;default:this.unget(),this.state=13,this.xmlDeclPossible=!1}}sDoctype(){var _a;const c=this.captureTo(DOCTYPE_TERMINATOR);switch(c){case 62:null===(_a=this.doctypeHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13,this.doctype=!0;break;case-1:break;default:this.text+=String.fromCodePoint(c),91===c?this.state=4:isQuote(c)&&(this.state=3,this.q=c)}}sDoctypeQuote(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.q=null,this.state=2)}sDTD(){const c=this.captureTo(DTD_TERMINATOR);-1!==c&&(this.text+=String.fromCodePoint(c),93===c?this.state=2:60===c?this.state=6:isQuote(c)&&(this.state=5,this.q=c))}sDTDQuoted(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.state=4,this.q=null)}sDTDOpenWaka(){const c=this.getCodeNorm();switch(this.text+=String.fromCodePoint(c),c){case 33:this.state=7,this.openWakaBang="";break;case 63:this.state=11;break;default:this.state=4}}sDTDOpenWakaBang(){const char=String.fromCodePoint(this.getCodeNorm()),owb=this.openWakaBang+=char;this.text+=char,"-"!==owb&&(this.state="--"===owb?8:4,this.openWakaBang="")}sDTDComment(){this.captureToChar(45)&&(this.text+="-",this.state=9)}sDTDCommentEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),this.state=45===c?10:8}sDTDCommentEnded(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c?this.state=4:(this.fail("malformed comment."),this.state=8)}sDTDPI(){this.captureToChar(63)&&(this.text+="?",this.state=12)}sDTDPIEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c&&(this.state=4)}sText(){0!==this.tags.length?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:start}=this;const{chunk:chunk}=this;loop:for(;;)switch(this.getCode()){case-2:this.entity+=`${chunk.slice(start,this.prevI)}\n`,start=this.i;break;case 59:{const{entityReturnState:entityReturnState}=this,entity=this.entity+chunk.slice(start,this.prevI);let parsed;this.state=entityReturnState,""===entity?(this.fail("empty entity name."),parsed="&;"):(parsed=this.parseEntity(entity),this.entity=""),13===entityReturnState&&void 0===this.textHandler||(this.text+=parsed);break loop}case-1:this.entity+=chunk.slice(start);break loop}}sOpenWaka(){const c=this.getCode();if(isNameStartChar(c))this.state=34,this.unget(),this.xmlDeclPossible=!1;else switch(c){case 47:this.state=43,this.xmlDeclPossible=!1;break;case 33:this.state=16,this.openWakaBang="",this.xmlDeclPossible=!1;break;case 63:this.state=23;break;default:this.fail("disallowed character in tag name"),this.state=13,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=20,this.openWakaBang="";break;case"--":this.state=17,this.openWakaBang="";break;case"DOCTYPE":this.state=2,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(45)&&(this.state=18)}sCommentEnding(){var _a;const c=this.getCodeNorm();45===c?(this.state=19,null===(_a=this.commentHandler)||void 0===_a||_a.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(c)}`,this.state=17)}sCommentEnded(){const c=this.getCodeNorm();62!==c?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(c)}`,this.state=17):this.state=13}sCData(){this.captureToChar(93)&&(this.state=21)}sCDataEnding(){const c=this.getCodeNorm();93===c?this.state=22:(this.text+=`]${String.fromCodePoint(c)}`,this.state=20)}sCDataEnding2(){var _a;const c=this.getCodeNorm();switch(c){case 62:null===(_a=this.cdataHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13;break;case 93:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(c)}`,this.state=20}}sPIFirstChar(){const c=this.getCodeNorm();this.nameStartCheck(c)?(this.piTarget+=String.fromCodePoint(c),this.state=24):63===c||isS(c)?(this.fail("processing instruction without a target."),this.state=63===c?26:25):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c),this.state=24)}sPIRest(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCodeNorm();if(-1===c)return void(this.piTarget+=chunk.slice(start));if(!this.nameCheck(c)){this.piTarget+=chunk.slice(start,this.prevI);const isQuestion=63===c;isQuestion||isS(c)?"xml"===this.piTarget?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=isQuestion?33:27):this.state=isQuestion?26:25:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c));break}}}sPIBody(){if(0===this.text.length){const c=this.getCodeNorm();63===c?this.state=26:isS(c)||(this.text=String.fromCodePoint(c))}else this.captureToChar(63)&&(this.state=26)}sPIEnding(){var _a;const c=this.getCodeNorm();if(62===c){const{piTarget:piTarget}=this;"xml"===piTarget.toLowerCase()&&this.fail("the XML declaration must appear at the start of the document."),null===(_a=this.piHandler)||void 0===_a||_a.call(this,{target:piTarget,body:this.text}),this.piTarget=this.text="",this.state=13}else 63===c?this.text+="?":(this.text+=`?${String.fromCodePoint(c)}`,this.state=25);this.xmlDeclPossible=!1}sXMLDeclNameStart(){const c=this.skipSpaces();63!==c?-1!==c&&(this.state=28,this.name=String.fromCodePoint(c)):this.state=33}sXMLDeclName(){const c=this.captureTo(XML_DECL_NAME_TERMINATOR);if(63===c)return this.state=33,this.name+=this.text,this.text="",void this.fail("XML declaration is incomplete.");if(isS(c)||61===c){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=61===c?30:29}}sXMLDeclEq(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(61!==c&&this.fail("value required."),this.state=30)}sXMLDeclValueStart(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(isQuote(c)?this.q=c:(this.fail("value must be quoted."),this.q=32),this.state=31)}sXMLDeclValue(){const c=this.captureTo([this.q,63]);if(63===c)return this.state=33,this.text="",void this.fail("XML declaration is incomplete.");if(-1===c)return;const value=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];const version=value;this.xmlDecl.version=version,/^1\.[0-9]+$/.test(version)?this.opt.forceXMLVersion||this.setXMLVersion(version):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=value;break;case"standalone":"yes"!==value&&"no"!==value&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=value}this.name="",this.state=32}sXMLDeclSeparator(){const c=this.getCodeNorm();63!==c?(isS(c)||(this.fail("whitespace required."),this.unget()),this.state=27):this.state=33}sXMLDeclEnding(){var _a;62===this.getCodeNorm()?("xml"!==this.piTarget?this.fail("processing instructions are not allowed before root."):"version"!==this.name&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),null===(_a=this.xmldeclHandler)||void 0===_a||_a.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=13):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var _a;const c=this.captureNameChars();if(-1===c)return;const tag=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=tag.ns=Object.create(null)),null===(_a=this.openTagStartHandler)||void 0===_a||_a.call(this,tag),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),c){case 62:this.openTag();break;case 47:this.state=35;break;default:isS(c)||this.fail("disallowed character in tag name."),this.state=36}}sOpenTagSlash(){62===this.getCode()?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=36)}sAttrib(){const c=this.skipSpaces();-1!==c&&(isNameStartChar(c)?(this.unget(),this.state=37):62===c?this.openTag():47===c?this.state=35:this.fail("disallowed character in attribute name."))}sAttribName(){const c=this.captureNameChars();61===c?this.state=39:isS(c)?this.state=38:62===c?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):-1!==c&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){const c=this.skipSpaces();switch(c){case-1:return;case 61:this.state=39;break;default:this.fail("attribute without value."),this.text="",this.name="",62===c?this.openTag():isNameStartChar(c)?(this.unget(),this.state=37):(this.fail("disallowed character in attribute name."),this.state=36)}}sAttribValue(){const c=this.getCodeNorm();isQuote(c)?(this.q=c,this.state=40):isS(c)||(this.fail("unquoted attribute value."),this.state=42,this.unget())}sAttribValueQuoted(){const{q:q,chunk:chunk}=this;let{i:start}=this;for(;;)switch(this.getCode()){case q:return this.pushAttrib(this.name,this.text+chunk.slice(start,this.prevI)),this.name=this.text="",this.q=null,void(this.state=41);case 38:return this.text+=chunk.slice(start,this.prevI),this.state=14,void(this.entityReturnState=40);case 10:case-2:case 9:this.text+=`${chunk.slice(start,this.prevI)} `,start=this.i;break;case 60:return this.text+=chunk.slice(start,this.prevI),void this.fail("disallowed character.");case-1:return void(this.text+=chunk.slice(start))}}sAttribValueClosed(){const c=this.getCodeNorm();isS(c)?this.state=36:62===c?this.openTag():47===c?this.state=35:isNameStartChar(c)?(this.fail("no whitespace between attributes."),this.unget(),this.state=37):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){const c=this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);switch(c){case 38:this.state=14,this.entityReturnState=42;break;case 60:this.fail("disallowed character.");break;case-1:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",62===c?this.openTag():this.state=36}}sCloseTag(){const c=this.captureNameChars();62===c?this.closeTag():isS(c)?this.state=44:-1!==c&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case 62:this.closeTag();break;case-1:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:start,forbiddenState:forbiddenState}=this;const{chunk:chunk,textHandler:handler}=this;scanLoop:for(;;)switch(this.getCode()){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}forbiddenState=0;break scanLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),forbiddenState=0;break scanLoop;case 93:switch(forbiddenState){case 0:forbiddenState=1;break;case 1:forbiddenState=2;break;case 2:break;default:throw new Error("impossible state")}break;case 62:2===forbiddenState&&this.fail('the string "]]>" is disallowed in char data.'),forbiddenState=0;break;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i,forbiddenState=0;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break scanLoop;default:forbiddenState=0}this.forbiddenState=forbiddenState}handleTextOutsideRoot(){let{i:start}=this;const{chunk:chunk,textHandler:handler}=this;let nonSpace=!1;outRootLoop:for(;;){const code=this.getCode();switch(code){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}break outRootLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),nonSpace=!0;break outRootLoop;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break outRootLoop;default:isS(code)||(nonSpace=!0)}}nonSpace&&(this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(name,value){var _a;const{prefix:prefix,local:local}=this.qname(name),attr={name:name,prefix:prefix,local:local,value:value};if(this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr),"xmlns"===prefix){const trimmed=value.trim();"1.0"===this.currentXMLVersion&&""===trimmed&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[local]=trimmed,nsPairCheck(this,local,trimmed)}else if("xmlns"===name){const trimmed=value.trim();this.topNS[""]=trimmed,nsPairCheck(this,"",trimmed)}}pushAttribPlain(name,value){var _a;const attr={name:name,value:value};this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr)}end(){var _a,_b;this.sawRoot||this.fail("document must contain a root element.");const{tags:tags}=this;for(;tags.length>0;){const tag=tags.pop();this.fail(`unclosed tag: ${tag.name}`)}0!==this.state&&13!==this.state&&this.fail("unexpected end.");const{text:text}=this;return 0!==text.length&&(null===(_a=this.textHandler)||void 0===_a||_a.call(this,text),this.text=""),this._closed=!0,null===(_b=this.endHandler)||void 0===_b||_b.call(this),this._init(),this}resolve(prefix){var _a,_b;let uri=this.topNS[prefix];if(void 0!==uri)return uri;const{tags:tags}=this;for(let index=tags.length-1;index>=0;index--)if(uri=tags[index].ns[prefix],void 0!==uri)return uri;return uri=this.ns[prefix],void 0!==uri?uri:null===(_b=(_a=this.opt).resolvePrefix)||void 0===_b?void 0:_b.call(_a,prefix)}qname(name){const colon=name.indexOf(":");if(-1===colon)return{prefix:"",local:name};const local=name.slice(colon+1),prefix=name.slice(0,colon);return(""===prefix||""===local||local.includes(":"))&&this.fail(`malformed name: ${name}.`),{prefix:prefix,local:local}}processAttribsNS(){var _a;const{attribList:attribList}=this,tag=this.tag;{const{prefix:prefix,local:local}=this.qname(tag.name);tag.prefix=prefix,tag.local=local;const uri=tag.uri=null!==(_a=this.resolve(prefix))&&void 0!==_a?_a:"";""!==prefix&&("xmlns"===prefix&&this.fail('tags may not have "xmlns" as prefix.'),""===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),tag.uri=prefix))}if(0===attribList.length)return;const{attributes:attributes}=tag,seen=new Set;for(const attr of attribList){const{name:name,prefix:prefix,local:local}=attr;let uri,eqname;""===prefix?(uri="xmlns"===name?XMLNS_NAMESPACE:"",eqname=name):(uri=this.resolve(prefix),void 0===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),uri=prefix),eqname=`{${uri}}${local}`),seen.has(eqname)&&this.fail(`duplicate attribute: ${eqname}.`),seen.add(eqname),attr.uri=uri,attributes[name]=attr}this.attribList=[]}processAttribsPlain(){const{attribList:attribList}=this,attributes=this.tag.attributes;for(const{name:name,value:value}of attribList)void 0!==attributes[name]&&this.fail(`duplicate attribute: ${name}.`),attributes[name]=value;this.attribList=[]}openTag(){var _a;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!1,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),tags.push(tag),this.state=13,this.name=""}openSelfClosingTag(){var _a,_b,_c;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!0,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),null===(_b=this.closeTagHandler)||void 0===_b||_b.call(this,tag),null===(this.tag=null!==(_c=tags[tags.length-1])&&void 0!==_c?_c:null)&&(this.closedRoot=!0),this.state=13,this.name=""}closeTag(){const{tags:tags,name:name}=this;if(this.state=13,this.name="",""===name)return this.fail("weird empty close tag."),void(this.text+="");const handler=this.closeTagHandler;let l=tags.length;for(;l-- >0;){const tag=this.tag=tags.pop();if(this.topNS=tag.ns,null==handler||handler(tag),tag.name===name)break;this.fail("unexpected close tag.")}0===l?this.closedRoot=!0:l<0&&(this.fail(`unmatched closing tag: ${name}.`),this.text+=``)}parseEntity(entity){if("#"!==entity[0]){const defined=this.ENTITIES[entity];return void 0!==defined?defined:(this.fail(this.isName(entity)?"undefined entity.":"disallowed character in entity name."),`&${entity};`)}let num=NaN;return"x"===entity[1]&&/^#x[0-9a-f]+$/i.test(entity)?num=parseInt(entity.slice(2),16):/^#[0-9]+$/.test(entity)&&(num=parseInt(entity.slice(1),10)),this.isChar(num)?String.fromCodePoint(num):(this.fail("malformed character entity."),`&${entity};`)}};let x3dLast=null,x3dDefinition=x3dTypes_X3D;const x3dObjects=[],x3dDefs=new Map,x3dMaterials=[],x3dTextures=[],x3dLength={factor:1,name:"meters"},x3dAngle={factor:1,name:"radians"};let x3dObj=null;const nodeToObjectMap={X3D:element=>{const obj={definition:x3dTypes_X3D,objects:[]};return obj},UNIT:element=>{const obj={definition:x3dTypes_UNIT,category:"",name:"",conversionFactor:1};return element.category&&(obj.category=element.category),element.name&&(obj.name=element.name),element.conversionfactor&&(obj.conversionFactor=element.conversionfactor),obj},META:element=>{const obj={definition:x3dTypes_META,content:"",name:""};return element.content&&(obj.content=element.content),element.name&&(obj.name=element.name),obj},SCENE:element=>{const obj={definition:x3dTypes_SCENE,objects:[]};return obj},TRANSFORM:element=>{const obj={definition:x3dTypes_TRANSFORM,center:[0,0,0],rotation:[0,0,1,0],scale:[1,1,1],scaleOrientation:[0,0,1,0],translation:[0,0,0]};if(element.center){const values=element.center.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(obj.center=values)}if(element.rotation){const values=element.rotation.trim().split(/ +/).map((v=>parseFloat(v)));values.length>3&&(obj.rotation=values)}if(element.scale){const values=element.scale.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(obj.scale=values)}if(element.scaleorientation){const values=element.scaleorientation.trim().split(/ +/).map((v=>parseFloat(v)));values.length>3&&(obj.scaleOrientation=values)}if(element.translation){const values=element.translation.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(obj.translation=values)}return obj.objects=[],obj},SHAPE:element=>{const obj={definition:x3dTypes_SHAPE,objects:[]};return obj},GROUP:x3dGroup,STATICGROUP:x3dGroup,BOX:element=>{const obj={definition:x3dTypes_BOX,size:[2,2,2]};if(element.size){const values=element.size.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(obj.size=values)}return obj},CONE:element=>{const obj={definition:x3dTypes_CONE,bottomRadius:1,height:2,subdivision:32,topRadius:1e-5};return element.bottomRadius&&(obj.bottomRadius=Math.max(parseFloat(element.bottomRadius),1e-5)),element.height&&(obj.height=parseFloat(element.height)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),element.topRadius&&(obj.topRadius=Math.max(parseFloat(element.topRadius),1e-5)),obj},CYLINDER:element=>{const obj={definition:x3dTypes_CYLINDER,height:2,radius:1,subdivision:32};return element.height&&(obj.height=parseFloat(element.height)),element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},SPHERE:element=>{const obj={definition:x3dTypes_SPHERE,radius:1,subdivision:24};if(element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision){const values=element.subdivision.trim().split(/ +/).map((v=>parseFloat(v)));values.length>1&&(obj.subdivision=Math.max(...values))}return obj},EXTRUSION:element=>{const obj={definition:x3dTypes_EXTRUSION,ccw:!0,beginCap:!0,endCap:!0,crossSection:[[1,1],[1,-1],[-1,-1],[-1,1],[1,1]],orientations:[[0,0,1,0]],scales:[[1,1]],spine:[[0,0,0],[0,1,0]]};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.beginCap&&(obj.beginCap=element.beginCap.includes("TRUE")||element.beginCap.includes("true")),element.endCap&&(obj.endCap=element.endCap.includes("TRUE")||element.endCap.includes("true")),element.crossSection){const values=element.crossSection.trim().split(/ +/).map((v=>parseFloat(v))),numpoints=Math.trunc(values.length/2),points=[];for(let i=0;iparseFloat(v))),numpoints=Math.trunc(values.length/4),points=[];for(let i=0;iparseFloat(v))),numpoints=Math.trunc(values.length/2),points=[];for(let i=0;iparseFloat(v))),numpoints=Math.trunc(values.length/3),points=[];for(let i=0;i{const obj={definition:x3dTypes_ARC2D,endAngle:Math.PI/2,radius:1,startAngle:0,subdivision:32};return element.endAngle&&(obj.endAngle=parseFloat(element.endAngle)),element.radius&&(obj.radius=parseFloat(element.radius)),element.startAngle&&(obj.startAngle=parseFloat(element.startAngle)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},ARCCLOSE2D:element=>{const obj={definition:x3dTypes_ARCCLOSE2D,closureType:"PIE",endAngle:Math.PI/2,radius:1,startAngle:0,subdivision:32};return element.closureType&&(obj.closureType=element.closureType),element.endAngle&&(obj.endAngle=parseFloat(element.endAngle)),element.radius&&(obj.radius=parseFloat(element.radius)),element.startAngle&&(obj.startAngle=parseFloat(element.startAngle)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},CIRCLE2D:element=>{const obj={definition:x3dTypes_CIRCLE2D,radius:1,subdivision:32};return element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},DISK2D:element=>{const obj={definition:x3dTypes_DISK2D,innerRadius:0,outerRadius:1,subdivision:32};return element.innerRadius&&(obj.innerRadius=parseFloat(element.innerRadius)),element.outerRadius&&(obj.outerRadius=parseFloat(element.outerRadius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},POLYLINE2D:element=>{const obj={definition:x3dTypes_POLYLINE2D,lineSegments:[]};if(element.lineSegments){const values=element.lineSegments.trim().split(/ +/).map((v=>parseFloat(v)));for(let i=0;i{const obj={definition:x3dTypes_RECTANGLE2D,size:[2,2]};if(element.size){const values=element.size.trim().split(/ +/).map((v=>parseFloat(v)));values.length>1&&(obj.size=values)}return obj},TRIANGLESET2D:element=>{const obj={definition:x3dTypes_TRIANGLESET2D,vertices:[]};if(element.vertices){const values=element.vertices.trim().split(/ +/).map((v=>parseFloat(v)));for(let i=0;i{const obj={definition:x3dTypes_COLOR,colors:[]};if(element.color){const values=element.color.trim().split(/ +/).map((v=>parseFloat(v))),numvalues=values.length,numcolors=Math.trunc(numvalues/3);for(let i=0;i{const obj={definition:x3dTypes_COORDINATE,points:[]};if(element.point){const values=element.point.trim().split(/ +/).map((v=>parseFloat(v))),numvalues=values.length,numpoints=Math.trunc(numvalues/3);for(let i=0;i{const obj={definition:x3dTypes_TRIANGLESET,ccw:!0,colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),obj.objects=[],obj},TRIANGLEFANSET:element=>{const obj={definition:x3dTypes_TRIANGLEFANSET,ccw:!0,fanCount:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.fanCount&&(obj.fanCount=element.fanCount.trim().split(/ +/).map((v=>parseFloat(v)))),obj.objects=[],obj},TRIANGLESTRIPSET:element=>{const obj={definition:x3dTypes_TRIANGLESTRIPSET,ccw:!0,stripCount:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.stripCount&&(obj.stripCount=element.stripCount.trim().split(/ +/).map((v=>parseFloat(v)))),obj.objects=[],obj},QUADSET:element=>{const obj={definition:x3dTypes_QUADSET,ccw:!0,colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),obj.objects=[],obj},INDEXEDTRIANGLESET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLESET,ccw:!0,index:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index&&(obj.index=element.index.trim().split(/ +/).map((v=>parseFloat(v)))),obj.objects=[],obj},INDEXEDTRIANGLEFANSET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLEFANSET,ccw:!0,fans:[],colorPerVertex:!0};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index){const indexes=element.index.trim().split(/ -1/);obj.fans=indexes.map((index=>index.trim().split(/ +/).map((v=>parseFloat(v))))).filter((index=>index.length>2))}return obj.objects=[],obj},INDEXEDTRIANGLESTRIPSET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLESTRIPSET,ccw:!0,strips:[],colorPerVertex:!0,objects:[]};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index){const indexes=element.index.trim().split(/ -1/);obj.strips=indexes.map((index=>index.trim().split(/ +/).map((v=>parseFloat(v))))).filter((index=>index.length>2))}return obj},INDEXEDQUADSET:element=>{const obj={definition:x3dTypes_INDEXEDQUADSET,ccw:!0,index:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index&&(obj.index=element.index.trim().split(/ +/).map((v=>parseFloat(v)))),obj.objects=[],obj},INDEXEDFACESET:element=>{const obj={definition:x3dTypes_INDEXEDFACESET,ccw:!0,convex:!0,faces:[],colorPerVertex:!0,colorIndex:null};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.convex&&(obj.convex=element.convex.includes("TRUE")||element.convex.includes("true")),element.coordIndex){const indexes=element.coordIndex.trim().split(/ -1/);obj.faces=indexes.map((index=>index.trim().split(/ +/).map((v=>parseFloat(v))))).filter((index=>index.length>2))}if(element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),element.colorIndex)if(obj.colorPerVertex){const indexes=element.colorIndex.trim().split(/ -1/);obj.colorIndex=indexes.map((index=>index.trim().split(/ +/).map((v=>parseFloat(v))))).filter((index=>index.length>2))}else obj.colorIndex=element.colorIndex.trim().split(/ +/).map((v=>parseFloat(v)));else obj.colorIndex=obj.faces;return obj.objects=[],obj},ELEVATIONGRID:element=>{const obj={definition:x3dTypes_ELEVATIONGRID,xDimension:2,zDimension:2,xSpacing:1,zSpacing:1,height:[0,0,0,0],ccw:!0,solid:!1,colorPerVertex:!0};return element.xDimension&&(obj.xDimension=parseFloat(element.xDimension)),element.zDimension&&(obj.zDimension=parseFloat(element.zDimension)),element.xSpacing&&(obj.xSpacing=parseFloat(element.xSpacing)),element.zSpacing&&(obj.zSpacing=parseFloat(element.zSpacing)),element.height&&(obj.height=element.height.trim().split(/ +/).map((v=>parseFloat(v)))),element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.solid&&(obj.solid=element.solid.includes("TRUE")||element.solid.includes("true")),element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},LINESET:element=>{const obj={definition:x3dTypes_LINESET,vertexCount:[],colorPerVertex:!0};return element.vertexCount&&(obj.vertexCount=element.vertexCount.trim().split(/ +/).map((v=>parseFloat(v)))),element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},INDEXEDLINESET:element=>{const obj={definition:x3dTypes_INDEXEDLINESET,indexes:[],colorPerVertex:!0};if(element.coordIndex){const indexes=element.coordIndex.trim().split(/ -1/);obj.indexes=indexes.map((index=>index.trim().split(/ +/).map((v=>parseFloat(v))))),obj.indexes=obj.indexes.filter((index=>index.length>1))}return element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},APPEARANCE:element=>{const obj={definition:x3dTypes_APPEARANCE,objects:[]};return obj},MATERIAL:element=>{const obj={definition:x3dTypes_MATERIAL,color:[.8,.8,.8,1]};let alpha=1;if(element.transparency&&(alpha=1-element.transparency),element.diffuseColor){const values=element.diffuseColor.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(values.length<4&&values.push(alpha),obj.color=values)}if(element.emissiveColor){const values=element.emissiveColor.trim().split(/ +/).map((v=>parseFloat(v)));values.length>2&&(values.length<4&&values.push(alpha),obj.color=values)}return obj}};let objectId=1;const createX3DParser=src=>{const parser=new SaxesParser_1;parser.on("error",(e=>{console.log(`error: line ${e.line}, column ${e.column}, bad character [${e.c}]`)})),parser.on("opentag",(node=>{const elementname=node.name.toUpperCase();let obj=nodeToObjectMap[elementname]?nodeToObjectMap[elementname](node.attributes,{x3dObjects:x3dObjects}):null;if(obj){if(obj.id=("0000"+objectId++).slice(-4),node.attributes.USE){const objectname=node.attributes.USE;if(x3dDefs.has(objectname)){const def=x3dDefs.get(objectname);def.definition!==obj.definition&&console.log(`WARNING: using a definition "${objectname}" of a different type; ${obj.definition} vs ${def.definition}`),obj=def}else console.log(`WARNING: definition "${objectname}" does not exist, using default for ${obj.definition}`)}else if(node.attributes.DEF){const objectname=node.attributes.DEF;x3dDefs.has(objectname)?console.log(`WARNING: redefintion of ${objectname} has been ignored`):x3dDefs.set(objectname,obj)}switch(obj.definition){case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:case x3dTypes_GROUP:x3dDefinition=obj.definition}switch(x3dDefinition){case x3dTypes_X3D:"objects"in obj&&x3dObjects.push(obj),obj.definition===x3dTypes_UNIT&&("length"===obj.category&&(x3dLength.factor=obj.conversionFactor,x3dLength.name=obj.name),"angle"===obj.category&&(x3dAngle.factor=obj.conversionFactor,x3dAngle.name=obj.name));break;case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_GROUP:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:if(x3dObjects.length>0){const group=x3dObjects.pop();"objects"in group&&group.objects.push(obj),x3dObjects.push(group),"objects"in obj&&x3dObjects.push(obj)}break;default:console.log("WARNING: invalid X3D definition")}x3dLast=obj}})),parser.on("closetag",(node=>{switch(node.name.toUpperCase()){case"X3D":case"SCENE":case"TRANSFORM":case"SHAPE":case"GROUP":case"STATICGROUP":case"APPEARANCE":case"TRIANGLESET":case"TRIANGLEFANSET":case"TRIANGLESTRIPSET":case"QUADSET":case"INDEXEDTRIANGLESET":case"INDEXEDTRIANGLEFANSET":case"INDEXEDTRIANGLESTRIPSET":case"INDEXEDQUADSET":case"INDEXEDFACESET":case"ELEVATIONGRID":case"LINESET":case"INDEXEDLINESET":break;default:return}const popDefinition=()=>{x3dObjects.length>0&&(x3dDefinition=x3dObjects[x3dObjects.length-1].definition)};let obj=null;switch(x3dDefinition){case x3dTypes_X3D:x3dObjects.length>0&&(obj=x3dObjects.pop(),popDefinition()),0===x3dObjects.length&&(obj.length=x3dLength,obj.angle=x3dAngle,x3dObj=obj);break;case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_GROUP:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:x3dObjects.length>0&&(obj=x3dObjects.pop(),popDefinition());break;default:console.log("WARNING: unhandled definition",x3dDefinition)}})),parser.on("text",(value=>{null!==value&&(value=value.trim()).length>0&&x3dLast&&0!==x3dDefinition&&(x3dLast.value=value)})),parser.on("end",(()=>{})),parser.write(src).close()},parse=src=>(createX3DParser(src),{x3dObj:x3dObj,x3dMaterials:x3dMaterials,x3dTextures:x3dTextures}),codify=(x3d,data)=>{if(x3d.definition!==x3dTypes_X3D||!x3d.objects)throw new Error("X3D malformed");if(x3d.objects.length<1||x3d.objects[0].definition!==x3dTypes_SCENE)throw new Error("X3D did not define a SCENE");const objects=x3d.objects[0].objects,length=x3d.length,angle=x3d.angle;let code="";code=`// Objects : ${objects.length}\n// Units : ${length.name} (${length.factor})\n// Angles : ${angle.name} (${angle.factor})\n\nimport * from '@jscad/modeling'\n\nexport const main = () => {\n let options = {}\n let objects = []\n`;for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),instantiatePrimitive=(options,objects)=>{let geometry,object=findNode(x3dTypes_BOX,objects);if(object)return geometry=(options=>{const{center:center,size:size}=Object.assign({},{center:[0,0,0],size:[2,2,2]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of width, depth and height values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");return 0===size[0]||0===size[1]||0===size[2]?create$8():create$8([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((info=>{const vertices=info[0].map((i=>[center[0]+size[0]/2*(2*!!(1&i)-1),center[1]+size[1]/2*(2*!!(2&i)-1),center[2]+size[2]/2*(2*!!(4&i)-1)]));return create$7(vertices)})))})({size:object.size}),geometry;if(object=findNode(x3dTypes_CONE,objects),object)return geometry=rotateX(-Math.PI/2,cylinderElliptic({startRadius:[object.bottomRadius,object.bottomRadius],height:object.height,segments:object.subdivision,endRadius:[object.topRadius,object.topRadius]})),geometry;if(object=findNode(x3dTypes_CYLINDER,objects),object)return geometry=rotateX(-Math.PI/2,(options=>{const{center:center,height:height,radius:radius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return 0===height||0===radius?create$8():cylinderElliptic({center:center,height:height,startRadius:[radius,radius],endRadius:[radius,radius],segments:segments})})({radius:object.radius,height:object.height,segments:object.subdivision})),geometry;if(object=findNode(x3dTypes_SPHERE,objects),object)return geometry=sphere({radius:object.radius,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_EXTRUSION,objects),object)return geometry=extrudeX3D(object),geometry;if(object=findNode(x3dTypes_ARC2D,objects),object)return geometry=arc({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_ARCCLOSE2D,objects),object)return geometry="PIE"===object.closureType?circle({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision}):index$a.create([index$5.toPoints(index$5.close(arc({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision})))]),geometry;if(object=findNode(x3dTypes_CIRCLE2D,objects),object)return geometry=arc({radius:object.radius,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_DISK2D,objects),object)return geometry=object.innerRadius===object.outerRadius?arc({radius:object.outerRadius,segments:object.subdivision}):0===object.innerRadius?circle({radius:object.outerRadius,segments:object.subdivision}):subtract(circle({radius:object.outerRadius,segments:object.subdivision}),circle({radius:object.innerRadius,segments:object.subdivision})),geometry;if(object=findNode(x3dTypes_POLYLINE2D,objects),object)return geometry=line([object.lineSegments]),geometry;if(object=findNode(x3dTypes_RECTANGLE2D,objects),object)return geometry=(options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])})({size:object.size}),geometry;if(object=findNode(x3dTypes_TRIANGLESET2D,objects),object){const vertices=object.vertices,numpoints=vertices.length,numfaces=Math.trunc(numpoints/3);geometry=[];for(let i=0;i{const geometries=object.objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));if(0===geometries.length)return null;const matrix=createTransform(object.center,object.rotation,object.scale,object.scaleOrientation,object.translation);return geometries.map((geometry=>{const color=geometry.color;return geometry=((matrix,...objects)=>{if(0===(objects=flatten$1(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results})(matrix,geometry),color&&(geometry.color=color),geometry}))},instantiateShape=(options,object)=>{const objects=object.objects,color=findColor(objects);let geometry=instantiatePrimitive(0,objects);return geometry||(geometry=instantiateMesh(0,objects)),geometry||(geometry=((options,objects)=>{let geometry;const components=convertLine(0,objects);if(components){const{pointsSet:pointsSet,segColors:segColors}=components;geometry=pointsSet.map(((points,i)=>{let l;return l=segColors?colorize(segColors[i],line(points)):line(points),l}))}return geometry})(0,objects)),geometry||(geometry=null),geometry&&color&&(geometry=colorize(color,geometry)),geometry},instantiateDefinition=(options,object)=>{let geometry;switch(object.definition){case x3dTypes_TRANSFORM:geometry=instantiateTransform(options,object);break;case x3dTypes_SHAPE:geometry=instantiateShape(0,object);break;case x3dTypes_GROUP:geometry=((options,object)=>{const geometries=object.objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));return 0===geometries.length?null:geometries})(options,object);break;default:console.log("WARNING: unknown definition: "+object.definition)}return geometry},instantiate=(options,src)=>{(options=Object.assign({},{},options))&&options.statusCallback&&options.statusCallback({progress:0});const{x3dObj:x3dObj}=parse(src);if(x3dObj.definition!==x3dTypes_X3D||!x3dObj.objects)throw new Error("X3D malformed");if(x3dObj.objects.length<1||x3dObj.objects[0].definition!==x3dTypes_SCENE)throw new Error("X3D did not define a SCENE");options&&options.statusCallback&&options.statusCallback({progress:50});let geometries=((options,objects)=>{const geometries=objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));return instantiatedList.clear(),geometries})(options,x3dObj.objects[0].objects);return options.flatten&&(geometries=flatten(geometries)),options&&options.statusCallback&&options.statusCallback({progress:100}),geometries};exports.deserialize=(options,input)=>{const defaults={filename:"x3d",output:"script",version:"3.0.0-alpha.0",flatten:!0,addMetaData:!0};return"script"===(options=Object.assign({},defaults,options)).output?((options,src)=>{options=Object.assign({},{},options);const{version:version,addMetaData:addMetaData,filename:filename}=options;options&&options.statusCallback&&options.statusCallback({progress:0});const{x3dObj:x3dObj,x3dMaterials:x3dMaterials,x3dTextures:x3dTextures}=parse(src);let code=addMetaData?`//\n// Produced by JSCAD IO Library : X3D Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n`:"";if(!x3dObj)throw new Error("X3D parsing failed, no valid X3D data retrieved");return options&&options.statusCallback&&options.statusCallback({progress:50}),code+=codify(x3dObj),options&&options.statusCallback&&options.statusCallback({progress:100}),code})(options,input):instantiate(options,input)},exports.mimeType="model/x3d+xml",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadX3dDeserializer={}); +Object.defineProperty(exports,"__esModule",{value:!0}),exports.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",exports.NC_NAME_CHAR="-"+exports.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀",exports.NC_NAME_START_CHAR_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]$","u"),exports.NC_NAME_CHAR_RE=new RegExp("^["+exports.NC_NAME_CHAR+"]$","u"),exports.NC_NAME_RE=new RegExp("^["+exports.NC_NAME_START_CHAR+"]["+exports.NC_NAME_CHAR+"]*$","u"),exports.isNCNameStartChar=isNCNameStartChar,exports.isNCNameChar=function(c){return isNCNameStartChar(c)||45===c||46===c||c>=48&&c<=57||183===c||c>=768&&c<=879||c>=8255&&c<=8256}}(ed3),Object.defineProperty(saxes,"__esModule",{value:!0});var SaxesParser_1=saxes.SaxesParser=saxes.EVENTS=void 0,isS=ed5$1.isS,isChar10=ed5$1.isChar,isNameStartChar=ed5$1.isNameStartChar,isNameChar=ed5$1.isNameChar,S_LIST=ed5$1.S_LIST,NAME_RE=ed5$1.NAME_RE,isChar11=ed2$1.isChar,isNCNameStartChar=ed3.isNCNameStartChar,isNCNameChar=ed3.isNCNameChar,NC_NAME_RE=ed3.NC_NAME_RE;const XML_NAMESPACE="http://www.w3.org/XML/1998/namespace",XMLNS_NAMESPACE="http://www.w3.org/2000/xmlns/",rootNS={__proto__:null,xml:XML_NAMESPACE,xmlns:XMLNS_NAMESPACE},XML_ENTITIES={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},isQuote=c=>34===c||39===c,QUOTES=[34,39],DOCTYPE_TERMINATOR=[...QUOTES,91,62],DTD_TERMINATOR=[...QUOTES,60,93],XML_DECL_NAME_TERMINATOR=[61,63,...S_LIST],ATTRIB_VALUE_UNQUOTED_TERMINATOR=[...S_LIST,62,38,60];function nsPairCheck(parser,prefix,uri){switch(prefix){case"xml":uri!==XML_NAMESPACE&&parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);break;case"xmlns":uri!==XMLNS_NAMESPACE&&parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`)}switch(uri){case XMLNS_NAMESPACE:parser.fail(""===prefix?`the default namespace may not be set to ${uri}.`:`may not assign a prefix (even "xmlns") to the URI ${XMLNS_NAMESPACE}.`);break;case XML_NAMESPACE:switch(prefix){case"xml":break;case"":parser.fail(`the default namespace may not be set to ${uri}.`);break;default:parser.fail("may not assign the xml namespace to another prefix.")}}}const isNCName=name=>NC_NAME_RE.test(name),isName=name=>NAME_RE.test(name);saxes.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];const EVENT_NAME_TO_HANDLER_NAME={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};SaxesParser_1=saxes.SaxesParser=class{constructor(opt){this.opt=null!=opt?opt:{},this.fragmentOpt=!!this.opt.fragment;const xmlnsOpt=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=!1!==this.opt.position,this.fileName=this.opt.fileName,xmlnsOpt){this.nameStartCheck=isNCNameStartChar,this.nameCheck=isNCNameChar,this.isName=isNCName,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},rootNS);const additional=this.opt.additionalNamespaces;null!=additional&&(function(parser,mapping){for(const local of Object.keys(mapping))nsPairCheck(parser,local,mapping[local])}(this,additional),Object.assign(this.ns,additional))}else this.nameStartCheck=isNameStartChar,this.nameCheck=isNameChar,this.isName=isName,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var _a;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=0,this.attribList=[];const{fragmentOpt:fragmentOpt}=this;this.state=fragmentOpt?13:0,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=fragmentOpt,this.xmlDeclPossible=!fragmentOpt,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:defaultXMLVersion}=this.opt;if(void 0===defaultXMLVersion){if(!0===this.opt.forceXMLVersion)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");defaultXMLVersion="1.0"}this.setXMLVersion(defaultXMLVersion),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(XML_ENTITIES),null===(_a=this.readyHandler)||void 0===_a||_a.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(name,handler){this[EVENT_NAME_TO_HANDLER_NAME[name]]=handler}off(name){this[EVENT_NAME_TO_HANDLER_NAME[name]]=void 0}makeError(message){var _a;let msg=null!==(_a=this.fileName)&&void 0!==_a?_a:"";return this.trackPosition&&(msg.length>0&&(msg+=":"),msg+=`${this.line}:${this.column}`),msg.length>0&&(msg+=": "),new Error(msg+message)}fail(message){const err=this.makeError(message),handler=this.errorHandler;if(void 0===handler)throw err;return handler(err),this}write(chunk){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let end=!1;null===chunk?(end=!0,chunk=""):"object"==typeof chunk&&(chunk=chunk.toString()),void 0!==this.carriedFromPrevious&&(chunk=`${this.carriedFromPrevious}${chunk}`,this.carriedFromPrevious=void 0);let limit=chunk.length;const lastCode=chunk.charCodeAt(limit-1);!end&&(13===lastCode||lastCode>=55296&&lastCode<=56319)&&(this.carriedFromPrevious=chunk[limit-1],limit--,chunk=chunk.slice(0,limit));const{stateTable:stateTable}=this;for(this.chunk=chunk,this.i=0;this.i=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>=32||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:return 10===chunk.charCodeAt(i+1)&&(this.i=i+2),this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCode11(){const{chunk:chunk,i:i}=this;if(this.prevI=i,this.i=i+1,i>=chunk.length)return-1;const code=chunk.charCodeAt(i);if(this.column++,code<55296){if(code>31&&code<127||code>159&&8232!==code||9===code)return code;switch(code){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:{const next=chunk.charCodeAt(i+1);10!==next&&133!==next||(this.i=i+2)}case 133:case 8232:return this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail("disallowed character."),code}}if(code>56319)return code>=57344&&code<=65533||this.fail("disallowed character."),code;const final=65536+1024*(code-55296)+(chunk.charCodeAt(i+1)-56320);return this.i=i+2,final>1114111&&this.fail("disallowed character."),final}getCodeNorm(){const c=this.getCode();return-2===c?10:c}unget(){this.i=this.prevI,this.column--}captureTo(chars){let{i:start}=this;const{chunk:chunk}=this;for(;;){const c=this.getCode(),isNLLike=-2===c,final=isNLLike?10:c;if(-1===final||chars.includes(final))return this.text+=chunk.slice(start,this.prevI),final;isNLLike&&(this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i)}}captureToChar(char){let{i:start}=this;const{chunk:chunk}=this;for(;;){let c=this.getCode();switch(c){case-2:this.text+=`${chunk.slice(start,this.prevI)}\n`,start=this.i,c=10;break;case-1:return this.text+=chunk.slice(start),!1}if(c===char)return this.text+=chunk.slice(start,this.prevI),!0}}captureNameChars(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCode();if(-1===c)return this.name+=chunk.slice(start),-1;if(!isNameChar(c))return this.name+=chunk.slice(start,this.prevI),-2===c?10:c}}skipSpaces(){for(;;){const c=this.getCodeNorm();if(-1===c||!isS(c))return c}}setXMLVersion(version){this.currentXMLVersion=version,"1.0"===version?(this.isChar=isChar10,this.getCode=this.getCode10):(this.isChar=isChar11,this.getCode=this.getCode11)}sBegin(){65279===this.chunk.charCodeAt(0)&&(this.i++,this.column++),this.state=1}sBeginWhitespace(){const iBefore=this.i,c=this.skipSpaces();switch(this.prevI!==iBefore&&(this.xmlDeclPossible=!1),c){case 60:if(this.state=15,0!==this.text.length)throw new Error("no-empty text at start");break;case-1:break;default:this.unget(),this.state=13,this.xmlDeclPossible=!1}}sDoctype(){var _a;const c=this.captureTo(DOCTYPE_TERMINATOR);switch(c){case 62:null===(_a=this.doctypeHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13,this.doctype=!0;break;case-1:break;default:this.text+=String.fromCodePoint(c),91===c?this.state=4:isQuote(c)&&(this.state=3,this.q=c)}}sDoctypeQuote(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.q=null,this.state=2)}sDTD(){const c=this.captureTo(DTD_TERMINATOR);-1!==c&&(this.text+=String.fromCodePoint(c),93===c?this.state=2:60===c?this.state=6:isQuote(c)&&(this.state=5,this.q=c))}sDTDQuoted(){const q=this.q;this.captureToChar(q)&&(this.text+=String.fromCodePoint(q),this.state=4,this.q=null)}sDTDOpenWaka(){const c=this.getCodeNorm();switch(this.text+=String.fromCodePoint(c),c){case 33:this.state=7,this.openWakaBang="";break;case 63:this.state=11;break;default:this.state=4}}sDTDOpenWakaBang(){const char=String.fromCodePoint(this.getCodeNorm()),owb=this.openWakaBang+=char;this.text+=char,"-"!==owb&&(this.state="--"===owb?8:4,this.openWakaBang="")}sDTDComment(){this.captureToChar(45)&&(this.text+="-",this.state=9)}sDTDCommentEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),this.state=45===c?10:8}sDTDCommentEnded(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c?this.state=4:(this.fail("malformed comment."),this.state=8)}sDTDPI(){this.captureToChar(63)&&(this.text+="?",this.state=12)}sDTDPIEnding(){const c=this.getCodeNorm();this.text+=String.fromCodePoint(c),62===c&&(this.state=4)}sText(){0!==this.tags.length?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:start}=this;const{chunk:chunk}=this;loop:for(;;)switch(this.getCode()){case-2:this.entity+=`${chunk.slice(start,this.prevI)}\n`,start=this.i;break;case 59:{const{entityReturnState:entityReturnState}=this,entity=this.entity+chunk.slice(start,this.prevI);let parsed;this.state=entityReturnState,""===entity?(this.fail("empty entity name."),parsed="&;"):(parsed=this.parseEntity(entity),this.entity=""),13===entityReturnState&&void 0===this.textHandler||(this.text+=parsed);break loop}case-1:this.entity+=chunk.slice(start);break loop}}sOpenWaka(){const c=this.getCode();if(isNameStartChar(c))this.state=34,this.unget(),this.xmlDeclPossible=!1;else switch(c){case 47:this.state=43,this.xmlDeclPossible=!1;break;case 33:this.state=16,this.openWakaBang="",this.xmlDeclPossible=!1;break;case 63:this.state=23;break;default:this.fail("disallowed character in tag name"),this.state=13,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=20,this.openWakaBang="";break;case"--":this.state=17,this.openWakaBang="";break;case"DOCTYPE":this.state=2,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(45)&&(this.state=18)}sCommentEnding(){var _a;const c=this.getCodeNorm();45===c?(this.state=19,null===(_a=this.commentHandler)||void 0===_a||_a.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(c)}`,this.state=17)}sCommentEnded(){const c=this.getCodeNorm();62!==c?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(c)}`,this.state=17):this.state=13}sCData(){this.captureToChar(93)&&(this.state=21)}sCDataEnding(){const c=this.getCodeNorm();93===c?this.state=22:(this.text+=`]${String.fromCodePoint(c)}`,this.state=20)}sCDataEnding2(){var _a;const c=this.getCodeNorm();switch(c){case 62:null===(_a=this.cdataHandler)||void 0===_a||_a.call(this,this.text),this.text="",this.state=13;break;case 93:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(c)}`,this.state=20}}sPIFirstChar(){const c=this.getCodeNorm();this.nameStartCheck(c)?(this.piTarget+=String.fromCodePoint(c),this.state=24):63===c||isS(c)?(this.fail("processing instruction without a target."),this.state=63===c?26:25):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c),this.state=24)}sPIRest(){const{chunk:chunk,i:start}=this;for(;;){const c=this.getCodeNorm();if(-1===c)return void(this.piTarget+=chunk.slice(start));if(!this.nameCheck(c)){this.piTarget+=chunk.slice(start,this.prevI);const isQuestion=63===c;isQuestion||isS(c)?"xml"===this.piTarget?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=isQuestion?33:27):this.state=isQuestion?26:25:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(c));break}}}sPIBody(){if(0===this.text.length){const c=this.getCodeNorm();63===c?this.state=26:isS(c)||(this.text=String.fromCodePoint(c))}else this.captureToChar(63)&&(this.state=26)}sPIEnding(){var _a;const c=this.getCodeNorm();if(62===c){const{piTarget:piTarget}=this;"xml"===piTarget.toLowerCase()&&this.fail("the XML declaration must appear at the start of the document."),null===(_a=this.piHandler)||void 0===_a||_a.call(this,{target:piTarget,body:this.text}),this.piTarget=this.text="",this.state=13}else 63===c?this.text+="?":(this.text+=`?${String.fromCodePoint(c)}`,this.state=25);this.xmlDeclPossible=!1}sXMLDeclNameStart(){const c=this.skipSpaces();63!==c?-1!==c&&(this.state=28,this.name=String.fromCodePoint(c)):this.state=33}sXMLDeclName(){const c=this.captureTo(XML_DECL_NAME_TERMINATOR);if(63===c)return this.state=33,this.name+=this.text,this.text="",void this.fail("XML declaration is incomplete.");if(isS(c)||61===c){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=61===c?30:29}}sXMLDeclEq(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(61!==c&&this.fail("value required."),this.state=30)}sXMLDeclValueStart(){const c=this.getCodeNorm();if(63===c)return this.state=33,void this.fail("XML declaration is incomplete.");isS(c)||(isQuote(c)?this.q=c:(this.fail("value must be quoted."),this.q=32),this.state=31)}sXMLDeclValue(){const c=this.captureTo([this.q,63]);if(63===c)return this.state=33,this.text="",void this.fail("XML declaration is incomplete.");if(-1===c)return;const value=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];const version=value;this.xmlDecl.version=version,/^1\.[0-9]+$/.test(version)?this.opt.forceXMLVersion||this.setXMLVersion(version):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=value;break;case"standalone":"yes"!==value&&"no"!==value&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=value}this.name="",this.state=32}sXMLDeclSeparator(){const c=this.getCodeNorm();63!==c?(isS(c)||(this.fail("whitespace required."),this.unget()),this.state=27):this.state=33}sXMLDeclEnding(){var _a;62===this.getCodeNorm()?("xml"!==this.piTarget?this.fail("processing instructions are not allowed before root."):"version"!==this.name&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),null===(_a=this.xmldeclHandler)||void 0===_a||_a.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=13):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var _a;const c=this.captureNameChars();if(-1===c)return;const tag=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=tag.ns=Object.create(null)),null===(_a=this.openTagStartHandler)||void 0===_a||_a.call(this,tag),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),c){case 62:this.openTag();break;case 47:this.state=35;break;default:isS(c)||this.fail("disallowed character in tag name."),this.state=36}}sOpenTagSlash(){62===this.getCode()?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=36)}sAttrib(){const c=this.skipSpaces();-1!==c&&(isNameStartChar(c)?(this.unget(),this.state=37):62===c?this.openTag():47===c?this.state=35:this.fail("disallowed character in attribute name."))}sAttribName(){const c=this.captureNameChars();61===c?this.state=39:isS(c)?this.state=38:62===c?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):-1!==c&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){const c=this.skipSpaces();switch(c){case-1:return;case 61:this.state=39;break;default:this.fail("attribute without value."),this.text="",this.name="",62===c?this.openTag():isNameStartChar(c)?(this.unget(),this.state=37):(this.fail("disallowed character in attribute name."),this.state=36)}}sAttribValue(){const c=this.getCodeNorm();isQuote(c)?(this.q=c,this.state=40):isS(c)||(this.fail("unquoted attribute value."),this.state=42,this.unget())}sAttribValueQuoted(){const{q:q,chunk:chunk}=this;let{i:start}=this;for(;;)switch(this.getCode()){case q:return this.pushAttrib(this.name,this.text+chunk.slice(start,this.prevI)),this.name=this.text="",this.q=null,void(this.state=41);case 38:return this.text+=chunk.slice(start,this.prevI),this.state=14,void(this.entityReturnState=40);case 10:case-2:case 9:this.text+=`${chunk.slice(start,this.prevI)} `,start=this.i;break;case 60:return this.text+=chunk.slice(start,this.prevI),void this.fail("disallowed character.");case-1:return void(this.text+=chunk.slice(start))}}sAttribValueClosed(){const c=this.getCodeNorm();isS(c)?this.state=36:62===c?this.openTag():47===c?this.state=35:isNameStartChar(c)?(this.fail("no whitespace between attributes."),this.unget(),this.state=37):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){const c=this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);switch(c){case 38:this.state=14,this.entityReturnState=42;break;case 60:this.fail("disallowed character.");break;case-1:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",62===c?this.openTag():this.state=36}}sCloseTag(){const c=this.captureNameChars();62===c?this.closeTag():isS(c)?this.state=44:-1!==c&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case 62:this.closeTag();break;case-1:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:start,forbiddenState:forbiddenState}=this;const{chunk:chunk,textHandler:handler}=this;scanLoop:for(;;)switch(this.getCode()){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}forbiddenState=0;break scanLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),forbiddenState=0;break scanLoop;case 93:switch(forbiddenState){case 0:forbiddenState=1;break;case 1:forbiddenState=2;break;case 2:break;default:throw new Error("impossible state")}break;case 62:2===forbiddenState&&this.fail('the string "]]>" is disallowed in char data.'),forbiddenState=0;break;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i,forbiddenState=0;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break scanLoop;default:forbiddenState=0}this.forbiddenState=forbiddenState}handleTextOutsideRoot(){let{i:start}=this;const{chunk:chunk,textHandler:handler}=this;let nonSpace=!1;outRootLoop:for(;;){const code=this.getCode();switch(code){case 60:if(this.state=15,void 0!==handler){const{text:text}=this,slice=chunk.slice(start,this.prevI);0!==text.length?(handler(text+slice),this.text=""):0!==slice.length&&handler(slice)}break outRootLoop;case 38:this.state=14,this.entityReturnState=13,void 0!==handler&&(this.text+=chunk.slice(start,this.prevI)),nonSpace=!0;break outRootLoop;case-2:void 0!==handler&&(this.text+=`${chunk.slice(start,this.prevI)}\n`),start=this.i;break;case-1:void 0!==handler&&(this.text+=chunk.slice(start));break outRootLoop;default:isS(code)||(nonSpace=!0)}}nonSpace&&(this.sawRoot||this.reportedTextBeforeRoot||(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(name,value){var _a;const{prefix:prefix,local:local}=this.qname(name),attr={name:name,prefix:prefix,local:local,value:value};if(this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr),"xmlns"===prefix){const trimmed=value.trim();"1.0"===this.currentXMLVersion&&""===trimmed&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[local]=trimmed,nsPairCheck(this,local,trimmed)}else if("xmlns"===name){const trimmed=value.trim();this.topNS[""]=trimmed,nsPairCheck(this,"",trimmed)}}pushAttribPlain(name,value){var _a;const attr={name:name,value:value};this.attribList.push(attr),null===(_a=this.attributeHandler)||void 0===_a||_a.call(this,attr)}end(){var _a,_b;this.sawRoot||this.fail("document must contain a root element.");const{tags:tags}=this;for(;tags.length>0;){const tag=tags.pop();this.fail(`unclosed tag: ${tag.name}`)}0!==this.state&&13!==this.state&&this.fail("unexpected end.");const{text:text}=this;return 0!==text.length&&(null===(_a=this.textHandler)||void 0===_a||_a.call(this,text),this.text=""),this._closed=!0,null===(_b=this.endHandler)||void 0===_b||_b.call(this),this._init(),this}resolve(prefix){var _a,_b;let uri=this.topNS[prefix];if(void 0!==uri)return uri;const{tags:tags}=this;for(let index=tags.length-1;index>=0;index--)if(uri=tags[index].ns[prefix],void 0!==uri)return uri;return uri=this.ns[prefix],void 0!==uri?uri:null===(_b=(_a=this.opt).resolvePrefix)||void 0===_b?void 0:_b.call(_a,prefix)}qname(name){const colon=name.indexOf(":");if(-1===colon)return{prefix:"",local:name};const local=name.slice(colon+1),prefix=name.slice(0,colon);return(""===prefix||""===local||local.includes(":"))&&this.fail(`malformed name: ${name}.`),{prefix:prefix,local:local}}processAttribsNS(){var _a;const{attribList:attribList}=this,tag=this.tag;{const{prefix:prefix,local:local}=this.qname(tag.name);tag.prefix=prefix,tag.local=local;const uri=tag.uri=null!==(_a=this.resolve(prefix))&&void 0!==_a?_a:"";""!==prefix&&("xmlns"===prefix&&this.fail('tags may not have "xmlns" as prefix.'),""===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),tag.uri=prefix))}if(0===attribList.length)return;const{attributes:attributes}=tag,seen=new Set;for(const attr of attribList){const{name:name,prefix:prefix,local:local}=attr;let uri,eqname;""===prefix?(uri="xmlns"===name?XMLNS_NAMESPACE:"",eqname=name):(uri=this.resolve(prefix),void 0===uri&&(this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`),uri=prefix),eqname=`{${uri}}${local}`),seen.has(eqname)&&this.fail(`duplicate attribute: ${eqname}.`),seen.add(eqname),attr.uri=uri,attributes[name]=attr}this.attribList=[]}processAttribsPlain(){const{attribList:attribList}=this,attributes=this.tag.attributes;for(const{name:name,value:value}of attribList)void 0!==attributes[name]&&this.fail(`duplicate attribute: ${name}.`),attributes[name]=value;this.attribList=[]}openTag(){var _a;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!1,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),tags.push(tag),this.state=13,this.name=""}openSelfClosingTag(){var _a,_b,_c;this.processAttribs();const{tags:tags}=this,tag=this.tag;tag.isSelfClosing=!0,null===(_a=this.openTagHandler)||void 0===_a||_a.call(this,tag),null===(_b=this.closeTagHandler)||void 0===_b||_b.call(this,tag),null===(this.tag=null!==(_c=tags[tags.length-1])&&void 0!==_c?_c:null)&&(this.closedRoot=!0),this.state=13,this.name=""}closeTag(){const{tags:tags,name:name}=this;if(this.state=13,this.name="",""===name)return this.fail("weird empty close tag."),void(this.text+="");const handler=this.closeTagHandler;let l=tags.length;for(;l-- >0;){const tag=this.tag=tags.pop();if(this.topNS=tag.ns,null==handler||handler(tag),tag.name===name)break;this.fail("unexpected close tag.")}0===l?this.closedRoot=!0:l<0&&(this.fail(`unmatched closing tag: ${name}.`),this.text+=``)}parseEntity(entity){if("#"!==entity[0]){const defined=this.ENTITIES[entity];return void 0!==defined?defined:(this.fail(this.isName(entity)?"undefined entity.":"disallowed character in entity name."),`&${entity};`)}let num=NaN;return"x"===entity[1]&&/^#x[0-9a-f]+$/i.test(entity)?num=parseInt(entity.slice(2),16):/^#[0-9]+$/.test(entity)&&(num=parseInt(entity.slice(1),10)),this.isChar(num)?String.fromCodePoint(num):(this.fail("malformed character entity."),`&${entity};`)}};const nodeToObjectMap={X3D:element=>{const obj={definition:x3dTypes_X3D,objects:[]};return obj},UNIT:element=>{const obj={definition:x3dTypes_UNIT,category:"",name:"",conversionFactor:1};return element.category&&(obj.category=element.category),element.name&&(obj.name=element.name),element.conversionfactor&&(obj.conversionFactor=element.conversionfactor),obj},META:element=>{const obj={definition:x3dTypes_META,content:"",name:""};return element.content&&(obj.content=element.content),element.name&&(obj.name=element.name),obj},SCENE:element=>{const obj={definition:x3dTypes_SCENE,objects:[]};return obj},TRANSFORM:element=>{const obj={definition:x3dTypes_TRANSFORM,center:[0,0,0],rotation:[0,0,1,0],scale:[1,1,1],scaleOrientation:[0,0,1,0],translation:[0,0,0]};if(element.center){const values=parseNumbers(element.center);values.length>2&&(obj.center=values)}if(element.rotation){const values=parseNumbers(element.rotation);values.length>3&&(obj.rotation=values)}if(element.scale){const values=parseNumbers(element.scale);values.length>2&&(obj.scale=values)}if(element.scaleorientation){const values=parseNumbers(element.scaleorientation);values.length>3&&(obj.scaleOrientation=values)}if(element.translation){const values=parseNumbers(element.translation);values.length>2&&(obj.translation=values)}return obj.objects=[],obj},SHAPE:element=>{const obj={definition:x3dTypes_SHAPE,objects:[]};return obj},GROUP:x3dGroup,STATICGROUP:x3dGroup,BOX:element=>{const obj={definition:x3dTypes_BOX,size:[2,2,2]};if(element.size){const values=parseNumbers(element.size);values.length>2&&(obj.size=values)}return obj},CONE:element=>{const obj={definition:x3dTypes_CONE,bottomRadius:1,height:2,subdivision:32,topRadius:1e-5};return element.bottomRadius&&(obj.bottomRadius=Math.max(parseFloat(element.bottomRadius),1e-5)),element.height&&(obj.height=parseFloat(element.height)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),element.topRadius&&(obj.topRadius=Math.max(parseFloat(element.topRadius),1e-5)),obj},CYLINDER:element=>{const obj={definition:x3dTypes_CYLINDER,height:2,radius:1,subdivision:32};return element.height&&(obj.height=parseFloat(element.height)),element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},SPHERE:element=>{const obj={definition:x3dTypes_SPHERE,radius:1,subdivision:24};if(element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision){const values=parseNumbers(element.subdivision);values.length>1&&(obj.subdivision=Math.max(...values))}return obj},EXTRUSION:element=>{const obj={definition:x3dTypes_EXTRUSION,ccw:!0,beginCap:!0,endCap:!0,crossSection:[[1,1],[1,-1],[-1,-1],[-1,1],[1,1]],orientations:[[0,0,1,0]],scales:[[1,1]],spine:[[0,0,0],[0,1,0]]};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.beginCap&&(obj.beginCap=element.beginCap.includes("TRUE")||element.beginCap.includes("true")),element.endCap&&(obj.endCap=element.endCap.includes("TRUE")||element.endCap.includes("true")),element.crossSection){const values=parseNumbers(element.crossSection),numpoints=Math.trunc(values.length/2),points=[];for(let i=0;i{const obj={definition:x3dTypes_ARC2D,endAngle:Math.PI/2,radius:1,startAngle:0,subdivision:32};return element.endAngle&&(obj.endAngle=parseFloat(element.endAngle)),element.radius&&(obj.radius=parseFloat(element.radius)),element.startAngle&&(obj.startAngle=parseFloat(element.startAngle)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},ARCCLOSE2D:element=>{const obj={definition:x3dTypes_ARCCLOSE2D,closureType:"PIE",endAngle:Math.PI/2,radius:1,startAngle:0,subdivision:32};return element.closureType&&(obj.closureType=element.closureType),element.endAngle&&(obj.endAngle=parseFloat(element.endAngle)),element.radius&&(obj.radius=parseFloat(element.radius)),element.startAngle&&(obj.startAngle=parseFloat(element.startAngle)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},CIRCLE2D:element=>{const obj={definition:x3dTypes_CIRCLE2D,radius:1,subdivision:32};return element.radius&&(obj.radius=parseFloat(element.radius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},DISK2D:element=>{const obj={definition:x3dTypes_DISK2D,innerRadius:0,outerRadius:1,subdivision:32};return element.innerRadius&&(obj.innerRadius=parseFloat(element.innerRadius)),element.outerRadius&&(obj.outerRadius=parseFloat(element.outerRadius)),element.subdivision&&(obj.subdivision=parseFloat(element.subdivision)),obj},POLYLINE2D:element=>{const obj={definition:x3dTypes_POLYLINE2D,lineSegments:[]};if(element.lineSegments){const values=parseNumbers(element.lineSegments);for(let i=0;i{const obj={definition:x3dTypes_RECTANGLE2D,size:[2,2]};if(element.size){const values=parseNumbers(element.size);values.length>1&&(obj.size=values)}return obj},TRIANGLESET2D:element=>{const obj={definition:x3dTypes_TRIANGLESET2D,vertices:[]};if(element.vertices){const values=parseNumbers(element.vertices);for(let i=0;i{const obj={definition:x3dTypes_COLOR,colors:[]};if(element.color){const values=parseNumbers(element.color),numvalues=values.length,numcolors=Math.trunc(numvalues/3);for(let i=0;i{const obj={definition:x3dTypes_COORDINATE,points:[]};if(element.point){const values=parseNumbers(element.point),numvalues=values.length,numpoints=Math.trunc(numvalues/3);for(let i=0;i{const obj={definition:x3dTypes_TRIANGLESET,ccw:!0,colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),obj.objects=[],obj},TRIANGLEFANSET:element=>{const obj={definition:x3dTypes_TRIANGLEFANSET,ccw:!0,fanCount:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.fanCount&&(obj.fanCount=parseNumbers(element.fanCount)),obj.objects=[],obj},TRIANGLESTRIPSET:element=>{const obj={definition:x3dTypes_TRIANGLESTRIPSET,ccw:!0,stripCount:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.stripCount&&(obj.stripCount=parseNumbers(element.stripCount)),obj.objects=[],obj},QUADSET:element=>{const obj={definition:x3dTypes_QUADSET,ccw:!0,colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),obj.objects=[],obj},INDEXEDTRIANGLESET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLESET,ccw:!0,index:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index&&(obj.index=parseNumbers(element.index)),obj.objects=[],obj},INDEXEDTRIANGLEFANSET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLEFANSET,ccw:!0,fans:[],colorPerVertex:!0};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index){const indexes=parseIndices(element.index);obj.fans=indexes.filter((index=>index.length>2))}return obj.objects=[],obj},INDEXEDTRIANGLESTRIPSET:element=>{const obj={definition:x3dTypes_INDEXEDTRIANGLESTRIPSET,ccw:!0,strips:[],colorPerVertex:!0,objects:[]};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index){const indexes=parseIndices(element.index);obj.strips=indexes.filter((index=>index.length>2))}return obj},INDEXEDQUADSET:element=>{const obj={definition:x3dTypes_INDEXEDQUADSET,ccw:!0,index:[],colorPerVertex:!0};return element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.index&&(obj.index=parseNumbers(element.index)),obj.objects=[],obj},INDEXEDFACESET:element=>{const obj={definition:x3dTypes_INDEXEDFACESET,ccw:!0,convex:!0,faces:[],colorPerVertex:!0,colorIndex:null};if(element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.convex&&(obj.convex=element.convex.includes("TRUE")||element.convex.includes("true")),element.coordIndex){const indexes=parseIndices(element.coordIndex);obj.faces=indexes.filter((index=>index.length>2))}if(element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),element.colorIndex)if(obj.colorPerVertex){const indexes=parseIndices(element.colorIndex);obj.colorIndex=indexes.filter((index=>index.length>2))}else obj.colorIndex=parseNumbers(element.colorIndex);else obj.colorIndex=obj.faces;return obj.objects=[],obj},ELEVATIONGRID:element=>{const obj={definition:x3dTypes_ELEVATIONGRID,xDimension:2,zDimension:2,xSpacing:1,zSpacing:1,height:[0,0,0,0],ccw:!0,solid:!1,colorPerVertex:!0};return element.xDimension&&(obj.xDimension=parseFloat(element.xDimension)),element.zDimension&&(obj.zDimension=parseFloat(element.zDimension)),element.xSpacing&&(obj.xSpacing=parseFloat(element.xSpacing)),element.zSpacing&&(obj.zSpacing=parseFloat(element.zSpacing)),element.height&&(obj.height=parseNumbers(element.height)),element.ccw&&(obj.ccw=element.ccw.includes("TRUE")||element.ccw.includes("true")),element.solid&&(obj.solid=element.solid.includes("TRUE")||element.solid.includes("true")),element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},LINESET:element=>{const obj={definition:x3dTypes_LINESET,vertexCount:[],colorPerVertex:!0};return element.vertexCount&&(obj.vertexCount=parseNumbers(element.vertexCount)),element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},INDEXEDLINESET:element=>{const obj={definition:x3dTypes_INDEXEDLINESET,indexes:[],colorPerVertex:!0};if(element.coordIndex){const indexes=parseIndices(element.coordIndex);obj.indexes=indexes.filter((index=>index.length>1))}return element.colorPerVertex&&(obj.colorPerVertex=element.colorPerVertex.includes("TRUE")||element.colorPerVertex.includes("true")),obj.objects=[],obj},APPEARANCE:element=>{const obj={definition:x3dTypes_APPEARANCE,objects:[]};return obj},MATERIAL:element=>{const obj={definition:x3dTypes_MATERIAL,color:[.8,.8,.8,1]};let alpha=1;if(element.transparency&&(alpha=1-element.transparency),element.diffuseColor){const values=parseNumbers(element.diffuseColor);values.length>2&&(values.length<4&&values.push(alpha),obj.color=values)}if(element.emissiveColor){const values=parseNumbers(element.emissiveColor);values.length>2&&(values.length<4&&values.push(alpha),obj.color=values)}return obj}};let objectId=1;const parse=src=>{const parser=new SaxesParser_1;let x3dLast=null,x3dDefinition=x3dTypes_X3D;const x3dObjects=[],x3dDefs=new Map,x3dLength={factor:1,name:"meters"},x3dAngle={factor:1,name:"radians"};let x3dObj=null;return parser.on("error",(e=>{console.log(`error: line ${e.line}, column ${e.column}, bad character [${e.c}]`)})),parser.on("opentag",(node=>{const elementname=node.name.toUpperCase();let obj=nodeToObjectMap[elementname]?nodeToObjectMap[elementname](node.attributes,{x3dObjects:x3dObjects}):null;if(obj){if(obj.id=("0000"+objectId++).slice(-4),node.attributes.USE){const objectname=node.attributes.USE;if(x3dDefs.has(objectname)){const def=x3dDefs.get(objectname);def.definition!==obj.definition&&console.log(`WARNING: using a definition "${objectname}" of a different type; ${obj.definition} vs ${def.definition}`),obj=def}else console.log(`WARNING: definition "${objectname}" does not exist, using default for ${obj.definition}`)}else if(node.attributes.DEF){const objectname=node.attributes.DEF;x3dDefs.has(objectname)?console.log(`WARNING: redefintion of ${objectname} has been ignored`):x3dDefs.set(objectname,obj)}switch(obj.definition){case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:case x3dTypes_GROUP:x3dDefinition=obj.definition}switch(x3dDefinition){case x3dTypes_X3D:"objects"in obj&&x3dObjects.push(obj),obj.definition===x3dTypes_UNIT&&("length"===obj.category&&(x3dLength.factor=obj.conversionFactor,x3dLength.name=obj.name),"angle"===obj.category&&(x3dAngle.factor=obj.conversionFactor,x3dAngle.name=obj.name));break;case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_GROUP:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:if(x3dObjects.length>0){const group=x3dObjects.pop();"objects"in group&&group.objects.push(obj),x3dObjects.push(group),"objects"in obj&&x3dObjects.push(obj)}break;default:console.log("WARNING: invalid X3D definition")}x3dLast=obj}})),parser.on("closetag",(node=>{switch(node.name.toUpperCase()){case"X3D":case"SCENE":case"TRANSFORM":case"SHAPE":case"GROUP":case"STATICGROUP":case"APPEARANCE":case"TRIANGLESET":case"TRIANGLEFANSET":case"TRIANGLESTRIPSET":case"QUADSET":case"INDEXEDTRIANGLESET":case"INDEXEDTRIANGLEFANSET":case"INDEXEDTRIANGLESTRIPSET":case"INDEXEDQUADSET":case"INDEXEDFACESET":case"ELEVATIONGRID":case"LINESET":case"INDEXEDLINESET":break;default:return}const popDefinition=()=>{x3dObjects.length>0&&(x3dDefinition=x3dObjects[x3dObjects.length-1].definition)};let obj=null;switch(x3dDefinition){case x3dTypes_X3D:x3dObjects.length>0&&(obj=x3dObjects.pop(),popDefinition()),0===x3dObjects.length&&(obj.length=x3dLength,obj.angle=x3dAngle,x3dObj=obj);break;case x3dTypes_SCENE:case x3dTypes_TRANSFORM:case x3dTypes_SHAPE:case x3dTypes_GROUP:case x3dTypes_APPEARANCE:case x3dTypes_TRIANGLESET:case x3dTypes_TRIANGLEFANSET:case x3dTypes_TRIANGLESTRIPSET:case x3dTypes_QUADSET:case x3dTypes_INDEXEDTRIANGLESET:case x3dTypes_INDEXEDTRIANGLEFANSET:case x3dTypes_INDEXEDTRIANGLESTRIPSET:case x3dTypes_INDEXEDQUADSET:case x3dTypes_INDEXEDFACESET:case x3dTypes_ELEVATIONGRID:case x3dTypes_LINESET:case x3dTypes_INDEXEDLINESET:x3dObjects.length>0&&(obj=x3dObjects.pop(),popDefinition());break;default:console.log("WARNING: unhandled definition",x3dDefinition)}})),parser.on("text",(value=>{null!==value&&(value=value.trim()).length>0&&x3dLast&&0!==x3dDefinition&&(x3dLast.value=value)})),parser.on("end",(()=>{})),parser.write(src).close(),{x3dObj:x3dObj,x3dMaterials:[],x3dTextures:[]}},codify=(x3d,data)=>{if(x3d.definition!==x3dTypes_X3D||!x3d.objects)throw new Error("X3D malformed");if(x3d.objects.length<1||x3d.objects[0].definition!==x3dTypes_SCENE)throw new Error("X3D did not define a SCENE");const objects=x3d.objects[0].objects,length=x3d.length,angle=x3d.angle;let code="";code=`// Objects : ${objects.length}\n// Units : ${length.name} (${length.factor})\n// Angles : ${angle.name} (${angle.factor})\n\nimport * from '@jscad/modeling'\n\nexport const main = () => {\n let options = {}\n let objects = []\n`;for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),instantiatePrimitive=(options,objects)=>{let geometry,object=findNode(x3dTypes_BOX,objects);if(object)return geometry=(options=>{const{center:center,size:size}=Object.assign({},{center:[0,0,0],size:[2,2,2]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of width, depth and height values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");return 0===size[0]||0===size[1]||0===size[2]?create$8():create$8([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((info=>{const vertices=info[0].map((i=>[center[0]+size[0]/2*(2*!!(1&i)-1),center[1]+size[1]/2*(2*!!(2&i)-1),center[2]+size[2]/2*(2*!!(4&i)-1)]));return create$7(vertices)})))})({size:object.size}),geometry;if(object=findNode(x3dTypes_CONE,objects),object)return geometry=rotateX(-Math.PI/2,cylinderElliptic({startRadius:[object.bottomRadius,object.bottomRadius],height:object.height,segments:object.subdivision,endRadius:[object.topRadius,object.topRadius]})),geometry;if(object=findNode(x3dTypes_CYLINDER,objects),object)return geometry=rotateX(-Math.PI/2,(options=>{const{center:center,height:height,radius:radius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return 0===height||0===radius?create$8():cylinderElliptic({center:center,height:height,startRadius:[radius,radius],endRadius:[radius,radius],segments:segments})})({radius:object.radius,height:object.height,segments:object.subdivision})),geometry;if(object=findNode(x3dTypes_SPHERE,objects),object)return geometry=sphere({radius:object.radius,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_EXTRUSION,objects),object)return geometry=extrudeX3D(object),geometry;if(object=findNode(x3dTypes_ARC2D,objects),object)return geometry=arc({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_ARCCLOSE2D,objects),object)return geometry="PIE"===object.closureType?circle({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision}):index$a.create([index$5.toPoints(index$5.close(arc({radius:object.radius,startAngle:object.startAngle,endAngle:object.endAngle,segments:object.subdivision})))]),geometry;if(object=findNode(x3dTypes_CIRCLE2D,objects),object)return geometry=arc({radius:object.radius,segments:object.subdivision}),geometry;if(object=findNode(x3dTypes_DISK2D,objects),object)return geometry=object.innerRadius===object.outerRadius?arc({radius:object.outerRadius,segments:object.subdivision}):0===object.innerRadius?circle({radius:object.outerRadius,segments:object.subdivision}):subtract(circle({radius:object.outerRadius,segments:object.subdivision}),circle({radius:object.innerRadius,segments:object.subdivision})),geometry;if(object=findNode(x3dTypes_POLYLINE2D,objects),object)return geometry=line([object.lineSegments]),geometry;if(object=findNode(x3dTypes_RECTANGLE2D,objects),object)return geometry=(options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])})({size:object.size}),geometry;if(object=findNode(x3dTypes_TRIANGLESET2D,objects),object){const vertices=object.vertices,numpoints=vertices.length,numfaces=Math.trunc(numpoints/3);geometry=[];for(let i=0;i{const objects=object.objects,color=findColor(objects);let geometry=instantiatePrimitive(0,objects);return geometry||(geometry=instantiateMesh(0,objects)),geometry||(geometry=((options,objects)=>{let geometry;const components=convertLine(0,objects);if(components){const{pointsSet:pointsSet,segColors:segColors}=components;geometry=pointsSet.map(((points,i)=>{let l;return l=segColors?colorize(segColors[i],line(points)):line(points),l}))}return geometry})(0,objects)),geometry||(geometry=null),geometry&&color&&(geometry=colorize(color,geometry)),geometry},instantiateDefinition=(options,object)=>{let geometry;switch(object.definition){case x3dTypes_TRANSFORM:geometry=((options,object)=>{const geometries=object.objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));if(0===geometries.length)return null;const matrix=createTransform(object.center,object.rotation,object.scale,object.scaleOrientation,object.translation);return geometries.map((geometry=>{const color=geometry.color;return geometry=transform(matrix,geometry),color&&(geometry.color=color),geometry}))})(options,object);break;case x3dTypes_SHAPE:geometry=instantiateShape(0,object);break;case x3dTypes_GROUP:geometry=((options,object)=>{const geometries=object.objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));return 0===geometries.length?null:geometries})(options,object);break;default:console.log("WARNING: unknown definition: "+object.definition)}return geometry},instantiate=(options,src)=>{(options=Object.assign({},{},options))&&options.statusCallback&&options.statusCallback({progress:0});const{x3dObj:x3dObj}=parse(src);if(x3dObj.definition!==x3dTypes_X3D||!x3dObj.objects)throw new Error("X3D malformed");if(x3dObj.objects.length<1||x3dObj.objects[0].definition!==x3dTypes_SCENE)throw new Error("X3D did not define a SCENE");options&&options.statusCallback&&options.statusCallback({progress:50});let geometries=((options,objects)=>{const geometries=objects.map((object=>instantiateDefinition(options,object))).filter((g=>null!=g));return instantiatedList.clear(),geometries})(options,x3dObj.objects[0].objects);return options.flatten&&(geometries=flatten(geometries)),options&&options.statusCallback&&options.statusCallback({progress:100}),geometries};exports.deserialize=(options,input)=>{const defaults={filename:"x3d",output:"script",version:"3.0.1-alpha.0",flatten:!0,addMetaData:!0};return options=Object.assign({},defaults,options),input=((stringOrArrayBuffer,defaultBinaryEncoding="utf-8")=>"string"==typeof stringOrArrayBuffer?stringOrArrayBuffer:new TextDecoder(defaultBinaryEncoding).decode(new Uint8Array(stringOrArrayBuffer)))(input),"script"===options.output?((options,src)=>{options=Object.assign({},{},options);const{version:version,addMetaData:addMetaData,filename:filename}=options;options&&options.statusCallback&&options.statusCallback({progress:0});const{x3dObj:x3dObj,x3dMaterials:x3dMaterials,x3dTextures:x3dTextures}=parse(src);let code=addMetaData?`//\n// Produced by JSCAD IO Library : X3D Deserializer (${version})\n// date: ${new Date}\n// source: ${filename}\n//\n`:"";if(!x3dObj)throw new Error("X3D parsing failed, no valid X3D data retrieved");return options&&options.statusCallback&&options.statusCallback({progress:50}),code+=codify(x3dObj),options&&options.statusCallback&&options.statusCallback({progress:100}),code})(options,input):instantiate(options,input)},exports.mimeType="model/x3d+xml",Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadX3dDeserializer={}); diff --git a/packages/io/x3d-deserializer/package.json b/packages/io/x3d-deserializer/package.json index 5e332cd1b..606a8912f 100644 --- a/packages/io/x3d-deserializer/package.json +++ b/packages/io/x3d-deserializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/x3d-deserializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "X3D Deserializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org/", @@ -32,9 +32,9 @@ "access": "public" }, "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/io-utils": "workspace:3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0", + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/io-utils": "workspace:3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", "saxes": "^6.0.0" }, "devDependencies": { diff --git a/packages/io/x3d-serializer/CHANGELOG.md b/packages/io/x3d-serializer/CHANGELOG.md index deff036c7..41d2cbba5 100644 --- a/packages/io/x3d-serializer/CHANGELOG.md +++ b/packages/io/x3d-serializer/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/x3d-serializer@2.4.2...@jscad/x3d-serializer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **io:** fix io after V3 refactoring ([7a12bbd](https://github.com/jscad/OpenJSCAD.org/commit/7a12bbdb7b4b3df792a4c5b3c8b30a6a985a48f0)) + +### Features + +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/x3d-serializer@2.4.2...@jscad/x3d-serializer@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/io/x3d-serializer/dist/jscad-x3d-serializer.es.js b/packages/io/x3d-serializer/dist/jscad-x3d-serializer.es.js index 3e3a4ebe1..bf26ea8a0 100644 --- a/packages/io/x3d-serializer/dist/jscad-x3d-serializer.es.js +++ b/packages/io/x3d-serializer/dist/jscad-x3d-serializer.es.js @@ -1,13 +1,13 @@ /** * X3D Serializer for JSCAD * @module @jscad/x3d-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),stringify=(a,indentation)=>{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;return a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}))?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},mimeType="model/x3d+xml",defNames=new Map,serialize=(options,...objects)=>{if(options=Object.assign({},{color:[0,0,1,1],shininess:8/256,smooth:!1,decimals:1e3,metadata:!0,unit:"millimeter",statusCallback:null},options),0===(objects=(objects=flatten(objects)).filter((object=>index$6.isA(object)||index$a.isA(object)||index$5.isA(object)))).length)throw new Error("expected one or more geom3/geom2/path2 objects");options.statusCallback&&options.statusCallback({progress:0});let body=["X3D",{profile:"Interchange",version:"3.3","xmlns:xsd":"http://www.w3.org/2001/XMLSchema-instance","xsd:noNamespaceSchemaLocation":"http://www.web3d.org/specifications/x3d-3.3.xsd"}];options.metadata?body.push(["head",{},["meta",{name:"creator",content:"Created by JSCAD"}],["meta",{name:"reference",content:"https://www.openjscad.xyz"}],["meta",{name:"created",content:(new Date).toISOString()}]]):body.push(["head",{},["meta",{name:"creator",content:"Created by JSCAD"}]]),body=body.concat(convertObjects(objects,options));const contents=`\n${stringify(body,2)}`;return options&&options.statusCallback&&options.statusCallback({progress:100}),[contents]},convertObjects=(objects,options)=>{const shapes=[];objects.forEach(((object,i)=>{if(options.statusCallback&&options.statusCallback({progress:100*i/objects.length}),index$6.isA(object)){object=((options,...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results})({snap:!0,triangulate:!0},object);index$6.toPolygons(object).length>0&&shapes.push(convertGeom3(object,options))}index$a.isA(object)&&shapes.push(convertGeom2(object,options)),index$5.isA(object)&&shapes.push(convertPath2(object,options))}));return[["Scene",{},["Transform",{rotation:"1 0 0 -1.5708"},...shapes]]]},convertPath2=(object,options)=>{const points=index$5.toPoints(object).slice();points.length>1&&object.isClosed&&points.push(points[0]);const shape=["Shape",shapeAttributes(object),convertPolyline2D(index$3.create(points))];return object.color&&shape.push(convertAppearance(object,"emissiveColor",options)),shape},convertGeom2=(object,options)=>{const outlines=index$a.toOutlines(object),group=["Group",{}];return outlines.forEach((outline=>{outline.length>1&&outline.push(outline[0]);const shape=["Shape",shapeAttributes(object),convertPolyline2D(index$3.create(outline))];object.color&&shape.push(convertAppearance(object,"emissiveColor",options)),group.push(shape)})),group},shapeAttributes=(object,attributes={})=>(object.id&&Object.assign(attributes,{DEF:checkDefName(object.id)}),attributes),checkDefName=defName=>{const count=defNames.get(defName)||0;return defNames.set(defName,count+1),count>0&&console.warn(`Warning: object.id set as DEF but not unique. ${defName} set ${count+1} times.`),defName},convertPolyline2D=(object,options)=>["Polyline2D",{lineSegments:object.points.map((p=>`${p[0]} ${p[1]}`)).join(" ")}],convertAppearance=(object,colorField,options)=>{const materialFields={[colorField]:object.color.slice(0,3).join(" "),transparency:roundToDecimals(1-object.color[3],options)};return"diffuseColor"===colorField&&Object.assign(materialFields,{specularColor:"0.2 0.2 0.2",shininess:options.shininess}),["Appearance",["Material",materialFields]]},convertGeom3=(object,options)=>{const shape=["Shape",shapeAttributes(object),convertMesh(object,options)];let appearance=["Appearance",{},["Material"]];return object.color&&(appearance=convertAppearance(object,"diffuseColor",options)),shape.push(appearance),shape},convertMesh=(object,options)=>{const mesh=convertToTriangles(object,options),lists=polygons2coordinates(mesh,options),indexList=lists[0].join(" "),pointList=lists[1].join(" "),colorList=lists[2].join(" "),faceset=["IndexedTriangleSet",{ccw:"true",colorPerVertex:"false",normalPerVertex:options.smooth,solid:"false",index:indexList},["Coordinate",{point:pointList}]];return object.color||faceset.push(["Color",{color:colorList}]),faceset},convertToTriangles=(object,options)=>{const triangles=[];return index$6.toPolygons(object).forEach((poly=>{const firstVertex=poly.vertices[0];for(let i=poly.vertices.length-3;i>=0;i--){const triangle=index$7.create([firstVertex,poly.vertices[i+1],poly.vertices[i+2]]);let color=options.color;object.color&&(color=object.color),poly.color&&(color=poly.color),triangle.color=color,triangles.push(triangle)}})),triangles},roundToDecimals=(float,options)=>Math.round(float*options.decimals)/options.decimals,polygons2coordinates=(polygons,options)=>{const indexList=[],pointList=[],colorList=[],vertexTagToCoordIndexMap=new Map;return polygons.forEach((polygon=>{const polygonVertexIndices=[],numvertices=polygon.vertices.length;for(let i=0;i{let color=options.color;return polygon.color&&(color=polygon.color),`${color[0]} ${color[1]} ${color[2]}`})(polygon,options))})),vertexTagToCoordIndexMap.clear(),[indexList,pointList,colorList]};export{mimeType,serialize}; +const clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),stringify=(a,indentation)=>{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;return a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}))?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},mimeType="model/x3d+xml",defNames=new Map,serialize=(options,...objects)=>{if(options=Object.assign({},{color:[0,0,1,1],shininess:8/256,smooth:!1,decimals:1e3,metadata:!0,unit:"millimeter",statusCallback:null},options),0===(objects=(objects=flatten(objects)).filter((object=>index$6.isA(object)||index$a.isA(object)||index$5.isA(object)))).length)throw new Error("expected one or more geom3/geom2/path2 objects");options.statusCallback&&options.statusCallback({progress:0});let body=["X3D",{profile:"Interchange",version:"3.3","xmlns:xsd":"http://www.w3.org/2001/XMLSchema-instance","xsd:noNamespaceSchemaLocation":"http://www.web3d.org/specifications/x3d-3.3.xsd"}];options.metadata?body.push(["head",{},["meta",{name:"creator",content:"Created by JSCAD"}],["meta",{name:"reference",content:"https://www.openjscad.xyz"}],["meta",{name:"created",content:(new Date).toISOString()}]]):body.push(["head",{},["meta",{name:"creator",content:"Created by JSCAD"}]]),body=body.concat(convertObjects(objects,options));const contents=`\n${stringify(body,2)}`;return options&&options.statusCallback&&options.statusCallback({progress:100}),[contents]},convertObjects=(objects,options)=>{const shapes=[];objects.forEach(((object,i)=>{if(options.statusCallback&&options.statusCallback({progress:100*i/objects.length}),index$6.isA(object)){object=generalize({snap:!0,triangulate:!0},object);index$6.toPolygons(object).length>0&&shapes.push(convertGeom3(object,options))}index$a.isA(object)&&shapes.push(convertGeom2(object,options)),index$5.isA(object)&&shapes.push(convertPath2(object,options))}));return[["Scene",{},["Transform",{rotation:"1 0 0 -1.5708"},...shapes]]]},convertPath2=(object,options)=>{const points=index$5.toPoints(object).slice();points.length>1&&object.isClosed&&points.push(points[0]);const shape=["Shape",shapeAttributes(object),convertPolyline2D(index$3.create(points))];return object.color&&shape.push(convertAppearance(object,"emissiveColor",options)),shape},convertGeom2=(object,options)=>{const outlines=index$a.toOutlines(object),group=["Group",{}];return outlines.forEach((outline=>{outline.length>1&&outline.push(outline[0]);const shape=["Shape",shapeAttributes(object),convertPolyline2D(index$3.create(outline))];object.color&&shape.push(convertAppearance(object,"emissiveColor",options)),group.push(shape)})),group},shapeAttributes=(object,attributes={})=>(object.id&&Object.assign(attributes,{DEF:checkDefName(object.id)}),attributes),checkDefName=defName=>{const count=defNames.get(defName)||0;return defNames.set(defName,count+1),count>0&&console.warn(`Warning: object.id set as DEF but not unique. ${defName} set ${count+1} times.`),defName},convertPolyline2D=(object,options)=>["Polyline2D",{lineSegments:object.points.map((p=>`${p[0]} ${p[1]}`)).join(" ")}],convertAppearance=(object,colorField,options)=>{const materialFields={[colorField]:object.color.slice(0,3).join(" "),transparency:roundToDecimals(1-object.color[3],options)};return"diffuseColor"===colorField&&Object.assign(materialFields,{specularColor:"0.2 0.2 0.2",shininess:options.shininess}),["Appearance",["Material",materialFields]]},convertGeom3=(object,options)=>{const shape=["Shape",shapeAttributes(object),convertMesh(object,options)];let appearance=["Appearance",{},["Material"]];return object.color&&(appearance=convertAppearance(object,"diffuseColor",options)),shape.push(appearance),shape},convertMesh=(object,options)=>{const mesh=convertToTriangles(object,options),lists=polygons2coordinates(mesh,options),indexList=lists[0].join(" "),pointList=lists[1].join(" "),colorList=lists[2].join(" "),faceset=["IndexedTriangleSet",{ccw:"true",colorPerVertex:"false",normalPerVertex:options.smooth,solid:"false",index:indexList},["Coordinate",{point:pointList}]];return object.color||faceset.push(["Color",{color:colorList}]),faceset},convertToTriangles=(object,options)=>{const triangles=[];return index$6.toPolygons(object).forEach((poly=>{const firstVertex=poly.vertices[0];for(let i=poly.vertices.length-3;i>=0;i--){const triangle=index$7.create([firstVertex,poly.vertices[i+1],poly.vertices[i+2]]);let color=options.color;object.color&&(color=object.color),poly.color&&(color=poly.color),triangle.color=color,triangles.push(triangle)}})),triangles},roundToDecimals=(float,options)=>Math.round(float*options.decimals)/options.decimals,polygons2coordinates=(polygons,options)=>{const indexList=[],pointList=[],colorList=[],vertexTagToCoordIndexMap=new Map;return polygons.forEach((polygon=>{const polygonVertexIndices=[],numvertices=polygon.vertices.length;for(let i=0;i{let color=options.color;return polygon.color&&(color=polygon.color),`${color[0]} ${color[1]} ${color[2]}`})(polygon,options))})),vertexTagToCoordIndexMap.clear(),[indexList,pointList,colorList]};export{mimeType,serialize}; diff --git a/packages/io/x3d-serializer/dist/jscad-x3d-serializer.min.js b/packages/io/x3d-serializer/dist/jscad-x3d-serializer.min.js index cf229e174..cd98029df 100644 --- a/packages/io/x3d-serializer/dist/jscad-x3d-serializer.min.js +++ b/packages/io/x3d-serializer/dist/jscad-x3d-serializer.min.js @@ -1,14 +1,14 @@ /** * X3D Serializer for JSCAD * @module @jscad/x3d-serializer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ var global,factory;global=this,factory=function(exports){ /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;iarr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),stringify=(a,indentation)=>{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;return a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}))?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},defNames=new Map,convertObjects=(objects,options)=>{const shapes=[];return objects.forEach(((object,i)=>{options.statusCallback&&options.statusCallback({progress:100*i/objects.length}),index$6.isA(object)&&(object=((options,...geometries)=>{if(0===(geometries=flatten$1(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results})({snap:!0,triangulate:!0},object),index$6.toPolygons(object).length>0&&shapes.push(convertGeom3(object,options))),index$a.isA(object)&&shapes.push(convertGeom2(object,options)),index$5.isA(object)&&shapes.push(convertPath2(object,options))})),[["Scene",{},["Transform",{rotation:"1 0 0 -1.5708"},...shapes]]]},convertPath2=(object,options)=>{const points=index$5.toPoints(object).slice();points.length>1&&object.isClosed&&points.push(points[0]);const shape=["Shape",shapeAttributes(object),convertPolyline2D(index$3.create(points))];return object.color&&shape.push(convertAppearance(object,"emissiveColor",options)),shape},convertGeom2=(object,options)=>{const outlines=index$a.toOutlines(object),group=["Group",{}];return outlines.forEach((outline=>{outline.length>1&&outline.push(outline[0]);const shape=["Shape",shapeAttributes(object),convertPolyline2D(index$3.create(outline))];object.color&&shape.push(convertAppearance(object,"emissiveColor",options)),group.push(shape)})),group},shapeAttributes=(object,attributes={})=>(object.id&&Object.assign(attributes,{DEF:checkDefName(object.id)}),attributes),checkDefName=defName=>{const count=defNames.get(defName)||0;return defNames.set(defName,count+1),count>0&&console.warn(`Warning: object.id set as DEF but not unique. ${defName} set ${count+1} times.`),defName},convertPolyline2D=(object,options)=>["Polyline2D",{lineSegments:object.points.map((p=>`${p[0]} ${p[1]}`)).join(" ")}],convertAppearance=(object,colorField,options)=>{const materialFields={[colorField]:object.color.slice(0,3).join(" "),transparency:roundToDecimals(1-object.color[3],options)};return"diffuseColor"===colorField&&Object.assign(materialFields,{specularColor:"0.2 0.2 0.2",shininess:options.shininess}),["Appearance",["Material",materialFields]]},convertGeom3=(object,options)=>{const shape=["Shape",shapeAttributes(object),convertMesh(object,options)];let appearance=["Appearance",{},["Material"]];return object.color&&(appearance=convertAppearance(object,"diffuseColor",options)),shape.push(appearance),shape},convertMesh=(object,options)=>{const mesh=convertToTriangles(object,options),lists=polygons2coordinates(mesh,options),indexList=lists[0].join(" "),pointList=lists[1].join(" "),colorList=lists[2].join(" "),faceset=["IndexedTriangleSet",{ccw:"true",colorPerVertex:"false",normalPerVertex:options.smooth,solid:"false",index:indexList},["Coordinate",{point:pointList}]];return object.color||faceset.push(["Color",{color:colorList}]),faceset},convertToTriangles=(object,options)=>{const triangles=[];return index$6.toPolygons(object).forEach((poly=>{const firstVertex=poly.vertices[0];for(let i=poly.vertices.length-3;i>=0;i--){const triangle=index$7.create([firstVertex,poly.vertices[i+1],poly.vertices[i+2]]);let color=options.color;object.color&&(color=object.color),poly.color&&(color=poly.color),triangle.color=color,triangles.push(triangle)}})),triangles},roundToDecimals=(float,options)=>Math.round(float*options.decimals)/options.decimals,polygons2coordinates=(polygons,options)=>{const indexList=[],pointList=[],colorList=[],vertexTagToCoordIndexMap=new Map;return polygons.forEach((polygon=>{const polygonVertexIndices=[],numvertices=polygon.vertices.length;for(let i=0;i{let color=options.color;return polygon.color&&(color=polygon.color),`${color[0]} ${color[1]} ${color[2]}`})(polygon,options))})),vertexTagToCoordIndexMap.clear(),[indexList,pointList,colorList]};exports.mimeType="model/x3d+xml",exports.serialize=(options,...objects)=>{if(options=Object.assign({},{color:[0,0,1,1],shininess:8/256,smooth:!1,decimals:1e3,metadata:!0,unit:"millimeter",statusCallback:null},options),0===(objects=(objects=flatten(objects)).filter((object=>index$6.isA(object)||index$a.isA(object)||index$5.isA(object)))).length)throw new Error("expected one or more geom3/geom2/path2 objects");options.statusCallback&&options.statusCallback({progress:0});let body=["X3D",{profile:"Interchange",version:"3.3","xmlns:xsd":"http://www.w3.org/2001/XMLSchema-instance","xsd:noNamespaceSchemaLocation":"http://www.web3d.org/specifications/x3d-3.3.xsd"}];options.metadata?body.push(["head",{},["meta",{name:"creator",content:"Created by JSCAD"}],["meta",{name:"reference",content:"https://www.openjscad.xyz"}],["meta",{name:"created",content:(new Date).toISOString()}]]):body.push(["head",{},["meta",{name:"creator",content:"Created by JSCAD"}]]),body=body.concat(convertObjects(objects,options));const contents=`\n${stringify(body,2)}`;return options&&options.statusCallback&&options.statusCallback({progress:100}),[contents]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadX3dSerializer={}); +const clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,TAU=2*Math.PI,rezero=n=>Math.abs(n)<1e-13?0:n,sin=radians=>rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0](out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:()=>[0,0,0],cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out};Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:(out,vector)=>(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation:(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues:(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},fromVectorRotation:(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:(out,plane)=>{const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out}});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:()=>[0,0],cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance:(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$a,fromSides:sides=>{const pointMap=(sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap})(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint:signedDistanceToPoint,toString:toString$7,transform:(out,plane,matrix)=>{const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,toVertices$1=polygon=>polygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>1e-13)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;i0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;i{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b)));distance>maxDistance&&(maxDistance=distance,v2=vertex)}}var point,a,b;const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms);var index$6=Object.freeze({__proto__:null,clone:geometry=>Object.assign({},geometry),create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),(object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)})(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms);var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validate:object=>{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const flatten$1=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten$1(val)):acc.concat(val)),[]),getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType}(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours));class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1;class PolygonHierarchy{constructor(slice){this.plane=calculatePlane(slice);const rightVector=orthogonal([0,0,0],this.plane),perp=cross$1([0,0,0],this.plane,rightVector);this.v=normalize$1(perp,perp),this.u=cross$1([0,0,0],this.v,this.plane),this.basisMap=new Map;const projected=slice.contours.map((part=>part.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=((list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuechildren[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices:vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA:isA,reverse:slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges:slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges},toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=((data,holeIndices,dim=2)=>{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles})(vertices.flat(),holesIndex);for(let i=0;i{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:(matrix,slice)=>{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)},validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]};Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:()=>[0,1,0],direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)},origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&(a=plane1,b=plane2,Math.abs(a[0]-b[0])<=1e-13&&Math.abs(a[1]-b[1])<=1e-13&&Math.abs(a[2]-b[2])<=1e-13);var a,b,plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const retesselatedPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons})(mapping[1]);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=((...geometries)=>{const results=(geometries=flatten$1(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results})(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=((epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons})(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),stringify=(a,indentation)=>{const cr=indentation>0?"\n":"",indent=(indentation=>{if(!(indentation>0))return txt=>txt;const space=" ".repeat(indentation);return txt=>{if("string"!=typeof txt)return txt;const arr=txt.split("\n");return 1===arr.length?space+txt:arr.map((e=>""===e.trim()?e:space+e)).join("\n")}})(indentation),rec=a=>{let res,body="",isFlat=!0;return a.some(((e,i,arr)=>{if(0===i)return res="<"+e,1===arr.length;if(1===i){if((o=e)&&"[object Object]"===Object.prototype.toString.call(o))return Object.keys(e).forEach((key=>{let val=e[key];Array.isArray(val)&&(val=val.join(" ")),res+=" "+key+'="'+val+'"'})),2===arr.length||(res+=">",!1);res+=">"}var o;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return body+=e+cr,!1}return isFlat=!1,body+=rec(e),!1}))?res+"/>"+cr:isFlat?res+body.split("\n").filter((e=>""!==e.trim())).join("\n")+""+cr:res+cr+indent(body)+""+cr};return rec(a)},defNames=new Map,convertObjects=(objects,options)=>{const shapes=[];return objects.forEach(((object,i)=>{options.statusCallback&&options.statusCallback({progress:100*i/objects.length}),index$6.isA(object)&&(object=generalize({snap:!0,triangulate:!0},object),index$6.toPolygons(object).length>0&&shapes.push(convertGeom3(object,options))),index$a.isA(object)&&shapes.push(convertGeom2(object,options)),index$5.isA(object)&&shapes.push(convertPath2(object,options))})),[["Scene",{},["Transform",{rotation:"1 0 0 -1.5708"},...shapes]]]},convertPath2=(object,options)=>{const points=index$5.toPoints(object).slice();points.length>1&&object.isClosed&&points.push(points[0]);const shape=["Shape",shapeAttributes(object),convertPolyline2D(index$3.create(points))];return object.color&&shape.push(convertAppearance(object,"emissiveColor",options)),shape},convertGeom2=(object,options)=>{const outlines=index$a.toOutlines(object),group=["Group",{}];return outlines.forEach((outline=>{outline.length>1&&outline.push(outline[0]);const shape=["Shape",shapeAttributes(object),convertPolyline2D(index$3.create(outline))];object.color&&shape.push(convertAppearance(object,"emissiveColor",options)),group.push(shape)})),group},shapeAttributes=(object,attributes={})=>(object.id&&Object.assign(attributes,{DEF:checkDefName(object.id)}),attributes),checkDefName=defName=>{const count=defNames.get(defName)||0;return defNames.set(defName,count+1),count>0&&console.warn(`Warning: object.id set as DEF but not unique. ${defName} set ${count+1} times.`),defName},convertPolyline2D=(object,options)=>["Polyline2D",{lineSegments:object.points.map((p=>`${p[0]} ${p[1]}`)).join(" ")}],convertAppearance=(object,colorField,options)=>{const materialFields={[colorField]:object.color.slice(0,3).join(" "),transparency:roundToDecimals(1-object.color[3],options)};return"diffuseColor"===colorField&&Object.assign(materialFields,{specularColor:"0.2 0.2 0.2",shininess:options.shininess}),["Appearance",["Material",materialFields]]},convertGeom3=(object,options)=>{const shape=["Shape",shapeAttributes(object),convertMesh(object,options)];let appearance=["Appearance",{},["Material"]];return object.color&&(appearance=convertAppearance(object,"diffuseColor",options)),shape.push(appearance),shape},convertMesh=(object,options)=>{const mesh=convertToTriangles(object,options),lists=polygons2coordinates(mesh,options),indexList=lists[0].join(" "),pointList=lists[1].join(" "),colorList=lists[2].join(" "),faceset=["IndexedTriangleSet",{ccw:"true",colorPerVertex:"false",normalPerVertex:options.smooth,solid:"false",index:indexList},["Coordinate",{point:pointList}]];return object.color||faceset.push(["Color",{color:colorList}]),faceset},convertToTriangles=(object,options)=>{const triangles=[];return index$6.toPolygons(object).forEach((poly=>{const firstVertex=poly.vertices[0];for(let i=poly.vertices.length-3;i>=0;i--){const triangle=index$7.create([firstVertex,poly.vertices[i+1],poly.vertices[i+2]]);let color=options.color;object.color&&(color=object.color),poly.color&&(color=poly.color),triangle.color=color,triangles.push(triangle)}})),triangles},roundToDecimals=(float,options)=>Math.round(float*options.decimals)/options.decimals,polygons2coordinates=(polygons,options)=>{const indexList=[],pointList=[],colorList=[],vertexTagToCoordIndexMap=new Map;return polygons.forEach((polygon=>{const polygonVertexIndices=[],numvertices=polygon.vertices.length;for(let i=0;i{let color=options.color;return polygon.color&&(color=polygon.color),`${color[0]} ${color[1]} ${color[2]}`})(polygon,options))})),vertexTagToCoordIndexMap.clear(),[indexList,pointList,colorList]};exports.mimeType="model/x3d+xml",exports.serialize=(options,...objects)=>{if(options=Object.assign({},{color:[0,0,1,1],shininess:8/256,smooth:!1,decimals:1e3,metadata:!0,unit:"millimeter",statusCallback:null},options),0===(objects=(objects=flatten(objects)).filter((object=>index$6.isA(object)||index$a.isA(object)||index$5.isA(object)))).length)throw new Error("expected one or more geom3/geom2/path2 objects");options.statusCallback&&options.statusCallback({progress:0});let body=["X3D",{profile:"Interchange",version:"3.3","xmlns:xsd":"http://www.w3.org/2001/XMLSchema-instance","xsd:noNamespaceSchemaLocation":"http://www.web3d.org/specifications/x3d-3.3.xsd"}];options.metadata?body.push(["head",{},["meta",{name:"creator",content:"Created by JSCAD"}],["meta",{name:"reference",content:"https://www.openjscad.xyz"}],["meta",{name:"created",content:(new Date).toISOString()}]]):body.push(["head",{},["meta",{name:"creator",content:"Created by JSCAD"}]]),body=body.concat(convertObjects(objects,options));const contents=`\n${stringify(body,2)}`;return options&&options.statusCallback&&options.statusCallback({progress:100}),[contents]},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadX3dSerializer={}); diff --git a/packages/io/x3d-serializer/package.json b/packages/io/x3d-serializer/package.json index 12af437be..62ec31efc 100644 --- a/packages/io/x3d-serializer/package.json +++ b/packages/io/x3d-serializer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/x3d-serializer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "X3D Serializer for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -37,9 +37,9 @@ ], "license": "MIT", "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", - "@jscad/io-utils": "workspace:^3.0.0-alpha.0", - "@jscad/modeling": "workspace:3.0.0-alpha.0", + "@jscad/array-utils": "workspace:3.0.1-alpha.0", + "@jscad/io-utils": "workspace:^3.0.1-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", "onml": "^1.3.0" }, "devDependencies": { diff --git a/packages/modeling/CHANGELOG.md b/packages/modeling/CHANGELOG.md index f2d471068..b5dbf86ef 100644 --- a/packages/modeling/CHANGELOG.md +++ b/packages/modeling/CHANGELOG.md @@ -3,6 +3,41 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/modeling@2.10.0...@jscad/modeling@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **all:** various fixes to pass tests ([5cb1d64](https://github.com/jscad/OpenJSCAD.org/commit/5cb1d648d3af1a4448d2c9a6a6acc701d38f36d3)) +* **cli:** rework logic for generating blobs, both singular and multiple as parts ([f88669b](https://github.com/jscad/OpenJSCAD.org/commit/f88669b286d9564165f5c33944703fce730dfc1f)) +* **modeling:** added geom3.fromPointsConvex() ([e23a5ab](https://github.com/jscad/OpenJSCAD.org/commit/e23a5ab55bb78d5e94b3562529fd100a5f163cf9)) +* **modeling:** added new TS definitions for mat4, and adjusted doc strings ([9fa56b7](https://github.com/jscad/OpenJSCAD.org/commit/9fa56b7b72fc40d49794ee153fd9d29b2fede785)) +* **modeling:** added orientation option to polygon ([cfa0e91](https://github.com/jscad/OpenJSCAD.org/commit/cfa0e9124c0df70d57502e4be7b29af31e03c2b9)) +* **modeling:** corrected checks of parameters to booleans ([29788a1](https://github.com/jscad/OpenJSCAD.org/commit/29788a14cefd142d6c0544871a606ea742ad0c39)) +* **modeling:** corrected geom2 mirroring transform ([8a1f04b](https://github.com/jscad/OpenJSCAD.org/commit/8a1f04b18bc866781ed08c2f38de3a495ea9581c)) +* **modeling:** corrected parameter names to follow standards ([4c35d41](https://github.com/jscad/OpenJSCAD.org/commit/4c35d41289ff4633a7e1a8b58e87e00fd565ce14)) +* **modeling:** create scission.d.ts and update index.d.ts ([5917d67](https://github.com/jscad/OpenJSCAD.org/commit/5917d6759889e9394a6cf4fd42065b0ff07750b1)) +* **modeling:** created TS definitions for splitPolygonByPlane ([f9a3715](https://github.com/jscad/OpenJSCAD.org/commit/f9a3715fc8b6528c1f1dde1599897cc30e2fe758)) +* **modeling:** fix ts definitions and ts hints in comments ([6855c73](https://github.com/jscad/OpenJSCAD.org/commit/6855c73c7835ef9e255355ff56a7b38fdd26d0f8)) +* **modeling:** small fixes to comments and tests ([d59217e](https://github.com/jscad/OpenJSCAD.org/commit/d59217eb550093d650e9df8d9e178d3b796ccaba)) +* **modeling:** use modern typescript imports ([0a0d2e8](https://github.com/jscad/OpenJSCAD.org/commit/0a0d2e8e4ac5db50cf9a6f05a33dba9bdd68c98a)) +* **typo:** fix typo in rounded error messages ([8870b43](https://github.com/jscad/OpenJSCAD.org/commit/8870b434c7508074dcfacd5a2c616518bc35d3b2)) + +### Features + +* **modeling:** added Martinez library for 2D booleans, refactored 2D booleans ([e035291](https://github.com/jscad/OpenJSCAD.org/commit/e035291fb4577d1a4c9f98f0c7b2de11711caf43)) +* **modeling:** added validate to slice, as well as measurements ([5cfb4d2](https://github.com/jscad/OpenJSCAD.org/commit/5cfb4d21edf1ac5b52ece776e6dd3760d3e28d87)) +* **modeling:** corrected vectorChar and vectorText options to align with the common API ([c3a950f](https://github.com/jscad/OpenJSCAD.org/commit/c3a950f2615d938243fde55d323b94dd0fd9f06c)) +* **modeling:** enhanced poly2 into a complete geometry ([7180c35](https://github.com/jscad/OpenJSCAD.org/commit/7180c35f95b8a36f78117a86e4ae26f5ed6bab12)) +* **modeling:** preserve color for offset and extrude ([48606fc](https://github.com/jscad/OpenJSCAD.org/commit/48606fc32fff26dd8bde6ec03ce10b3c7086ee37)) +* **modeling:** remove unused mat4 functions ([3602faf](https://github.com/jscad/OpenJSCAD.org/commit/3602fafea32506e35f75b74f94ecd9d762116da6)) +* **modeling:** removed extrudeRectangular ([6c0cb4a](https://github.com/jscad/OpenJSCAD.org/commit/6c0cb4aae6f03a38f6f77f82db2d8e5b1166d8d8)) +* **modeling:** rename expansions to offsets, and unify expand into offset ([f2b3e31](https://github.com/jscad/OpenJSCAD.org/commit/f2b3e3162fedbd7c438bb2925abeac73342e62c6)) +* **modeling:** renamed poly3 toVertices and fromVerticesAndPlane ([58621b9](https://github.com/jscad/OpenJSCAD.org/commit/58621b9d23d8e0905eff23faf8e9dddb2c4023fb)) +* **modeling:** rework orthonormal formula ([008a462](https://github.com/jscad/OpenJSCAD.org/commit/008a4623b73ea95112c33cd9b48831055961bb96)) +* **modeling:** reworked exports to expose a flattened API ([8235238](https://github.com/jscad/OpenJSCAD.org/commit/8235238ad63d063f1e501478cae1208deb130a9c)) +* **modeling:** reworked vectorChar and vectorText to return segments as path2 objects ([d388fab](https://github.com/jscad/OpenJSCAD.org/commit/d388fab1c6341265f01db2b24360186de07f5c58)) +* **modeling:** support nested array structures in the API ([b8d8fb8](https://github.com/jscad/OpenJSCAD.org/commit/b8d8fb856f76985f9954eb70ea759dc6c07af07e)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/modeling@2.10.0...@jscad/modeling@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/modeling/dist/jscad-modeling.es.js b/packages/modeling/dist/jscad-modeling.es.js index f8f7751e5..2c7e3d1d3 100644 --- a/packages/modeling/dist/jscad-modeling.es.js +++ b/packages/modeling/dist/jscad-modeling.es.js @@ -1,7 +1,7 @@ /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -const cssColors={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]},colorNameToRgb=s=>cssColors[s.toLowerCase()],flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),clone$b=geometry=>Object.assign({},geometry),create$c=()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,NEPS=1e-13,TAU=2*Math.PI,rezero=n=>Math.abs(n)rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation=(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues$4=(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],create$b=()=>[0,0,0],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0]{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale$3=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:create$b,cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:rotateZ$2,scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const fromVectorRotation=(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation=(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation=(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply$1=(out,a,b)=>{const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out},translate$1=(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:create$c,equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:fromScaling,fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:fromValues$4,fromVectorRotation:fromVectorRotation,fromXRotation:fromXRotation,fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:fromZRotation,identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:mirrorByPlane,multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:translate$1});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),create$9=()=>[0,0],clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),snap$1=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};var index$b=Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:create$9,cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:snap$1,squaredDistance:squaredDistance,squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const toPointMap=sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap},fromSides=sides=>{const pointMap=toPointMap(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides=geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1)return;if(!endpointTouch&&(0===ua||1===ua||0===ub||1===ub))return;return[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:fromSides,fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:toSides,toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromNormalAndPoint=(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},projectionOfPoint=(plane,point)=>{const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;var index$9=Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:fromNormalAndPoint,fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,measureBoundingSphere$1=polygon=>{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;ipolygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>NEPS)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),toPoints$2=geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validateManifold=object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${`${v}`}/${`${vertices[(i+1)%vertices.length]}`}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)};var index$6=Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:toPoints$2,toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),validateManifold(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");controlPoints=controlPoints.slice();if(null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");if(3===color.length&&(color=[color[0],color[1],color[2],1]),0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):(object.color=color,object)));return 1===results.length?results[0]:results},hexToRgb=notation=>{if((notation=notation.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const r=parseInt(notation.substring(0,2),16)/255,g=parseInt(notation.substring(2,4),16)/255,b=parseInt(notation.substring(4,6),16)/255;if(notation.length>=8){return[r,g,b,parseInt(notation.substring(6,8),16)/255]}return[r,g,b]},hueToColorComponent=(p,q,t)=>(t<0&&(t+=1),t>1&&(t-=1),t<1/6?p+6*(q-p)*t:t<.5?q:t<2/3?p+(q-p)*(2/3-t)*6:p),hslToRgb=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain H, S and L values");const h=values[0],s=values[1],l=values[2];let r=l,g=l,b=l;if(0!==s){const q=l<.5?l*(1+s):l+s-l*s,p=2*l-q;r=hueToColorComponent(p,q,h+1/3),g=hueToColorComponent(p,q,h),b=hueToColorComponent(p,q,h-1/3)}if(values.length>3){return[r,g,b,values[3]]}return[r,g,b]},hsvToRgb=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain H, S and V values");const h=values[0],s=values[1],v=values[2];let r=0,g=0,b=0;const i=Math.floor(6*h),f=6*h-i,p=v*(1-s),q=v*(1-f*s),t=v*(1-(1-f)*s);switch(i%6){case 0:r=v,g=t,b=p;break;case 1:r=q,g=v,b=p;break;case 2:r=p,g=v,b=t;break;case 3:r=p,g=q,b=v;break;case 4:r=t,g=p,b=v;break;case 5:r=v,g=p,b=q}if(values.length>3){return[r,g,b,values[3]]}return[r,g,b]},rgbToHex=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=255*values[0],g=255*values[1],b=255*values[2];let s=`#${Number(16777216+65536*r+256*g+b).toString(16).substring(1,7)}`;return values.length>3&&(s+=Number(255*values[3]).toString(16)),s},rgbToHsl=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=values[0],g=values[1],b=values[2],max=Math.max(r,g,b),min=Math.min(r,g,b);let h,s;const l=(max+min)/2;if(max===min)h=s=0;else{const d=max-min;switch(s=l>.5?d/(2-max-min):d/(max+min),max){case r:h=(g-b)/d+(g3){return[h,s,l,values[3]]}return[h,s,l]},rgbToHsv=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=values[0],g=values[1],b=values[2],max=Math.max(r,g,b),min=Math.min(r,g,b);let h;const v=max,d=max-min,s=0===max?0:d/max;if(max===min)h=0;else{switch(max){case r:h=(g-b)/d+(g3){return[h,s,v,values[3]]}return[h,s,v]},getPointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=getPointType(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>{if(0===points.length)return 0;if(polygon.points.length<3)return 0;measureArea$1(polygon)<0&&(polygon=reverse$3(polygon));return points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0},isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),equals$3=(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices=vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours)),reverse$2=slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges=slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges};class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||(!(0!==o1||!onSegment(p1,p2,q1))||(!(0!==o2||!onSegment(p1,q2,q1))||(!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2)))))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles},earcutLinked=(ear,triangles,dim,minX,minY,invSize,pass)=>{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1,minIndex=(list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuepart.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=minIndex(parents[j],(p=>children[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}const toPolygons=slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),data=vertices.flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=triangulate(data,holesIndex);for(let i=0;i{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)};var index$2=Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:equals$3,fromGeom2:fromGeom2,fromVertices:fromVertices,isA:isA,reverse:reverse$2,toEdges:toEdges,toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:toPolygons,toString:slice=>{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:transform$3,validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i[0,1,0],direction$1=line=>{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]},intersectPointOfLines=(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)};var index$1=Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:create$1,direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:intersectPointOfLines,origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];if(Number.isNaN(x)){x=origin$1(line)[0]}return x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};var index=Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$3=new WeakMap,measureArea=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?0:isA$5(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=toSides(geometry).reduce(((area,side)=>area+(side[0][0]*side[1][1]-side[0][1]*side[1][0])),0),area*=.5,cache$3.set(geometry,area),area)})(geometry):isA$3(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=toPolygons$1(geometry).reduce(((area,polygon)=>area+measureArea$2(polygon)),0),cache$3.set(geometry,area),area)})(geometry):isA(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=0,geometry.contours.forEach((contour=>{area+=measureArea$2(create$7(contour))})),cache$3.set(geometry,area),area)})(geometry):0));return 1===results.length?results[0]:results},measureAggregateArea=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("measureAggregateArea: no geometries supplied");const areas=measureArea(geometries);if(1===geometries.length)return areas;return areas.reduce(((result,area)=>result+area),0)},cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},measureAggregateBoundingBox=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("measureAggregateBoundingBox: no geometries supplied");const bounds=measureBoundingBox(geometries);if(1===geometries.length)return bounds;const result=[[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],[-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE]];return bounds.reduce(((result,item)=>result=[min$2(result[0],result[0],item[0]),max$2(result[1],result[1],item[1])]),result)},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{if(0===(geometries=flatten(geometries)).length)throw new Error("measureAggregateEpsilon: no geometries supplied");const bounds=measureAggregateBoundingBox(geometries);let dimensions=0;return dimensions=geometries.reduce(((dimensions,geometry)=>isA$2(geometry)||isA$5(geometry)?Math.max(dimensions,2):isA$3(geometry)?Math.max(dimensions,3):0),dimensions),calculateEpsilonFromBounds(bounds,dimensions)},cache$1=new WeakMap,measureVolume=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$3(geometry)?(geometry=>{let volume=cache$1.get(geometry);return volume||(volume=toPolygons$1(geometry).reduce(((volume,polygon)=>volume+measureSignedVolume(polygon)),0),cache$1.set(geometry,volume),volume)})(geometry):0));return 1===results.length?results[0]:results},measureAggregateVolume=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("measureAggregateVolume: no geometries supplied");const volumes=measureVolume(geometries);if(1===geometries.length)return volumes;return volumes.reduce(((result,volume)=>result+volume),0)},cache=new WeakMap,measureCached=(geometry,measureFn)=>{let boundingSphere=cache.get(geometry);return boundingSphere||(boundingSphere=measureFn(geometry),0===boundingSphere.length&&(boundingSphere[0]=[0,0,0],boundingSphere[1]=0),cache.set(geometry,boundingSphere),boundingSphere)},measureBoundingSphereOfPoints=points=>{const centroid=[0,0,0];let radius=0;if(points.length>0){let numPoints=0;const temp=[0,0,0];points.forEach((point=>{add$1(centroid,centroid,fromVec2(temp,point,0)),numPoints++})),scale$3(centroid,centroid,1/numPoints),points.forEach((point=>{radius=Math.max(radius,squaredDistance(centroid,point))})),radius=Math.sqrt(radius)}return[centroid,radius]},measureBoundingSphereOfPath2=points=>measureBoundingSphereOfPoints(toPoints$1(points)),measureBoundingSphereOfGeom2=geometry=>measureBoundingSphereOfPoints(toPoints$3(geometry)),measureBoundingSphereOfGeom3=geometry=>{const centroid=[0,0,0];let radius=0;const polygons=toPolygons$1(geometry);if(polygons.length>0){let numVertices=0;polygons.forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{add$1(centroid,centroid,vertex),numVertices++}))})),scale$3(centroid,centroid,1/numVertices),polygons.forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{radius=Math.max(radius,squaredDistance$1(centroid,vertex))}))})),radius=Math.sqrt(radius)}return[centroid,radius]},measureBoundingSphereOfSlice=geometry=>{const centroid=[0,0,0];let radius=0,numVertices=0;return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(centroid,centroid,vertex),numVertices++}))})),numVertices>0&&(scale$3(centroid,centroid,1/numVertices),geometry.contours.forEach((contour=>{contour.forEach((vertex=>{radius=Math.max(radius,squaredDistance$1(centroid,vertex))}))})),radius=Math.sqrt(radius)),[centroid,radius]},measureBoundingSphere=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?measureCached(geometry,measureBoundingSphereOfPath2):isA$5(geometry)?measureCached(geometry,measureBoundingSphereOfGeom2):isA$3(geometry)?measureCached(geometry,measureBoundingSphereOfGeom3):isA(geometry)?measureCached(geometry,measureBoundingSphereOfSlice):[[0,0,0],0]));return 1===results.length?results[0]:results},measureCenter=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>{const bounds=measureBoundingBox(geometry);return[bounds[0][0]+(bounds[1][0]-bounds[0][0])/2,bounds[0][1]+(bounds[1][1]-bounds[0][1])/2,bounds[0][2]+(bounds[1][2]-bounds[0][2])/2]}));return 1===results.length?results[0]:results},cacheOfCenterOfMass=new WeakMap,measureCenterOfMass=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$5(geometry)?(geometry=>{let centerOfMass=cacheOfCenterOfMass.get(geometry);if(void 0!==centerOfMass)return centerOfMass;const sides=toSides(geometry);let area=0,x=0,y=0;if(sides.length>0){for(let i=0;i{let centerOfMass=cacheOfCenterOfMass.get(geometry);if(void 0!==centerOfMass)return centerOfMass;centerOfMass=[0,0,0];const polygons=toPolygons$1(geometry);if(0===polygons.length)return centerOfMass;let totalVolume=0;const vector=[0,0,0];return polygons.forEach((polygon=>{const vertices=polygon.vertices;for(let i=0;i{const results=(geometries=flatten(geometries)).map((geometry=>{const boundingBox=measureBoundingBox(geometry);return[boundingBox[1][0]-boundingBox[0][0],boundingBox[1][1]-boundingBox[0][1],boundingBox[1][2]-boundingBox[0][2]]}));return 1===results.length?results[0]:results},measureEpsilon=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results},isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGT=(value,constant)=>Number.isFinite(value)&&value>constant,isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGT(radius,0))throw new Error("radius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS*EPS)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps));point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})},cuboid=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0,0],size:[2,2,2]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of width, depth and height values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1]||0===size[2])return create$8();return create$8([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((info=>{const vertices=info[0].map((i=>[center[0]+size[0]/2*(2*!!(1&i)-1),center[1]+size[1]/2*(2*!!(2&i)-1),center[2]+size[2]/2*(2*!!(4&i)-1)]));return create$7(vertices)})))},cube=options=>{let{center:center,size:size}=Object.assign({},{center:[0,0,0],size:2},options);if(!isGTE(size,0))throw new Error("size must be positive");return size=[size,size,size],cuboid({center:center,size:size})},cylinderElliptic=options=>{const defaults={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:TAU,segments:32};let{center:center,height:height,startRadius:startRadius,startAngle:startAngle,endRadius:endRadius,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGT(height,0))throw new Error("height must be greater then zero");if(!isNumberArray(startRadius,2))throw new Error("startRadius must be an array of X and Y values");if(!startRadius.every((n=>n>=0)))throw new Error("startRadius values must be positive");if(!isNumberArray(endRadius,2))throw new Error("endRadius must be an array of X and Y values");if(!endRadius.every((n=>n>=0)))throw new Error("endRadius values must be positive");if(endRadius.every((n=>0===n))&&startRadius.every((n=>0===n)))throw new Error("at least one radius must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(startRadius[0],startRadius[1],endRadius[0],endRadius[1]),minAngle=Math.acos((minRadius*minRadius+minRadius*minRadius-EPS*EPS)/(2*minRadius*minRadius));if(rotation{const angle=slice*rotation+startAngle;return scale$3(v1,axisX,radius[0]*cos(angle)),scale$3(v2,axisY,radius[1]*sin(angle)),add$1(v1,v1,v2),scale$3(v3,ray,stack),add$1(v3,v3,start),add$1([0,0,0],v1,v3)},fromVertices=(...vertices)=>{const newVertices=vertices.map((vertex=>add$1([0,0,0],vertex,center)));return create$7(newVertices)},polygons=[];for(let i=0;i0&&startRadius[1]>0&&polygons.push(fromVertices(start,genVertex(0,t1,startRadius),genVertex(0,t0,startRadius))),(startRadius[0]>0||startRadius[1]>0)&&polygons.push(fromVertices(genVertex(0,t0,startRadius),genVertex(0,t1,startRadius),genVertex(1,t0,endRadius))),endRadius[0]>0&&endRadius[1]>0&&polygons.push(fromVertices(end,genVertex(1,t0,endRadius),genVertex(1,t1,endRadius))),(endRadius[0]>0||endRadius[1]>0)&&polygons.push(fromVertices(genVertex(1,t0,endRadius),genVertex(0,t1,startRadius),genVertex(1,t1,endRadius))))}rotation{const{center:center,height:height,radius:radius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},options);if(!isGTE(radius,0))throw new Error("radius must be positive");if(0===height||0===radius)return create$8();return cylinderElliptic({center:center,height:height,startRadius:[radius,radius],endRadius:[radius,radius],segments:segments})},ellipsoid=options=>{const{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(radius,3))throw new Error("radius must be an array of X, Y and Z values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===radius[0]||0===radius[1]||0===radius[2])return create$8();const xVector=scale$3([0,0,0],normalize$1([0,0,0],axes[0]),radius[0]),yVector=scale$3([0,0,0],normalize$1([0,0,0],axes[1]),radius[1]),zVector=scale$3([0,0,0],normalize$1([0,0,0],axes[2]),radius[2]),qSegments=Math.round(segments/4);let prevCylinderVertex;const polygons=[],p1=[0,0,0],p2=[0,0,0];for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(p1,xVector,cos(angle)),scale$3(p2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch;for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);if(slice2>0){let vertex,vertices=[];vertex=subtract$3([0,0,0],scale$3(p1,prevCylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),vertex=subtract$3([0,0,0],scale$3(p1,cylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),slice2{const defaults={points:[],faces:[],colors:void 0,orientation:"outward"},{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},defaults,options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)},geodesicSphere=options=>{let{radius:radius,frequency:frequency}=Object.assign({},{radius:1,frequency:6},options);if(!isGTE(radius,0))throw new Error("radius must be positive");if(!isGTE(frequency,6))throw new Error("frequency must be six or more");if(0===radius)return create$8();frequency=Math.floor(frequency/6);const ci=[[.850651,0,-.525731],[.850651,-0,.525731],[-.850651,-0,.525731],[-.850651,0,-.525731],[0,-.525731,.850651],[0,.525731,.850651],[0,.525731,-.850651],[0,-.525731,-.850651],[-.525731,-.850651,-0],[.525731,-.850651,-0],[.525731,.850651,0],[-.525731,.850651,0]],ti=[[0,9,1],[1,10,0],[6,7,0],[10,6,0],[7,9,0],[5,1,4],[4,1,9],[5,10,1],[2,8,3],[3,11,2],[2,5,4],[4,8,2],[2,11,5],[3,7,6],[6,11,3],[8,7,3],[9,8,4],[11,10,5],[10,11,6],[8,9,7]],geodesicSubDivide=(p,frequency,offset)=>{const p1=p[0],p2=p[1],p3=p[2];let n=offset;const c=[],f=[];for(let i=0;i{const _f=1-f,c=[];for(let i=0;i<3;i++)c[i]=a[i]*_f+b[i]*f;return c};let vertices=[],faces=[],offset=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},polygon=options=>{const{points:points,paths:paths}=Object.assign({},{points:[],paths:[]},options);if(!Array.isArray(points)||!Array.isArray(paths))throw new Error("points and paths must be arrays");let listOfPolys=points;Array.isArray(points[0])&&(Array.isArray(points[0][0])||(listOfPolys=[points])),listOfPolys.forEach(((list,i)=>{if(!Array.isArray(list))throw new Error("list of points "+i+" must be an array");if(list.length<3)throw new Error("list of points "+i+" must contain three or more points");list.forEach(((point,j)=>{if(!Array.isArray(point))throw new Error("list of points "+i+", point "+j+" must be an array");if(point.length<2)throw new Error("list of points "+i+", point "+j+" must contain by X and Y values")}))}));let listOfPaths=paths;if(0===paths.length){let count=0;listOfPaths=listOfPolys.map((list=>list.map((point=>count++))))}const allPoints=[];listOfPolys.forEach((list=>list.forEach((point=>allPoints.push(point)))));const outlines=[];return listOfPaths.forEach((path=>{const setOfPoints=path.map((index=>allPoints[index]));outlines.push(setOfPoints)})),create$a(outlines)},rectangle=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])},createCorners=(center,size,radius,segments,slice,positive)=>{const pitch=TAU/4*slice/segments,cosPitch=cos(pitch),sinPitch=sin(pitch),layerSegments=segments-slice;let layerRadius=radius*cosPitch,layerOffset=size[2]-(radius-radius*sinPitch);positive||(layerOffset=radius-radius*sinPitch-size[2]),layerRadius=layerRadius>EPS?layerRadius:0;const corner0=add$1([0,0,0],center,[size[0]-radius,size[1]-radius,layerOffset]),corner1=add$1([0,0,0],center,[radius-size[0],size[1]-radius,layerOffset]),corner2=add$1([0,0,0],center,[radius-size[0],radius-size[1],layerOffset]),corner3=add$1([0,0,0],center,[size[0]-radius,radius-size[1],layerOffset]),corner0Vertices=[],corner1Vertices=[],corner2Vertices=[],corner3Vertices=[];for(let i=0;i<=layerSegments;i++){const point2d=fromAngleRadians([0,0],layerSegments>0?TAU/4*i/layerSegments:0);scale$1(point2d,point2d,layerRadius);const point3d=fromVec2([0,0,0],point2d);corner0Vertices.push(add$1([0,0,0],corner0,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner1Vertices.push(add$1([0,0,0],corner1,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner2Vertices.push(add$1([0,0,0],corner2,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner3Vertices.push(add$1([0,0,0],corner3,point3d))}return positive?[corner0Vertices,corner1Vertices,corner2Vertices,corner3Vertices]:(corner0Vertices.reverse(),corner1Vertices.reverse(),corner2Vertices.reverse(),corner3Vertices.reverse(),[corner3Vertices,corner2Vertices,corner1Vertices,corner0Vertices])},stitchCorners=(previousCorners,currentCorners)=>{const polygons=[];for(let i=0;i{const polygons=[];for(let i=0;i{bottomCorners=(bottomCorners=[bottomCorners[3],bottomCorners[2],bottomCorners[1],bottomCorners[0]]).map((corner=>corner.slice().reverse()));const bottomVertices=[];bottomCorners.forEach((corner=>{corner.forEach((vertex=>bottomVertices.push(vertex)))}));const topVertices=[];topCorners.forEach((corner=>{corner.forEach((vertex=>topVertices.push(vertex)))}));const polygons=[];for(let i=0;i{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0,0],size:[2,2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of X, Y and Z values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1]||0===size[2])return create$8();if(0===roundRadius)return cuboid({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS||roundRadius>size[2]-EPS)throw new Error("roundRadius must be smaller then the radius of all dimensions");segments=Math.floor(segments/4);let prevCornersPos=null,prevCornersNeg=null,polygons=[];for(let slice=0;slice<=segments;slice++){const cornersPos=createCorners(center,size,roundRadius,segments,slice,!0),cornersNeg=createCorners(center,size,roundRadius,segments,slice,!1);if(0===slice&&(polygons=polygons.concat(stitchSides(cornersNeg,cornersPos))),prevCornersPos&&(polygons=polygons.concat(stitchCorners(prevCornersPos,cornersPos),stitchWalls(prevCornersPos,cornersPos))),prevCornersNeg&&(polygons=polygons.concat(stitchCorners(prevCornersNeg,cornersNeg),stitchWalls(prevCornersNeg,cornersNeg))),slice===segments){let vertices=cornersPos.map((corner=>corner[0]));polygons.push(create$7(vertices)),vertices=cornersNeg.map((corner=>corner[0])),polygons.push(create$7(vertices))}prevCornersPos=cornersPos,prevCornersNeg=cornersNeg}return create$8(polygons)},roundedCylinder=options=>{const{center:center,height:height,radius:radius,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,roundRadius:.2,segments:32},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGTE(height,0))throw new Error("height must be positive");if(!isGTE(radius,0))throw new Error("radius must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(roundRadius>radius)throw new Error("roundRadius must be smaller then the radius");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===height||0===radius)return create$8();if(0===roundRadius)return cylinder({center:center,height:height,radius:radius});const start=[0,0,-height/2],end=[0,0,height/2],direction=subtract$3([0,0,0],end,start);if(2*roundRadius>length$2(direction)-EPS)throw new Error("height must be larger than twice roundRadius");let defaultNormal;defaultNormal=Math.abs(direction[0])>Math.abs(direction[1])?fromValues$3(0,1,0):fromValues$3(1,0,0);const zVector=scale$3([0,0,0],normalize$1([0,0,0],direction),roundRadius),xVector=scale$3([0,0,0],normalize$1([0,0,0],cross$1([0,0,0],zVector,defaultNormal)),radius),yVector=scale$3([0,0,0],normalize$1([0,0,0],cross$1([0,0,0],xVector,zVector)),radius);add$1(start,start,zVector),subtract$3(end,end,zVector);const qSegments=Math.floor(.25*segments),fromVertices=vertices=>{const newVertices=vertices.map((vertex=>add$1(vertex,vertex,center)));return create$7(newVertices)},polygons=[],v1=[0,0,0],v2=[0,0,0];let prevCylinderVertex;for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(v1,xVector,cos(angle)),scale$3(v2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch,vertex,vertices=[];vertices.push(add$1([0,0,0],start,cylinderVertex)),vertices.push(add$1([0,0,0],start,prevCylinderVertex)),vertices.push(add$1([0,0,0],end,prevCylinderVertex)),vertices.push(add$1([0,0,0],end,cylinderVertex)),polygons.push(fromVertices(vertices));for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);slice2>0&&(vertices=[],vertex=add$1([0,0,0],start,subtract$3(v1,scale$3(v1,prevCylinderVertex,prevCosPitch),scale$3(v2,zVector,prevSinPitch))),vertices.push(vertex),vertex=add$1([0,0,0],start,subtract$3(v1,scale$3(v1,cylinderVertex,prevCosPitch),scale$3(v2,zVector,prevSinPitch))),vertices.push(vertex),slice2{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1])return create$a();if(0===roundRadius)return rectangle({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS)throw new Error("roundRadius must be smaller then the radius of all dimensions");const cornerSegments=Math.floor(segments/4),corner0=add([0,0],center,[size[0]-roundRadius,size[1]-roundRadius]),corner1=add([0,0],center,[roundRadius-size[0],size[1]-roundRadius]),corner2=add([0,0],center,[roundRadius-size[0],roundRadius-size[1]]),corner3=add([0,0],center,[size[0]-roundRadius,roundRadius-size[1]]),corner0Points=[],corner1Points=[],corner2Points=[],corner3Points=[];for(let i=0;i<=cornerSegments;i++){const point=fromAngleRadians([0,0],TAU/4*i/cornerSegments);scale$1(point,point,roundRadius),corner0Points.push(add([0,0],corner0,point)),rotate$1(point,point,[0,0],TAU/4),corner1Points.push(add([0,0],corner1,point)),rotate$1(point,point,[0,0],TAU/4),corner2Points.push(add([0,0],corner2,point)),rotate$1(point,point,[0,0],TAU/4),corner3Points.push(add([0,0],corner3,point))}const points=corner0Points.concat(corner1Points,corner2Points,corner3Points);return create$a([points])},sphere=options=>{let{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius,radius],ellipsoid({center:center,radius:radius,segments:segments,axes:axes})},square=options=>{let{center:center,size:size}=Object.assign({},{center:[0,0],size:2},options);if(!isGTE(size,0))throw new Error("size must be positive");return size=[size,size],rectangle({center:center,size:size})},getPoints=(vertices,radius,startAngle,center)=>{const a=TAU/vertices,points=[];for(let i=0;i{let{center:center,vertices:vertices,outerRadius:outerRadius,innerRadius:innerRadius,density:density,startAngle:startAngle}=Object.assign({},{center:[0,0],vertices:5,outerRadius:1,innerRadius:0,density:2,startAngle:0},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGTE(vertices,2))throw new Error("vertices must be two or more");if(!isGT(outerRadius,0))throw new Error("outerRadius must be greater than zero");if(!isGTE(innerRadius,0))throw new Error("innerRadius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be greater than zero");if(vertices=Math.floor(vertices),density=Math.floor(density),startAngle%=TAU,0===innerRadius){if(!isGTE(density,2))throw new Error("density must be two or more");innerRadius=outerRadius*((vertices,density)=>vertices>0&&density>1&&density{const{origin:origin,normal:normal}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},options);if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const planeOfMirror=fromNormalAndPoint([0,0,0,0],normal,origin);if(Number.isNaN(planeOfMirror[0]))throw new Error("the given origin and normal do not define a proper plane");const matrix=mirrorByPlane([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],planeOfMirror),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},mirrorX=(...objects)=>mirror({normal:[1,0,0]},objects),mirrorY=(...objects)=>mirror({normal:[0,1,0]},objects),mirrorZ=(...objects)=>mirror({normal:[0,0,1]},objects),gcd=(a,b)=>a===b?a:a{const multiple=newLength/edges.length;if(1===multiple)return edges;const divisor=fromValues$3(multiple,multiple,multiple),newEdges=[];return edges.forEach((edge=>{const increment=subtract$3([0,0,0],edge[1],edge[0]);divide$1(increment,increment,divisor);let prev=edge[0];for(let i=1;i<=multiple;++i){const next=add$1([0,0,0],prev,increment);newEdges.push([prev,next]),prev=next}})),newEdges},EPSAREA=EPS*EPS/2*Math.sin(Math.PI/3),extrudeWalls=(slice0,slice1)=>{let edges0=toEdges(slice0),edges1=toEdges(slice1);if(edges0.length!==edges1.length){const newLength=(a=edges0.length,b=edges1.length,a*b/gcd(a,b));newLength!==edges0.length&&(edges0=repartitionEdges(newLength,edges0)),newLength!==edges1.length&&(edges1=repartitionEdges(newLength,edges1))}var a,b;const walls=[];return edges0.forEach(((edge0,i)=>{const edge1=edges1[i],poly0=create$7([edge0[0],edge0[1],edge1[1]]),poly0area=measureArea$2(poly0);Number.isFinite(poly0area)&&poly0area>EPSAREA&&walls.push(poly0);const poly1=create$7([edge0[0],edge1[1],edge1[0]]),poly1area=measureArea$2(poly1);Number.isFinite(poly1area)&&poly1area>EPSAREA&&walls.push(poly1)})),walls},defaultCallback=(progress,index,base)=>{let baseSlice=null;return isA$5(base)&&(baseSlice=fromGeom2(base)),isA$4(base)&&(baseSlice=fromVertices(toVertices$1(base))),0===progress||1===progress?transform$3(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[0,0,progress]),baseSlice):null},extrudeFromSlices=(options,base)=>{const defaults={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,callback:defaultCallback},{numberOfSlices:numberOfSlices,capStart:capStart,capEnd:capEnd,close:close,callback:generate}=Object.assign({},defaults,options);if(numberOfSlices<2)throw new Error("numberOfSlices must be 2 or more");const sMax=numberOfSlices-1;let startSlice=null,endSlice=null,prevSlice=null,polygons=[];for(let s=0;s{const defaults={segments:12,startAngle:0,angle:TAU,overflow:"cap"};let{segments:segments,startAngle:startAngle,angle:angle,overflow:overflow}=Object.assign({},defaults,options);if(segments<3)throw new Error("segments must be greater then 3");startAngle=Math.abs(startAngle)>TAU?startAngle%TAU:startAngle,angle=Math.abs(angle)>TAU?angle%TAU:angle;let endAngle=startAngle+angle;if(endAngle=Math.abs(endAngle)>TAU?endAngle%TAU:endAngle,endAnglesegments*anglePerSegment&&segments++}let shapeSides=toSides(geometry);if(0===shapeSides.length)return geometry;let sliceGeometry=geometry;const pointsWithNegativeX=shapeSides.filter((s=>s[0][0]<0)),pointsWithPositiveX=shapeSides.filter((s=>s[0][0]>=0));pointsWithNegativeX.length>0&&pointsWithPositiveX.length>0&&"cap"===overflow&&(pointsWithNegativeX.length>pointsWithPositiveX.length?(shapeSides=shapeSides.map((side=>{let point0=side[0],point1=side[1];return point0=[Math.min(point0[0],0),point0[1]],point1=[Math.min(point1[0],0),point1[1]],[point0,point1]})),sliceGeometry=reverse$5(fromSides(shapeSides)),sliceGeometry=mirrorX(sliceGeometry)):pointsWithPositiveX.length>=pointsWithNegativeX.length&&(shapeSides=shapeSides.map((side=>{let point0=side[0],point1=side[1];return point0=[Math.max(point0[0],0),point0[1]],point1=[Math.max(point1[0],0),point1[1]],[point0,point1]})),sliceGeometry=fromSides(shapeSides)));const rotationPerSlice=totalRotation/segments,isCapped=Math.abs(totalRotation){let Zrotation=rotationPerSlice*index+startAngle;return totalRotation===TAU&&index===segments&&(Zrotation=startAngle),multiply$1(matrix,fromZRotation(matrix,Zrotation),fromXRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],TAU/4)),transform$3(matrix,base)}};const output=extrudeFromSlices(options,baseSlice);return geometry.color&&(output.color=geometry.color),output},rotate=(angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},rotateX=(angle,...objects)=>rotate([angle,0,0],objects),rotateY=(angle,...objects)=>rotate([0,angle,0],objects),rotateZ=(angle,...objects)=>rotate([0,0,angle],objects),translate=(offset,...objects)=>{if(!Array.isArray(offset))throw new Error("offset must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(offset=offset.slice();offset.length<3;)offset.push(0);const matrix=fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offset),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},translateX=(offset,...objects)=>translate([offset,0,0],objects),translateY=(offset,...objects)=>translate([0,offset,0],objects),translateZ=(offset,...objects)=>translate([0,0,offset],objects),torus=options=>{const defaults={innerRadius:1,innerSegments:32,outerRadius:4,outerSegments:32,innerRotation:0,startAngle:0,outerRotation:TAU},{innerRadius:innerRadius,innerSegments:innerSegments,outerRadius:outerRadius,outerSegments:outerSegments,innerRotation:innerRotation,startAngle:startAngle,outerRotation:outerRotation}=Object.assign({},defaults,options);if(!isGT(innerRadius,0))throw new Error("innerRadius must be greater than zero");if(!isGTE(innerSegments,3))throw new Error("innerSegments must be three or more");if(!isGT(outerRadius,0))throw new Error("outerRadius must be greater than zero");if(!isGTE(outerSegments,3))throw new Error("outerSegments must be three or more");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGT(outerRotation,0))throw new Error("outerRotation must be greater than zero");if(innerRadius>=outerRadius)throw new Error("inner circle is two large to rotate about the outer circle");let innerCircle=circle({radius:innerRadius,segments:innerSegments});0!==innerRotation&&(innerCircle=rotate([0,0,innerRotation],innerCircle)),innerCircle=translate([outerRadius,0],innerCircle);return extrudeRotate({startAngle:startAngle,angle:outerRotation,segments:outerSegments},innerCircle)},solveAngleFromSSS=(a,b,c)=>Math.acos((a*a+b*b-c*c)/(2*a*b)),solveSAS=values=>{const c=values[0],B=values[1],a=values[2],b=((a,C,b)=>C>NEPS?Math.sqrt(a*a+b*b-2*a*b*Math.cos(C)):Math.sqrt((a-b)*(a-b)+a*b*C*C*(1-C*C/12)))(c,B,a),A=solveAngleFromSSS(b,c,a),C=Math.PI-A-B;return createTriangle(A,B,C,a,b,c)},createTriangle=(A,B,C,a,b,c)=>{const p0=fromValues$2(0,0),p1=fromValues$2(c,0),p2=fromValues$2(a,0);return add(p2,rotate$1(p2,p2,[0,0],Math.PI-B),p1),create$a([[p0,p1,p2]])},triangle=options=>{let{type:type,values:values}=Object.assign({},{type:"SSS",values:[1,1,1]},options);if("string"!=typeof type)throw new Error("triangle type must be a string");if(type=type.toUpperCase(),"A"!==type[0]&&"S"!==type[0]||"A"!==type[1]&&"S"!==type[1]||"A"!==type[2]&&"S"!==type[2])throw new Error("triangle type must contain three letters; A or S");if(!isNumberArray(values,3))throw new Error("triangle values must contain three values");if(!values.every((n=>n>0)))throw new Error("triangle values must be greater than zero");switch(type){case"AAA":return(angles=>{if(Math.abs(angles[0]+angles[1]+angles[2]-Math.PI)>NEPS)throw new Error("AAA triangles require angles that sum to PI");const A=angles[0],B=angles[1],C=Math.PI-A-B,a=1/Math.sin(C)*Math.sin(A),b=1/Math.sin(C)*Math.sin(B);return createTriangle(A,B,C,a,b,1)})(values);case"AAS":return(values=>{const A=values[0],B=values[1],C=Math.PI+NEPS-A-B;if(C{const A=values[0],B=values[2],C=Math.PI+NEPS-A-B;if(C{const c=values[0],a=values[1],C=values[2],A=Math.asin(a*Math.sin(C)/c),B=Math.PI-A-C,b=c/Math.sin(C)*Math.sin(B);return createTriangle(A,B,C,a,b,c)})(values);case"SSS":return(lengths=>{const a=lengths[1],b=lengths[2],c=lengths[0];if(a+b<=c||b+c<=a||c+a<=b)throw new Error("SSS triangle is incorrect, as the longest side is longer than the sum of the other sides");const A=solveAngleFromSSS(b,c,a),B=solveAngleFromSSS(c,a,b),C=Math.PI-A-B;return createTriangle(A,B,C,a,b,c)})(values);default:throw new Error("invalid triangle type, try again")}},simplex={height:14,32:[16],33:[10,5,21,5,7,void 0,5,2,4,1,5,0,6,1,5,2],34:[16,4,21,4,14,void 0,12,21,12,14],35:[21,11,25,4,-7,void 0,17,25,10,-7,void 0,4,12,18,12,void 0,3,6,17,6],36:[20,8,25,8,-4,void 0,12,25,12,-4,void 0,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],37:[24,21,21,3,0,void 0,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,void 0,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7],38:[26,23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2],39:[10,5,19,4,20,5,21,6,20,6,18,5,16,4,15],40:[14,11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7],41:[14,3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7],42:[16,8,21,8,9,void 0,3,18,13,12,void 0,13,18,3,12],43:[26,13,18,13,0,void 0,4,9,22,9],44:[10,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],45:[26,4,9,22,9],46:[10,5,2,4,1,5,0,6,1,5,2],47:[22,20,25,2,-7],48:[20,9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21],49:[20,6,17,8,18,11,21,11,0],50:[20,4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0],51:[20,5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],52:[20,13,21,3,7,18,7,void 0,13,21,13,0],53:[20,15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],54:[20,16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7],55:[20,17,21,7,0,void 0,3,21,17,21],56:[20,8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21],57:[20,16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3],58:[10,5,14,4,13,5,12,6,13,5,14,void 0,5,2,4,1,5,0,6,1,5,2],59:[10,5,14,4,13,5,12,6,13,5,14,void 0,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],60:[24,20,18,4,9,20,0],61:[26,4,12,22,12,void 0,4,6,22,6],62:[24,4,18,20,9,4,0],63:[18,3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,void 0,9,2,8,1,9,0,10,1,9,2],64:[27,18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,void 0,12,16,10,14,9,11,9,8,10,6,11,5,void 0,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,void 0,19,16,18,8,18,6,19,5],65:[18,9,21,1,0,void 0,9,21,17,0,void 0,4,7,14,7],66:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,void 0,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0],67:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5],68:[21,4,21,4,0,void 0,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0],69:[19,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11,void 0,4,0,17,0],70:[18,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11],71:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,void 0,13,8,18,8],72:[22,4,21,4,0,void 0,18,21,18,0,void 0,4,11,18,11],73:[8,4,21,4,0],74:[16,12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7],75:[21,4,21,4,0,void 0,18,21,4,7,void 0,9,12,18,0],76:[17,4,21,4,0,void 0,4,0,16,0],77:[24,4,21,4,0,void 0,4,21,12,0,void 0,20,21,12,0,void 0,20,21,20,0],78:[22,4,21,4,0,void 0,4,21,18,0,void 0,18,21,18,0],79:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21],80:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10],81:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,void 0,12,4,18,-2],82:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,void 0,11,11,18,0],83:[20,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],84:[16,8,21,8,0,void 0,1,21,15,21],85:[22,4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21],86:[18,1,21,9,0,void 0,17,21,9,0],87:[24,2,21,7,0,void 0,12,21,7,0,void 0,12,21,17,0,void 0,22,21,17,0],88:[20,3,21,17,0,void 0,17,21,3,0],89:[18,1,21,9,11,9,0,void 0,17,21,9,11],90:[20,17,21,3,0,void 0,3,21,17,21,void 0,3,0,17,0],91:[14,4,25,4,-7,void 0,5,25,5,-7,void 0,4,25,11,25,void 0,4,-7,11,-7],92:[14,0,21,14,-3],93:[14,9,25,9,-7,void 0,10,25,10,-7,void 0,3,25,10,25,void 0,3,-7,10,-7],94:[16,6,15,8,18,10,15,void 0,3,12,8,17,13,12,void 0,8,17,8,0],95:[16,0,-2,16,-2],96:[10,6,21,5,20,4,18,4,16,5,15,6,16,5,17],97:[19,15,14,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],98:[19,4,21,4,0,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],99:[18,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],100:[19,15,21,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],101:[18,3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],102:[12,10,21,8,21,6,20,5,17,5,0,void 0,2,14,9,14],103:[19,15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],104:[19,4,21,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],105:[8,3,21,4,20,5,21,4,22,3,21,void 0,4,14,4,0],106:[10,5,21,6,20,7,21,6,22,5,21,void 0,6,14,6,-3,5,-6,3,-7,1,-7],107:[17,4,21,4,0,void 0,14,14,4,4,void 0,8,8,15,0],108:[8,4,21,4,0],109:[30,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0,void 0,15,10,18,13,20,14,23,14,25,13,26,10,26,0],110:[19,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],111:[19,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14],112:[19,4,14,4,-7,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],113:[19,15,14,15,-7,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],114:[13,4,14,4,0,void 0,4,8,5,11,7,13,9,14,12,14],115:[17,14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3],116:[12,5,21,5,4,6,1,8,0,10,0,void 0,2,14,9,14],117:[19,4,14,4,4,5,1,7,0,10,0,12,1,15,4,void 0,15,14,15,0],118:[16,2,14,8,0,void 0,14,14,8,0],119:[22,3,14,7,0,void 0,11,14,7,0,void 0,11,14,15,0,void 0,19,14,15,0],120:[17,3,14,14,0,void 0,14,14,3,0],121:[16,2,14,8,0,void 0,14,14,8,0,6,-4,4,-6,2,-7,1,-7],122:[17,14,14,3,0,void 0,3,14,14,14,void 0,3,0,14,0],123:[14,9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,void 0,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,void 0,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7],124:[8,4,25,4,-7],125:[14,5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,void 0,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,void 0,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7],126:[24,3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,void 0,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]},defaultsVectorParams$1={xOffset:0,yOffset:0,font:simplex,height:14,extrudeOffset:0},vectorChar=(options,text)=>{const{xOffset:xOffset,yOffset:yOffset,font:font,height:height,extrudeOffset:extrudeOffset}=Object.assign({},defaultsVectorParams$1,options);if("string"!=typeof text||1!==text.length)throw new Error("text must be a single character");let code=text.charCodeAt(0);code&&font[code]||(code=63);const glyph=[].concat(font[code]),ratio=(height-extrudeOffset)/font.height,extrudeYOffset=extrudeOffset/2,width=glyph.shift()*ratio,paths=[];let polyline=[];for(let i=0,il=glyph.length;i{const{x:x,y:y}=Object.assign({x:0,y:0},options);return identity(matrix),translate$1(matrix,matrix,[x,y,0]),line.chars=line.chars.map((vchar=>(vchar.paths=vchar.paths.map((path=>transform$5(matrix,path))),vchar))),line},vectorText=(options,text)=>{const{xOffset:xOffset,yOffset:yOffset,font:font,height:height,align:align,extrudeOffset:extrudeOffset,lineSpacing:lineSpacing,letterSpacing:letterSpacing}=Object.assign({},defaultsVectorParams,options);if("string"!=typeof text)throw new Error("text must be a string");const extraLetterSpacing=height*letterSpacing;let maxWidth=0,line={width:0,height:0,chars:[]},lines=[];const pushLine=()=>{maxWidth=Math.max(maxWidth,line.width),line.chars.length&&lines.push(line),line={width:0,height:0,chars:[]}};let vchar,x=xOffset,y=yOffset;const il=text.length;for(let i=0;i{const diff=maxWidth-line.width;return"right"===align?translateLine({x:diff},line):"center"===align?translateLine({x:diff/2},line):line})),lines},degToRad=degrees=>.017453292519943295*degrees,radiusToSegments=(radius,minimumLength,minimumAngle)=>{const ss=minimumLength>0?radius*TAU/minimumLength:0,as=minimumAngle>0?TAU/minimumAngle:0;return Math.ceil(Math.max(ss,as,4))},radToDeg=radians=>57.29577951308232*radians,areAllShapesTheSameType=shapes=>{let previousType;for(const shape of shapes){let currentType=0;if(isA$5(shape)&&(currentType=1),isA$3(shape)&&(currentType=2),isA$2(shape)&&(currentType=3),previousType&¤tType!==previousType)return!1;previousType=currentType}return!0},DEFAULT_COMPARE=(a,b)=>a>b?1:a{const N=new Node$1(null,null);let l=N,r=N;for(;;){const cmp=comparator(i,t.key);if(cmp<0){if(null===t.left)break;if(comparator(i,t.left.key)<0){const y=t.left;if(t.left=y.right,y.right=t,null===(t=y).left)break}r.left=t,r=t,t=t.left}else{if(!(cmp>0))break;if(null===t.right)break;if(comparator(i,t.right.key)>0){const y=t.right;if(t.right=y.left,y.left=t,null===(t=y).right)break}l.right=t,l=t,t=t.right}}return l.right=t.left,r.left=t.right,t.left=N.right,t.right=N.left,t},insert=(i,data,t,comparator)=>{const node=new Node$1(i,data);if(null===t)return node.left=node.right=null,node;const cmp=comparator(i,(t=splay(i,t,comparator)).key);return cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>=0&&(node.right=t.right,node.left=t,t.right=null),node},split=(key,v,comparator)=>{let left=null,right=null;if(v){const cmp=comparator((v=splay(key,v,comparator)).key,key);0===cmp?(left=v.left,right=v.right):cmp<0?(right=v.right,v.right=null,left=v):(left=v.left,v.left=null,right=v)}return{left:left,right:right}},printRow=(root,prefix,isTail,out,printNode)=>{if(root){out(`${prefix}${isTail?"└── ":"├── "}${printNode(root)}\n`);const indent=prefix+(isTail?" ":"│ ");root.left&&printRow(root.left,indent,!1,out,printNode),root.right&&printRow(root.right,indent,!0,out,printNode)}};class Tree$1{constructor(comparator=DEFAULT_COMPARE){this._comparator=comparator,this._root=null,this._size=0}insert(key,data){return this._size++,this._root=insert(key,data,this._root,this._comparator),this._root}add(key,data){const node=new Node$1(key,data);null===this._root&&(node.left=node.right=null,this._size++,this._root=node);const comparator=this._comparator,t=splay(key,this._root,comparator),cmp=comparator(key,t.key);return 0===cmp?this._root=t:(cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>0&&(node.right=t.right,node.left=t,t.right=null),this._size++,this._root=node),this._root}remove(key){this._root=this._remove(key,this._root,this._comparator)}_remove(i,t,comparator){let x;if(null===t)return null;return 0===comparator(i,(t=splay(i,t,comparator)).key)?(null===t.left?x=t.right:(x=splay(i,t.left,comparator),x.right=t.right),this._size--,x):t}pop(){let node=this._root;if(node){for(;node.left;)node=node.left;return this._root=splay(node.key,this._root,this._comparator),this._root=this._remove(node.key,this._root,this._comparator),{key:node.key,data:node.data}}return null}findStatic(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return current;current=cmp<0?current.left:current.right}return null}find(key){return this._root&&(this._root=splay(key,this._root,this._comparator),0!==this._comparator(key,this._root.key))?null:this._root}contains(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return!0;current=cmp<0?current.left:current.right}return!1}forEach(visitor,ctx){let current=this._root;const Q=[];let done=!1;for(;!done;)null!==current?(Q.push(current),current=current.left):0!==Q.length?(current=Q.pop(),visitor.call(ctx,current),current=current.right):done=!0;return this}range(low,high,fn,ctx){const Q=[],compare=this._comparator;let cmp,node=this._root;for(;0!==Q.length||node;)if(node)Q.push(node),node=node.left;else{if(node=Q.pop(),cmp=compare(node.key,high),cmp>0)break;if(compare(node.key,low)>=0&&fn.call(ctx,node))return this;node=node.right}return this}keys(){const keys=[];return this.forEach((({key:key})=>keys.push(key))),keys}values(){const values=[];return this.forEach((({data:data})=>values.push(data))),values}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(index){let current=this._root,done=!1,i=0;const Q=[];for(;!done;)if(current)Q.push(current),current=current.left;else if(Q.length>0){if(current=Q.pop(),i===index)return current;i++,current=current.right}else done=!0;return null}next(d){let root=this._root,successor=null;if(d.right){for(successor=d.right;successor.left;)successor=successor.left;return successor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?(successor=root,root=root.left):root=root.right}return successor}prev(d){let root=this._root,predecessor=null;if(null!==d.left){for(predecessor=d.left;predecessor.right;)predecessor=predecessor.right;return predecessor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?root=root.left:(predecessor=root,root=root.right)}return predecessor}clear(){return this._root=null,this._size=0,this}toList(){return toList(this._root)}load(keys,values=[],presort=!1){let size=keys.length;const comparator=this._comparator;if(presort&&sort(keys,values,0,size-1,comparator),null===this._root)this._root=loadRecursive(keys,values,0,size),this._size=size;else{const mergedList=mergeLists(this.toList(),createList(keys,values),comparator);size=this._size+size,this._root=sortedListToBST({head:mergedList},0,size)}return this}isEmpty(){return null===this._root}size(){return this._size}root(){return this._root}toString(printNode=(n=>String(n.key))){const out=[];return printRow(this._root,"",!0,(v=>out.push(v)),printNode),out.join("")}update(key,newKey,newData){const comparator=this._comparator;let{left:left,right:right}=split(key,this._root,comparator);comparator(key,newKey)<0?right=insert(newKey,newData,right,comparator):left=insert(newKey,newData,left,comparator),this._root=((left,right,comparator)=>null===right?left:(null===left||((right=splay(left.key,right,comparator)).left=left),right))(left,right,comparator)}split(key){return split(key,this._root,this._comparator)}*[Symbol.iterator](){let n=this.minNode();for(;n;)yield n,n=this.next(n)}}const loadRecursive=(keys,values,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),key=keys[middle],data=values[middle],node=new Node$1(key,data);return node.left=loadRecursive(keys,values,start,middle),node.right=loadRecursive(keys,values,middle+1,end),node}return null},createList=(keys,values)=>{const head=new Node$1(null,null);let p=head;for(let i=0;i{let current=root;const Q=[];let done=!1;const head=new Node$1(null,null);let p=head;for(;!done;)current?(Q.push(current),current=current.left):Q.length>0?(current=p=p.next=Q.pop(),current=current.right):done=!0;return p.next=null,head.next},sortedListToBST=(list,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),left=sortedListToBST(list,start,middle),root=list.head;return root.left=left,list.head=list.head.next,root.right=sortedListToBST(list,middle+1,end),root}return null},mergeLists=(l1,l2,compare)=>{const head=new Node$1(null,null);let p=head,p1=l1,p2=l2;for(;null!==p1&&null!==p2;)compare(p1.key,p2.key)<0?(p.next=p1,p1=p1.next):(p.next=p2,p2=p2.next),p=p.next;return null!==p1?p.next=p1:null!==p2&&(p.next=p2),head.next},sort=(keys,values,left,right,compare)=>{if(left>=right)return;const pivot=keys[left+right>>1];let i=left-1,j=right+1;for(;;){do{i++}while(compare(keys[i],pivot)<0);do{j--}while(compare(keys[j],pivot)>0);if(i>=j)break;let tmp=keys[i];keys[i]=keys[j],keys[j]=tmp,tmp=values[i],values[i]=values[j],values[j]=tmp}sort(keys,values,left,j,compare),sort(keys,values,j+1,right,compare)},computeFields=(event,prev,operation)=>{null===prev?(event.inOut=!1,event.otherInOut=!0):(event.isSubject===prev.isSubject?(event.inOut=!prev.inOut,event.otherInOut=prev.otherInOut):(event.inOut=!prev.otherInOut,event.otherInOut=prev.isVertical()?!prev.inOut:prev.inOut),prev&&(event.prevInResult=!inResult(prev,operation)||prev.isVertical()?prev.prevInResult:prev));const isInResult=inResult(event,operation);event.resultTransition=isInResult?determineResultTransition(event,operation):0},inResult=(event,operation)=>{switch(event.type){case 0:switch(operation){case 0:return!event.otherInOut;case 1:return event.otherInOut;case 2:return event.isSubject&&event.otherInOut||!event.isSubject&&!event.otherInOut;case 3:return!0}break;case 2:return 0===operation||1===operation;case 3:return 2===operation;case 1:return!1}return!1},determineResultTransition=(event,operation)=>{const thisIn=!event.inOut,thatIn=!event.otherInOut;let isIn;switch(operation){case 0:isIn=thisIn&&thatIn;break;case 1:isIn=thisIn||thatIn;break;case 3:isIn=thisIn^thatIn;break;case 2:isIn=event.isSubject?thisIn&&!thatIn:thatIn&&!thisIn}return isIn?1:-1};class SweepEvent{constructor(point,left,otherEvent,isSubject,edgeType){this.left=left,this.point=point,this.otherEvent=otherEvent,this.isSubject=isSubject,this.type=edgeType||0,this.inOut=!1,this.otherInOut=!1,this.prevInResult=null,this.resultTransition=0,this.otherPos=-1,this.outputContourId=-1,this.isExteriorRing=!0}isBelow(p){const p0=this.point,p1=this.otherEvent.point;return this.left?(p0[0]-p[0])*(p1[1]-p[1])-(p1[0]-p[0])*(p0[1]-p[1])>0:(p1[0]-p[0])*(p0[1]-p[1])-(p0[0]-p[0])*(p1[1]-p[1])>0}isAbove(p){return!this.isBelow(p)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return 0!==this.resultTransition}clone(){const copy=new SweepEvent(this.point,this.left,this.otherEvent,this.isSubject,this.type);return copy.contourId=this.contourId,copy.resultTransition=this.resultTransition,copy.prevInResult=this.prevInResult,copy.isExteriorRing=this.isExteriorRing,copy.inOut=this.inOut,copy.otherInOut=this.otherInOut,copy}}const signedArea=(p0,p1,p2)=>{const res=(ax=p0[0],ay=p0[1],bx=p1[0],by=p1[1],cx=p2[0],cy=p2[1],(ay-cy)*(bx-cx)-(ax-cx)*(by-cy));var ax,ay,bx,by,cx,cy;return res>0?-1:res<0?1:0},compareEvents=(e1,e2)=>{const p1=e1.point,p2=e2.point;return p1[0]>p2[0]?1:p1[0]p2[1]?1:-1:specialCases(e1,e2,p1)},specialCases=(e1,e2,p1,p2)=>e1.left!==e2.left?e1.left?1:-1:0!==signedArea(p1,e1.otherEvent.point,e2.otherEvent.point)?e1.isBelow(e2.otherEvent.point)?-1:1:!e1.isSubject&&e2.isSubject?1:-1,divideSegment=(se,p,queue)=>{const r=new SweepEvent(p,!1,se,se.isSubject),l=new SweepEvent(p,!0,se.otherEvent,se.isSubject);return r.contourId=l.contourId=se.contourId,compareEvents(l,se.otherEvent)>0&&(se.otherEvent.left=!0,l.left=!1),se.otherEvent.otherEvent=l,se.otherEvent=r,queue.push(l),queue.push(r),queue},crossProduct=(a,b)=>a[0]*b[1]-a[1]*b[0],possibleIntersection=(se1,se2,queue)=>{const inter=((a1,a2,b1,b2,noEndpointTouch)=>{const va=[a2[0]-a1[0],a2[1]-a1[1]],vb=[b2[0]-b1[0],b2[1]-b1[1]],toPoint=(p,s,d)=>[p[0]+s*d[0],p[1]+s*d[1]],e=[b1[0]-a1[0],b1[1]-a1[1]];let kross=crossProduct(va,vb),sqrKross=kross*kross;const sqrLenA=dot$1(va,va);if(sqrKross>0){const s=crossProduct(e,vb)/kross;if(s<0||s>1)return null;const t=crossProduct(e,va)/kross;return t<0||t>1?null:0===s||1===s?noEndpointTouch?null:[toPoint(a1,s,va)]:0===t||1===t?noEndpointTouch?null:[toPoint(b1,t,vb)]:[toPoint(a1,s,va)]}if(kross=crossProduct(e,va),sqrKross=kross*kross,sqrKross>0)return null;const sa=dot$1(va,e)/sqrLenA,sb=sa+dot$1(va,vb)/sqrLenA,smin=Math.min(sa,sb),smax=Math.max(sa,sb);return smin<=1&&smax>=0?1===smin?noEndpointTouch?null:[toPoint(a1,smin>0?smin:0,va)]:0===smax?noEndpointTouch?null:[toPoint(a1,smax<1?smax:1,va)]:noEndpointTouch&&0===smin&&1===smax?null:[toPoint(a1,smin>0?smin:0,va),toPoint(a1,smax<1?smax:1,va)]:null})(se1.point,se1.otherEvent.point,se2.point,se2.otherEvent.point),nIntersections=inter?inter.length:0;if(0===nIntersections)return 0;if(1===nIntersections&&(equals$6(se1.point,se2.point)||equals$6(se1.otherEvent.point,se2.otherEvent.point)))return 0;if(2===nIntersections&&se1.isSubject===se2.isSubject)return 0;if(1===nIntersections)return equals$6(se1.point,inter[0])||equals$6(se1.otherEvent.point,inter[0])||divideSegment(se1,inter[0],queue),equals$6(se2.point,inter[0])||equals$6(se2.otherEvent.point,inter[0])||divideSegment(se2,inter[0],queue),1;const events=[];let leftCoincide=!1,rightCoincide=!1;return equals$6(se1.point,se2.point)?leftCoincide=!0:1===compareEvents(se1,se2)?events.push(se2,se1):events.push(se1,se2),equals$6(se1.otherEvent.point,se2.otherEvent.point)?rightCoincide=!0:1===compareEvents(se1.otherEvent,se2.otherEvent)?events.push(se2.otherEvent,se1.otherEvent):events.push(se1.otherEvent,se2.otherEvent),leftCoincide&&rightCoincide||leftCoincide?(se2.type=1,se1.type=se2.inOut===se1.inOut?2:3,leftCoincide&&!rightCoincide&÷Segment(events[1].otherEvent,events[0].point,queue),2):rightCoincide?(divideSegment(events[0],events[1].point,queue),3):events[0]!==events[3].otherEvent?(divideSegment(events[0],events[1].point,queue),divideSegment(events[1],events[2].point,queue),3):(divideSegment(events[0],events[1].point,queue),divideSegment(events[3].otherEvent,events[2].point,queue),3)},compareSegments=(le1,le2)=>{if(le1===le2)return 0;if(0!==signedArea(le1.point,le1.otherEvent.point,le2.point)||0!==signedArea(le1.point,le1.otherEvent.point,le2.otherEvent.point))return equals$6(le1.point,le2.point)?le1.isBelow(le2.otherEvent.point)?-1:1:le1.point[0]===le2.point[0]?le1.point[1]le2.contourId?1:-1}return 1===compareEvents(le1,le2)?1:-1};class Contour{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return null==this.holeOf}}const nextPos=(pos,resultEvents,processed,origPos)=>{let newPos=pos+1;const p=resultEvents[pos].point;let p1;const length=resultEvents.length;for(newPosorigPos;)newPos--;return newPos},initializeContourFromContext=(event,contours,contourId)=>{const contour=new Contour;if(null!=event.prevInResult){const prevInResult=event.prevInResult,lowerContourId=prevInResult.outputContourId,lowerResultTransition=prevInResult.resultTransition;if(lowerContourId<0)contour.holeOf=null,contour.depth=0;else if(lowerResultTransition>0){const lowerContour=contours[lowerContourId];if(null!=lowerContour.holeOf){const parentContourId=lowerContour.holeOf;contours[parentContourId].holeIds.push(contourId),contour.holeOf=parentContourId,contour.depth=contours[lowerContourId].depth}else contours[lowerContourId].holeIds.push(contourId),contour.holeOf=lowerContourId,contour.depth=contours[lowerContourId].depth+1}else contour.holeOf=null,contour.depth=contours[lowerContourId].depth}else contour.holeOf=null,contour.depth=0;return contour},connectEdges=sortedEvents=>{const resultEvents=(sortedEvents=>{let event,i,len,tmp;const resultEvents=[];for(i=0,len=sortedEvents.length;i{processed[pos]=!0,pos=resultEvents.length)&&resultEvents[pos];);contours.push(contour)}return contours};class Queue{constructor(data,compare){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this._up(this.length++)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return--this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos=0)break;data[pos]=data[bestChild],pos=bestChild}data[pos]=item}}const max=Math.max,min=Math.min;let contourId=0;const processPolygon=(contourOrHole,isSubject,depth,queue,bbox,isExteriorRing)=>{const len=contourOrHole.length-1;let s1,s2,e1,e2;for(let i=0;i0?e2.left=!0:e1.left=!0;const x=s1[0],y=s1[1];bbox[0]=min(bbox[0],x),bbox[1]=min(bbox[1],y),bbox[2]=max(bbox[2],x),bbox[3]=max(bbox[3],y),queue.push(e1),queue.push(e2)}},EMPTY=[],toMartinez=geometry=>{const outlines=[];return toOutlines(geometry).forEach((outline=>{equals$6(outline[0],outline[outline.length-1])?outlines.push(outline):outlines.push([...outline,outline[0]])})),[outlines]},fromOutlines=outlines=>(outlines.forEach((outline=>{equals$6(outline[0],outline[outline.length-1])&&outline.pop()})),outlines=outlines.filter((o=>o.length>=3)),create$a(outlines)),boolean=(subjectGeom,clippingGeom,operation)=>{const subject=toMartinez(subjectGeom),clipping=toMartinez(clippingGeom);let trivial=((subject,clipping,operation)=>{let result=null;if(subject.length*clipping.length==0){if(0===operation)return EMPTY;2===operation?result=subject:1!==operation&&3!==operation||(result=0===subject.length?clipping:subject)}return result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,operation);if(trivial)return trivial;const sbbox=[1/0,1/0,-1/0,-1/0],cbbox=[1/0,1/0,-1/0,-1/0],eventQueue=((subject,clipping,sbbox,cbbox,operation)=>{const eventQueue=new Queue([],compareEvents);let polygonSet,isExteriorRing,i,ii,j,jj;for(i=0,ii=subject.length;i{let result=null;return(sbbox[0]>cbbox[2]||cbbox[0]>sbbox[2]||sbbox[1]>cbbox[3]||cbbox[1]>sbbox[3])&&(0===operation?result=EMPTY:2===operation?result=subject:1!==operation&&3!==operation||(result=subject.concat(clipping))),result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,sbbox,cbbox,operation),trivial)return trivial;const sortedEvents=((eventQueue,subject,clipping,sbbox,cbbox,operation)=>{const sweepLine=new Tree$1(compareSegments),sortedEvents=[],rightBound=Math.min(sbbox[2],cbbox[2]);let prev,next,begin;for(;0!==eventQueue.length;){let event=eventQueue.pop();if(sortedEvents.push(event),0===operation&&event.point[0]>rightBound||2===operation&&event.point[0]>sbbox[2])break;if(event.left){next=prev=sweepLine.insert(event),begin=sweepLine.minNode(),prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next);const prevEvent=prev?prev.key:null;let prevprevEvent;if(computeFields(event,prevEvent,operation),next&&2===possibleIntersection(event,next.key,eventQueue)&&(computeFields(event,prevEvent,operation),computeFields(next.key,event,operation)),prev&&2===possibleIntersection(prev.key,event,eventQueue)){let prevprev=prev;prevprev=prevprev!==begin?sweepLine.prev(prevprev):null,prevprevEvent=prevprev?prevprev.key:null,computeFields(prevEvent,prevprevEvent,operation),computeFields(event,prevEvent,operation)}}else event=event.otherEvent,next=prev=sweepLine.find(event),prev&&next&&(prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next),sweepLine.remove(event),next&&prev&&possibleIntersection(prev.key,next.key,eventQueue))}return sortedEvents})(eventQueue,0,0,sbbox,cbbox,operation),contours=connectEdges(sortedEvents),polygons=[];for(let i=0;i=0;k--)hole.push(holePoints[k]);rings.push(hole)}polygons.push(rings)}}return polygons?fromOutlines(polygons.flat()):create$a()},interpolateBetween2DPointsForY=(point1,point2,y)=>{let t,f1=y-point1[1],f2=point2[1]-point1[1];f2<0&&(f1=-f1,f2=-f2),t=f1<=0?0:f1>=f2?1:f2<1e-10?.5:f1/f2;return point1[0]+t*(point2[0]-point1[0])};class OrthonormalFormula{constructor(plane){this.plane=plane;const rightVector=orthogonal([0,0,0],plane);this.v=normalize$1(rightVector,cross$1(rightVector,plane,rightVector)),this.u=cross$1([0,0,0],this.v,plane),this.planeOrigin=scale$3([0,0,0],plane,plane[3]),this.basisMap=new Map}getProjectionMatrix(){return fromValues$4(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)}getInverseProjectionMatrix(){return fromValues$4(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,this.planeOrigin[0],this.planeOrigin[1],this.planeOrigin[2],1)}to2D(vertex){const point=fromValues$2(dot$2(vertex,this.u),dot$2(vertex,this.v));return this.basisMap.set(point,vertex),point}to3D(point){const original=this.basisMap.get(point);if(original)return original;const v1=scale$3([0,0,0],this.u,point[0]),v2=scale$3([0,0,0],this.v,point[1]),v3=add$1(v1,v1,this.planeOrigin);return add$1(v2,v2,v3)}}const insertSorted=(array,element,compareFunc)=>{let leftBound=0,rightBound=array.length;for(;rightBound>leftBound;){const testIndex=Math.floor((leftBound+rightBound)/2);compareFunc(element,array[testIndex])>0?leftBound=testIndex+1:rightBound=testIndex}array.splice(leftBound,0,element)},fnNumberSort=(a,b)=>a-b,retessellate=geometry=>{if(geometry.isRetesselated)return geometry;const polygons=toPolygons$1(geometry).map(((polygon,index)=>({vertices:polygon.vertices,plane:plane(polygon),index:index}))),classified=classifyPolygons(polygons),destPolygons=[];classified.forEach((group=>{if(Array.isArray(group)){const reTessellateCoplanarPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const destPolygons=[],numPolygons=sourcePolygons.length,plane$1=plane(sourcePolygons[0]),orthonormalFormula=new OrthonormalFormula(plane$1),polygonVertices2d=[],polygonTopVertexIndexes=[],topy2polygonIndexes=new Map,yCoordinateToPolygonIndexes=new Map,yCoordinateBins=new Map;for(let polygonIndex=0;polygonIndex0){let miny,maxy;for(let i=0;imaxy)&&(maxy=y);let polygonIndexes=yCoordinateToPolygonIndexes.get(y);polygonIndexes||(polygonIndexes={},yCoordinateToPolygonIndexes.set(y,polygonIndexes)),polygonIndexes[polygonIndex]=!0}if(miny>=maxy)vertices2d=[],numVertices=0,minIndex=-1;else{let polygonIndexes=topy2polygonIndexes.get(miny);polygonIndexes||(polygonIndexes=[],topy2polygonIndexes.set(miny,polygonIndexes)),polygonIndexes.push(polygonIndex)}}vertices2d.reverse(),minIndex=numVertices-minIndex-1,polygonVertices2d.push(vertices2d),polygonTopVertexIndexes.push(minIndex)}const yCoordinates=[];yCoordinateToPolygonIndexes.forEach(((polylist,y)=>yCoordinates.push(y))),yCoordinates.sort(fnNumberSort);let activePolygons=[],prevOutPolygonRow=[];for(let yIndex=0;yIndex=numVertices&&(nextLeftVertexIndex=0),vertices2d[nextLeftVertexIndex][1]!==yCoordinate)break;newLeftVertexIndex=nextLeftVertexIndex}let nextRightVertexIndex=newRightVertexIndex-1;if(nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),vertices2d[nextRightVertexIndex][1]===yCoordinate&&(newRightVertexIndex=nextRightVertexIndex),newLeftVertexIndex!==activePolygon.leftVertexIndex&&newLeftVertexIndex===newRightVertexIndex)activePolygons.splice(activePolygonIndex,1),--activePolygonIndex;else{activePolygon.leftVertexIndex=newLeftVertexIndex,activePolygon.rightVertexIndex=newRightVertexIndex,activePolygon.topLeft=vertices2d[newLeftVertexIndex],activePolygon.topRight=vertices2d[newRightVertexIndex];let nextLeftVertexIndex=newLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0),activePolygon.bottomLeft=vertices2d[nextLeftVertexIndex];let nextRightVertexIndex=newRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),activePolygon.bottomRight=vertices2d[nextRightVertexIndex]}}}let nextYcoordinate;if(yIndex>=yCoordinates.length-1)activePolygons=[],nextYcoordinate=null;else{nextYcoordinate=Number(yCoordinates[yIndex+1]);const middleYcoordinate=.5*(yCoordinate+nextYcoordinate),startingPolygonIndexes=topy2polygonIndexes.get(yCoordinate);for(const polygonIndexKey in startingPolygonIndexes){const polygonIndex=startingPolygonIndexes[polygonIndexKey],vertices2d=polygonVertices2d[polygonIndex],numVertices=vertices2d.length,topVertexIndex=polygonTopVertexIndexes[polygonIndex];let topLeftVertexIndex=topVertexIndex;for(;;){let i=topLeftVertexIndex+1;if(i>=numVertices&&(i=0),vertices2d[i][1]!==yCoordinate)break;if(i===topVertexIndex)break;topLeftVertexIndex=i}let topRightVertexIndex=topVertexIndex;for(;;){let i=topRightVertexIndex-1;if(i<0&&(i=numVertices-1),vertices2d[i][1]!==yCoordinate)break;if(i===topLeftVertexIndex)break;topRightVertexIndex=i}let nextLeftVertexIndex=topLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0);let nextRightVertexIndex=topRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1);const newActivePolygon={polygonIndex:polygonIndex,leftVertexIndex:topLeftVertexIndex,rightVertexIndex:topRightVertexIndex,topLeft:vertices2d[topLeftVertexIndex],topRight:vertices2d[topRightVertexIndex],bottomLeft:vertices2d[nextLeftVertexIndex],bottomRight:vertices2d[nextRightVertexIndex]};insertSorted(activePolygons,newActivePolygon,((el1,el2)=>{const x1=interpolateBetween2DPointsForY(el1.topLeft,el1.bottomLeft,middleYcoordinate),x2=interpolateBetween2DPointsForY(el2.topLeft,el2.bottomLeft,middleYcoordinate);return x1>x2?1:x10){const prevOutPolygon=newOutPolygonRow[newOutPolygonRow.length-1],d1=distance(outPolygon.topLeft,prevOutPolygon.topRight),d2=distance(outPolygon.bottomLeft,prevOutPolygon.bottomRight);d10){const prevContinuedIndexes=new Set,matchedIndexes=new Set;for(let i=0;i=0)&&(rightLineContinues||d2>=0)&&(thisPolygon.outPolygon=prevPolygon.outPolygon,thisPolygon.leftLineContinues=leftLineContinues,thisPolygon.rightLineContinues=rightLineContinues,prevContinuedIndexes.add(ii));break}}}for(let ii=0;iiEPS&&prevPolygon.outPolygon.leftPoints.push(prevPolygon.bottomLeft),prevPolygon.outPolygon.leftPoints.reverse();const vertices3d=prevPolygon.outPolygon.rightPoints.concat(prevPolygon.outPolygon.leftPoints).map((point2d=>orthonormalFormula.to3D(point2d))),polygon=fromVerticesAndPlane(vertices3d,plane$1);polygon.vertices.length&&destPolygons.push(polygon)}}for(let i=0;iEPS&&thisPolygon.outPolygon.rightPoints.push(thisPolygon.topRight))}prevOutPolygonRow=newOutPolygonRow}return destPolygons})(group);destPolygons.push(...reTessellateCoplanarPolygons)}else destPolygons.push(group)}));const result=create$8(destPolygons);return result.isRetesselated=!0,result},classifyPolygons=polygons=>{let clusters=[polygons];const nonCoplanar=[];for(let component=3;component>=0;component--){const maybeCoplanar=[],tolerance=3===component?15e-9:NEPS;clusters.forEach((cluster=>{cluster.sort(byPlaneComponent(component,tolerance));let startIndex=0;for(let i=1;itolerance&&(i-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex,i)),startIndex=i);cluster.length-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex))})),clusters=maybeCoplanar}const result=[];return clusters.forEach((cluster=>{cluster[0]&&(result[cluster[0].index]=cluster)})),nonCoplanar.forEach((polygon=>{result[polygon.index]=polygon})),result},byPlaneComponent=(component,tolerance)=>(a,b)=>a.plane[component]-b.plane[component]>tolerance?1:b.plane[component]-a.plane[component]>tolerance?-1:0;class Node{constructor(parent){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=parent}invert(){const queue=[this];let node;for(let i=0;i{treeNode.isRemoved()||treeNode.splitByPlane(plane,coplanarFrontNodes,backNodes,frontNodes,backNodes)})),node.front&&frontNodes.length>0&&stack.push({node:node.front,polygonTreeNodes:frontNodes});const numBackNodes=backNodes.length;if(node.back&&numBackNodes>0)stack.push({node:node.back,polygonTreeNodes:backNodes});else for(let i=0;i0&&tree.rootnode.clipPolygons(node.polygontreenodes,alsoRemoveCoplanarFront),node.front&&stack.push(node.front),node.back&&stack.push(node.back),node=stack.pop()}while(void 0!==node)}addPolygonTreeNodes(newPolygonTreeNodes){let current={node:this,polygonTreeNodes:newPolygonTreeNodes};const stack=[];do{const node=current.node,polygonTreeNodes=current.polygonTreeNodes,len=polygonTreeNodes.length;if(0===len){current=stack.pop();continue}if(!node.plane){let index=0;index=Math.floor(len/2);const bestPoly=polygonTreeNodes[index].getPolygon();node.plane=plane(bestPoly)}const frontNodes=[],backNodes=[];for(let i=0;i0){node.front||(node.front=new Node(node));len===frontNodes.length&&0===backNodes.length?node.front.polygontreenodes=frontNodes:stack.push({node:node.front,polygonTreeNodes:frontNodes})}if(backNodes.length>0){node.back||(node.back=new Node(node));len===backNodes.length&&0===frontNodes.length?node.back.polygontreenodes=backNodes:stack.push({node:node.back,polygonTreeNodes:backNodes})}current=stack.pop()}while(void 0!==current)}}const splitLineSegmentByPlane=(plane,p1,p2)=>{const direction=subtract$3([0,0,0],p2,p1);let lambda=(plane[3]-dot$2(plane,p1))/dot$2(plane,direction);return Number.isNaN(lambda)&&(lambda=0),lambda>1&&(lambda=1),lambda<0&&(lambda=0),scale$3(direction,direction,lambda),add$1(direction,p1,direction),direction};class PolygonTreeNode{constructor(parent,polygon){this.parent=parent,this.children=[],this.polygon=polygon,this.removed=!1}addPolygons(polygons){if(!this.isRootNode())throw new Error("Assertion failed");const _this=this;polygons.forEach((polygon=>{_this.addChild(polygon)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const parentschildren=this.parent.children,i=parentschildren.indexOf(this);if(i<0)throw new Error("Assertion failed");parentschildren.splice(i,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(result){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){if(this.children.length){const queue=[this.children];let i,j,l,node,nodes;for(i=0;i0?queue.push(node.children):node._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}else this._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}_splitByPlane(splane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){const polygon=this.polygon;if(polygon){const bound=measureBoundingSphere$1(polygon),sphereRadius=bound[3]+EPS,d=dot$2(splane,bound)-splane[3];if(d>sphereRadius)frontNodes.push(this);else if(d<-sphereRadius)backNodes.push(this);else{const splitResult=((splane,polygon)=>{const result={type:null,front:null,back:null},vertices=polygon.vertices,numVertices=vertices.length,pplane=plane(polygon);if(equals$5(pplane,splane))result.type=0;else{let hasFront=!1,hasBack=!1;const vertexIsBack=[],MINEPS=-EPS;for(let i=0;iEPS&&(hasFront=!0),t=numVertices&&(nextVertexIndex=0);const nextIsBack=vertexIsBack[nextVertexIndex];if(isback===nextIsBack)isback?backVertices.push(vertex):frontVertices.push(vertex);else{const nextPoint=vertices[nextVertexIndex],intersectionPoint=splitLineSegmentByPlane(splane,vertex,nextPoint);isback?(backVertices.push(vertex),backVertices.push(intersectionPoint),frontVertices.push(intersectionPoint)):(frontVertices.push(vertex),frontVertices.push(intersectionPoint),backVertices.push(intersectionPoint))}isback=nextIsBack}const EPS_SQUARED=EPS*EPS;if(backVertices.length>=3){let prevVertex=backVertices[backVertices.length-1];for(let vertexIndex=0;vertexIndex=3){let prevVertex=frontVertices[frontVertices.length-1];for(let vertexIndex=0;vertexIndex=3&&(result.front=fromVerticesAndPlane(frontVertices,pplane)),backVertices.length>=3&&(result.back=fromVerticesAndPlane(backVertices,pplane))}else result.type=3;else result.type=2;else{const t=dot$2(splane,pplane);result.type=t>=0?0:1}}return result})(splane,polygon);switch(splitResult.type){case 0:coplanarFrontNodes.push(this);break;case 1:coplanarBackNodes.push(this);break;case 2:frontNodes.push(this);break;case 3:backNodes.push(this);break;case 4:if(splitResult.front){const frontNode=this.addChild(splitResult.front);frontNodes.push(frontNode)}if(splitResult.back){const backNode=this.addChild(splitResult.back);backNodes.push(backNode)}}}}}addChild(polygon){const newChild=new PolygonTreeNode(this,polygon);return this.children.push(newChild),newChild}invertSub(){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let children=[this];const queue=[children];for(let i=0;i0&&queue.push(node.children),node.children=[]}}}toString(){let result="",children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}return result}}class Tree{constructor(polygons){this.polygonTree=new PolygonTreeNode,this.rootnode=new Node(null),polygons&&this.addPolygons(polygons)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(tree,alsoRemoveCoplanarFront=!1){this.rootnode.clipTo(tree,alsoRemoveCoplanarFront)}allPolygons(){const result=[];return this.polygonTree.getPolygons(result),result}addPolygons(polygons){const polygonTreeNodes=new Array(polygons.length);for(let i=0;i{if(0===geometry1.polygons.length||0===geometry2.polygons.length)return!1;const bounds1=measureBoundingBox(geometry1),min1=bounds1[0],max1=bounds1[1],bounds2=measureBoundingBox(geometry2),min2=bounds2[0],max2=bounds2[1];return!(min2[0]-max1[0]>EPS)&&(!(min1[0]-max2[0]>EPS)&&(!(min2[1]-max1[1]>EPS)&&(!(min1[1]-max2[1]>EPS)&&(!(min2[2]-max1[2]>EPS)&&!(min1[2]-max2[2]>EPS)))))},intersectGeom3=(...geometries)=>{let newGeometry=(geometries=flatten(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return create$8();const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),b.clipTo(a),b.invert(),a.clipTo(b),b.clipTo(a),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=retessellate(newGeometry),newGeometry},intersect=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("intersect wrong number of arguments");if(!areAllShapesTheSameType(geometries))throw new Error("intersect arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return((...geometries)=>{let newGeometry=(geometries=flatten(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,0)})),newGeometry})(geometries);if(isA$3(geometry))return intersectGeom3(geometries);throw new Error("intersect unsupported geometry type")},scission=(...objects)=>{if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$3(object)?(geometry=>{const eps=measureEpsilon(geometry),polygons=toPolygons$1(geometry),pl=polygons.length,indexesPerVertex=new Map,temp=[0,0,0];polygons.forEach(((polygon,index)=>{polygon.vertices.forEach((vertex=>{((map,vertex,index)=>{const key=`${vertex}`,mapping=map.get(key);void 0===mapping?map.set(key,[index]):mapping.push(index)})(indexesPerVertex,snap$2(temp,vertex,eps),index)}))}));const indexesPerPolygon=polygons.map((polygon=>{let indexes=[];return polygon.vertices.forEach((vertex=>{indexes=indexes.concat(((map,vertex)=>{const key=`${vertex}`;return map.get(key)})(indexesPerVertex,snap$2(temp,vertex,eps)))})),{e:1,d:(array=indexes,array.sort(((a,b)=>a-b)).filter(((item,pos,ary)=>!pos||item!==ary[pos-1])))};var array}));indexesPerVertex.clear();let merges=0;const ippl=indexesPerPolygon.length;for(let i=0;i0){const indexes=new Array(pl);indexes[i]=!0;do{merges=0,indexes.forEach(((e,j)=>{const mapj=indexesPerPolygon[j];if(mapj.e>0){mapj.e=-1;for(let d=0;d0);mapi.indexes=indexes}}const newgeometries=[];for(let i=0;inewpolygons.push(polygons[p]))),newgeometries.push(create$8(newpolygons))}return newgeometries})(object):object));return 1===results.length?results[0]:results},subtractGeom3=(...geometries)=>{let newGeometry=(geometries=flatten(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return clone$7(geometry1);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),a.clipTo(b),b.clipTo(a,!0),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=retessellate(newGeometry),newGeometry},subtract=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("subtract wrong number of arguments");if(!areAllShapesTheSameType(geometries))throw new Error("subtract arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return((...geometries)=>{let newGeometry=(geometries=flatten(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,2)})),newGeometry})(geometries);if(isA$3(geometry))return subtractGeom3(geometries);throw new Error("subtract unsupported geometry type")},unionGeom2=(...geometries)=>{let newGeometry=(geometries=flatten(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,1)})),newGeometry},unionGeom3Sub=(geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return unionForNonIntersecting(geometry1,geometry2);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.clipTo(b,!1),b.clipTo(a),b.invert(),b.clipTo(a),b.invert();const newPolygons=a.allPolygons().concat(b.allPolygons());return create$8(newPolygons)},unionForNonIntersecting=(geometry1,geometry2)=>{let newpolygons=toPolygons$1(geometry1);return newpolygons=newpolygons.concat(toPolygons$1(geometry2)),create$8(newpolygons)},union=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("union wrong number of arguments");if(!areAllShapesTheSameType(geometries))throw new Error("union arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return unionGeom2(geometries);if(isA$3(geometry))return((...geometries)=>{let i;for(geometries=flatten(geometries),i=1;i{let{offset:offset,twistAngle:twistAngle,twistSteps:twistSteps,repair:repair}=Object.assign({},{offset:[0,0,1],twistAngle:0,twistSteps:12,repair:!0},options);if(twistSteps<1)throw new Error("twistSteps must be 1 or more");0===twistAngle&&(twistSteps=1);const offsetV=clone$9(offset);let baseSlice=fromGeom2(geometry);offsetV[2]<0&&(baseSlice=reverse$2(baseSlice));const matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];options={numberOfSlices:twistSteps+1,capStart:!0,capEnd:!0,repair:repair,callback:(progress,index,base)=>{const Zrotation=index/twistSteps*twistAngle,Zoffset=scale$3([0,0,0],offsetV,index/twistSteps);return multiply$1(matrix,fromZRotation(matrix,Zrotation),fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],Zoffset)),transform$3(matrix,base)}};const output=extrudeFromSlices(options,baseSlice);return geometry.color&&(output.color=geometry.color),output},extrudeLinear=(options,...objects)=>{const{height:height,twistAngle:twistAngle,twistSteps:twistSteps,repair:repair}=Object.assign({},{height:1,twistAngle:0,twistSteps:1,repair:!0},options);if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");options={offset:[0,0,height],twistAngle:twistAngle,twistSteps:twistSteps,repair:repair};const results=objects.map((object=>isA$2(object)?((options,geometry)=>{if(!geometry.isClosed)throw new Error("extruded path must be closed");const points=toPoints$1(geometry),geometry2=create$a([points]);return geometry.color&&(geometry2.color=geometry.color),extrudeLinearGeom2(options,geometry2)})(options,object):isA$5(object)?extrudeLinearGeom2(options,object):object));return 1===results.length?results[0]:results},extrudeHelical=(options,geometry)=>{const defaults={angle:TAU,startAngle:0,pitch:10,endOffset:0,segmentsPerRotation:32},{angle:angle,endOffset:endOffset,segmentsPerRotation:segmentsPerRotation,startAngle:startAngle}=Object.assign({},defaults,options);let pitch;pitch=!options.pitch&&options.height?options.height/(angle/TAU):options.pitch?options.pitch:defaults.pitch;if(segmentsPerRotation<3)throw new Error("The number of segments per rotation needs to be at least 3.");let baseSlice=fromGeom2(geometry);measureBoundingBox(geometry)[1][0]<=0&&(baseSlice=reverse$2(baseSlice));const calculatedSegments=Math.round(segmentsPerRotation/TAU*Math.abs(angle)),segments=calculatedSegments>=2?calculatedSegments:2,step1=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];let matrix;return extrudeFromSlices({numberOfSlices:segments+1,callback:(progress,index,base)=>{const zRotation=startAngle+angle/segments*index;return multiply$1(step1,fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[endOffset/segments*index,0,(zRotation-startAngle)/TAU*pitch*Math.sign(angle)]),fromXRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],-TAU/4*Math.sign(angle))),matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],multiply$1(matrix,fromZRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],zRotation),step1),transform$3(matrix,baseSlice)}},baseSlice)},aboutEqualNormals=(a,b)=>Math.abs(a[0]-b[0])<=NEPS&&Math.abs(a[1]-b[1])<=NEPS&&Math.abs(a[2]-b[2])<=NEPS,project=(options,...objects)=>{const{axis:axis,origin:origin}=Object.assign({},{axis:[0,0,1],origin:[0,0,0]},options);if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");options={axis:axis,origin:origin};const results=objects.map((object=>isA$3(object)?((options,geometry)=>{const projPlane=fromNormalAndPoint([0,0,0,0],options.axis,options.origin);if(Number.isNaN(projPlane[0])||Number.isNaN(projPlane[1])||Number.isNaN(projPlane[2])||Number.isNaN(projPlane[3]))throw new Error("project: invalid axis or origin");const epsilon=measureEpsilon(geometry),epsilonArea=epsilon*epsilon*Math.sqrt(3)/4;if(0===epsilon)return create$a();const polygons=toPolygons$1(geometry);let projPolys=[];for(let i=0;iprojectionOfPoint(projPlane,v))),newPoly=create$7(newVertices),newPlane=plane(newPoly);aboutEqualNormals(projPlane,newPlane)&&(measureArea$2(newPoly)transform$7(rotation,p)))}projPolys=projPolys.sort(((a,b)=>measureArea$2(b)-measureArea$2(a)));const projGeoms=projPolys.map((p=>{const cloned=p.vertices.map(clone$8);return create$a([cloned])})),output=unionGeom2(projGeoms);return geometry.color&&(output.color=geometry.color),output})(options,object):object));return 1===results.length?results[0]:results},hullPoints2=uniquePoints=>{let min=fromValues$2(1/0,1/0);uniquePoints.forEach((point=>{(point[1]{const angle=fakeAtan2(point[1]-min[1],point[0]-min[0]),distSq=squaredDistance(point,min);points.push({point:point,angle:angle,distSq:distSq})})),points.sort(((pt1,pt2)=>pt1.angle!==pt2.angle?pt1.angle-pt2.angle:pt1.distSq-pt2.distSq));const stack=[];return points.forEach((point=>{let cnt=stack.length;for(;cnt>1&&ccw(stack[cnt-2],stack[cnt-1],point.point)<=Number.EPSILON;)stack.pop(),cnt=stack.length;stack.push(point.point)})),stack},ccw=(v1,v2,v3)=>(v2[0]-v1[0])*(v3[1]-v1[1])-(v2[1]-v1[1])*(v3[0]-v1[0]),fakeAtan2=(y,x)=>0===y&&0===x?-1/0:-x/y,toUniquePoints=geometries=>{const found=new Set,uniquePoints=[],addPoint=point=>{const key=point.toString();found.has(key)||(uniquePoints.push(point),found.add(key))};return geometries.forEach((geometry=>{isA$5(geometry)?toPoints$3(geometry).forEach(addPoint):isA$3(geometry)?toPoints$2(geometry).forEach((points=>points.forEach(addPoint))):isA$2(geometry)&&toPoints$1(geometry).forEach(addPoint)})),uniquePoints},pointLineDistance=(point,a,b)=>Math.sqrt(((p,a,b)=>{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b));class VertexList{constructor(){this.head=null,this.tail=null}clear(){this.head=this.tail=null}insertBefore(target,node){node.prev=target.prev,node.next=target,node.prev?node.prev.next=node:this.head=node,target.prev=node}insertAfter(target,node){node.prev=target,node.next=target.next,node.next?node.next.prev=node:this.tail=node,target.next=node}add(node){this.head?this.tail.next=node:this.head=node,node.prev=this.tail,node.next=null,this.tail=node}addAll(node){for(this.head?this.tail.next=node:this.head=node,node.prev=this.tail;node.next;)node=node.next;this.tail=node}remove(node){node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev}removeChain(a,b){a.prev?a.prev.next=b.next:this.head=b.next,b.next?b.next.prev=a.prev:this.tail=a.prev}first(){return this.head}isEmpty(){return!this.head}}class Vertex{constructor(point,index){this.point=point,this.index=index,this.next=null,this.prev=null,this.face=null}}class HalfEdge{constructor(vertex,face){this.vertex=vertex,this.face=face,this.next=null,this.prev=null,this.opposite=null}head(){return this.vertex}tail(){return this.prev?this.prev.vertex:null}length(){return this.tail()?distance$1(this.tail().point,this.head().point):-1}lengthSquared(){return this.tail()?squaredDistance$1(this.tail().point,this.head().point):-1}setOpposite(edge){this.opposite=edge,edge.opposite=this}}class Face{constructor(){this.normal=[],this.centroid=[],this.offset=0,this.outside=null,this.mark=0,this.edge=null,this.nVertices=0}getEdge(i){if("number"!=typeof i)throw Error("requires a number");let it=this.edge;for(;i>0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;imaxDistance&&(maxDistance=distance,v2=vertex)}}const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i{if(1===(geometries=flatten(geometries)).length)return geometries[0];const unique=toUniquePoints(geometries),polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(unique,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>unique[index]));return create$7(vertices)}));return create$8(polygons)},hull=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");if(!areAllShapesTheSameType(geometries))throw new Error("only hulls of the same type are supported");const geometry=geometries[0];return isA$2(geometry)?((...geometries)=>{geometries=flatten(geometries);const unique=toUniquePoints(geometries),hullPoints=hullPoints2(unique);return fromPoints$2({closed:!0},hullPoints)})(geometries):isA$5(geometry)?((...geometries)=>{geometries=flatten(geometries);const unique=toUniquePoints(geometries),hullPoints=hullPoints2(unique);return hullPoints.length<3?create$a():create$a([hullPoints])})(geometries):isA$3(geometry)?hullGeom3(geometries):geometry},hullChain=(...geometries)=>{const hulls=[];if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");1===geometries.length&&hulls.push(geometries[0]);for(let i=1;i{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons},createEdges=polygon=>{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2;return[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergeCoplanarPolygons=sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&aboutEqualNormals(plane1,plane2);var plane1,plane2}));if(mapping){mapping[1].push(polygon)}else polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const sourcePolygons=mapping[1],retesselatedPolygons=mergeCoplanarPolygons(sourcePolygons);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=measureEpsilon(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=snapPolygons(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results},snap=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry),newPoints=toPoints$1(geometry).map((point=>snap$1([0,0],point,epsilon)));return create$5(newPoints)})(geometry):isA$5(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry);let newOutlines=toOutlines(geometry).map((outline=>{let prev=snap$1([0,0],outline[outline.length-1],epsilon);const newOutline=[];return outline.forEach((point=>{const snapped=snap$1([0,0],point,epsilon);equals$6(prev,snapped)||newOutline.push(snapped),prev=snapped})),newOutline}));return newOutlines=newOutlines.filter((outline=>measureArea$1(create$3(outline)))),create$a(newOutlines)})(geometry):isA$3(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry),polygons=toPolygons$1(geometry),newPolygons=snapPolygons(epsilon,polygons);return create$8(newPolygons)})(geometry):geometry));return 1===results.length?results[0]:results},offsetFromPoints=(options,points)=>{let{delta:delta,corners:corners,closed:closed,segments:segments}=Object.assign({},{delta:1,corners:"edge",closed:!1,segments:16},options);if(Math.abs(delta)0&&delta>=0||rotation<0&&delta<0;delta=Math.abs(delta);let previousSegment=null,newPoints=[];const newCorners=[],of=[0,0],n=points.length;for(let i=0;ipointIndex.set(point,index)));const line0=[0,1,0],line1=[0,1,0];newCorners.forEach((corner=>{fromPoints$1(line0,corner.s0[0],corner.s0[1]),fromPoints$1(line1,corner.s1[0],corner.s1[1]);const ip=intersectPointOfLines(line0,line1);if(Number.isFinite(ip[0])&&Number.isFinite(ip[1])){const p0=corner.s0[1],i=pointIndex.get(p0);newPoints[i]=ip,newPoints[(i+1)%newPoints.length]=void 0}else{const p0=corner.s1[0],i=pointIndex.get(p0);newPoints[i]=void 0}})),newPoints=newPoints.filter((p=>void 0!==p))}if("round"===corners){let cornerSegments=Math.floor(segments/4);const v0=[0,0];newCorners.forEach((corner=>{let rotation=angleRadians(subtract$1(v0,corner.s1[0],corner.c));if(rotation-=angleRadians(subtract$1(v0,corner.s0[1],corner.c)),orientation&&rotation<0&&(rotation+=Math.PI,rotation<0&&(rotation+=Math.PI)),!orientation&&rotation>0&&(rotation-=Math.PI,rotation>0&&(rotation-=Math.PI)),0!==rotation){cornerSegments=Math.floor(segments*(Math.abs(rotation)/TAU));const step=rotation/cornerSegments,start=angleRadians(subtract$1(v0,corner.s0[1],corner.c)),cornerPoints=[];for(let i=1;i0){const p0=corner.s0[1];let i=newPoints.findIndex((point=>equals$6(p0,point)));i=(i+1)%newPoints.length,newPoints.splice(i,0,...cornerPoints)}}else{const p0=corner.s1[0],i=newPoints.findIndex((point=>equals$6(p0,point)));newPoints.splice(i,1)}}))}return newPoints},mapPlaneToVertex=(map,vertex,plane)=>{const key=vertex.toString();if(map.has(key)){map.get(key)[1].push(plane)}else{const entry=[vertex,[plane]];map.set(key,entry)}},mapPlaneToEdge=(map,edge,plane)=>{const key0=edge[0].toString(),key1=edge[1].toString(),key=key0{map.findIndex((item=>item===angle))<0&&map.push(angle)},offsetShell=(options,geometry)=>{const{delta:delta,segments:segments}=Object.assign({},{delta:1,segments:12},options);let result=create$8();const vertices2planes=new Map,edges2planes=new Map,v1=[0,0,0],v2=[0,0,0];return toPolygons$1(geometry).forEach((polygon=>{const extrudeVector=scale$3([0,0,0],plane(polygon),2*delta),extrudedFace=((offsetVector,polygon1)=>{dot$2(plane(polygon1),offsetVector)>0&&(polygon1=invert$1(polygon1));const newPolygons=[polygon1],polygon2=transform$7(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offsetVector),polygon1),numVertices=polygon1.vertices.length;for(let i=0;i{const edge=item[0],planes=item[1],startVertex=edge[0],endVertex=edge[1],zBase=subtract$3([0,0,0],endVertex,startVertex);normalize$1(zBase,zBase);const xBase=planes[0],yBase=cross$1([0,0,0],xBase,zBase);let angles=[];for(let i=0;i=0&&distance$1(p1,prevP1)=0){startFaceVertices.push(p1),endFaceVertices.push(p2);const polygon=create$7([prevP2,p2,p1,prevP1]);polygons.push(polygon)}prevP1=p1,prevP2=p2}}endFaceVertices.reverse(),polygons.push(create$7(startFaceVertices)),polygons.push(create$7(endFaceVertices));const cylinder=create$8(polygons);result=unionGeom3Sub(result,cylinder)})),vertices2planes.forEach((item=>{const vertex=item[0],planes=item[1],xaxis=planes[0];let bestzaxis=null,bestzaxisOrthogonality=0;for(let i=1;i.05&&crossLength>bestzaxisOrthogonality&&(bestzaxisOrthogonality=crossLength,bestzaxis=normal)}bestzaxis||(bestzaxis=orthogonal(v1,xaxis));const yaxis=cross$1(v1,xaxis,bestzaxis);normalize$1(yaxis,yaxis);const zaxis=cross$1(v2,yaxis,xaxis),corner=sphere({center:[vertex[0],vertex[1],vertex[2]],radius:delta,segments:segments,axes:[xaxis,yaxis,zaxis]});result=unionGeom3Sub(result,corner)})),retessellate(result)},offsetPath2=(options,geometry)=>{const{delta:delta,corners:corners,segments:segments}=Object.assign({},{delta:1,corners:"edge",segments:16},options);if(delta<=0)throw new Error("the given delta must be positive for paths");if("edge"!==corners&&"chamfer"!==corners&&"round"!==corners)throw new Error('corners must be "edge", "chamfer", or "round"');const closed=geometry.isClosed,points=toPoints$1(geometry),paths={points:points,external:offsetFromPoints({delta:delta,corners:corners,segments:segments,closed:closed},points),internal:offsetFromPoints({delta:-delta,corners:corners,segments:segments,closed:closed},points)},output=geometry.isClosed?(paths=>{let{external:external,internal:internal}=paths;return external.length<2?create$a():(area$1(external)<0?external=external.reverse():internal=internal.reverse(),create$a([external,internal]))})(paths):((paths,segments,corners,delta)=>{const{points:points,external:external,internal:internal}=paths;if(0===points.length)return create$a();if(1===points.length)return circle({center:points[0],radius:delta});const capSegments=Math.floor(segments/2),e2iCap=[],i2eCap=[];if("round"===corners&&capSegments>0){const step=Math.PI/capSegments,eCorner=points[points.length-1],e2iStart=angleRadians(subtract$1([0,0],external[external.length-1],eCorner)),iCorner=points[0],i2eStart=angleRadians(subtract$1([0,0],internal[0],iCorner));for(let i=1;i{if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$2(object)?offsetPath2(options,object):isA$5(object)?((options,geometry)=>{const{delta:delta,corners:corners,segments:segments,expandHoles:expandHoles}=Object.assign({},{delta:1,corners:"edge",segments:16,expandHoles:!1},options);if("edge"!==corners&&"chamfer"!==corners&&"round"!==corners)throw new Error('corners must be "edge", "chamfer", or "round"');if(!Number.isFinite(delta))throw new Error("delta must be a finite number");if("round"===corners&&!Number.isFinite(segments))throw new Error("segments must be a finite number");if("round"===corners&&!(segments>0))throw new Error("segments must be greater than zero");const outlines=toOutlines(geometry),newOutlines=outlines.map((outline=>{let outside=!0;if(expandHoles){const level=outlines.reduce(((acc,polygon)=>acc+arePointsInside(outline,create$3(polygon))),0);outside=level%2==0}return offsetFromPoints(options={delta:outside?delta:-delta,corners:corners,closed:!0,segments:segments},outline)})),output=create$a(newOutlines);return geometry.color&&(output.color=geometry.color),output})(options,object):isA$3(object)?((options,geometry)=>{const{delta:delta,corners:corners,segments:segments}=Object.assign({},{delta:1,corners:"round",segments:12},options);if("round"!==corners)throw new Error('corners must be "round" for 3D geometries');const expanded=offsetShell(options={delta:delta,corners:corners,segments:segments},geometry),output=union(geometry,expanded);return geometry.color&&(output.color=geometry.color),output})(options,object):object));return 1===results.length?results[0]:results},padArrayToLength=(anArray,padding,targetLength)=>{for(anArray=anArray.slice();anArray.length{const bounds=measureAggregateBoundingBox(geometry),translation=[0,0,0];for(let i=0;i<3;i++)"center"===modes[i]?translation[i]=relativeTo[i]-(bounds[0][i]+bounds[1][i])/2:"max"===modes[i]?translation[i]=relativeTo[i]-bounds[1][i]:"min"===modes[i]&&(translation[i]=relativeTo[i]-bounds[0][i]);return translate(translation,geometry)},align=(options,...geometries)=>{options=(options=>{if(!Array.isArray(options.modes)||options.modes.length>3)throw new Error("align(): modes must be an array of length <= 3");if(options.modes=padArrayToLength(options.modes,"none",3),3!==options.modes.filter((mode=>["center","max","min","none"].includes(mode))).length)throw new Error('align(): all modes must be one of "center", "max" or "min"');if(!Array.isArray(options.relativeTo)||options.relativeTo.length>3)throw new Error("align(): relativeTo must be an array of length <= 3");if(options.relativeTo=padArrayToLength(options.relativeTo,0,3),3!==options.relativeTo.filter((alignVal=>Number.isFinite(alignVal)||null==alignVal)).length)throw new Error("align(): all relativeTo values must be a number, or null.");if("boolean"!=typeof options.grouped)throw new Error("align(): grouped must be a boolean value.");return options})(options=Object.assign({},{modes:["center","center","min"],relativeTo:[0,0,0],grouped:!1},options));let{modes:modes,relativeTo:relativeTo,grouped:grouped}=options;if(0===(geometries=flatten(geometries)).length)throw new Error("align(): No geometries were provided to act upon");if(relativeTo.filter((val=>null==val)).length){const bounds=measureAggregateBoundingBox(geometries);relativeTo=((relativeTo,modes,bounds)=>{for(let i=0;i<3;i++)null==relativeTo[i]&&("center"===modes[i]?relativeTo[i]=(bounds[0][i]+bounds[1][i])/2:"max"===modes[i]?relativeTo[i]=bounds[1][i]:"min"===modes[i]&&(relativeTo[i]=bounds[0][i]));return relativeTo})(relativeTo,modes,bounds)}return 1===(geometries=grouped?alignGeometries(geometries,modes,relativeTo):geometries.map((geometry=>alignGeometries(geometry,modes,relativeTo)))).length?geometries[0]:geometries},centerGeometry=(options,object)=>{const{axes:axes,relativeTo:relativeTo}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},options),bounds=measureBoundingBox(object),offset=[0,0,0];return axes[0]&&(offset[0]=relativeTo[0]-(bounds[0][0]+(bounds[1][0]-bounds[0][0])/2)),axes[1]&&(offset[1]=relativeTo[1]-(bounds[0][1]+(bounds[1][1]-bounds[0][1])/2)),axes[2]&&(offset[2]=relativeTo[2]-(bounds[0][2]+(bounds[1][2]-bounds[0][2])/2)),translate(offset,object)},center=(options,...objects)=>{const{axes:axes,relativeTo:relativeTo}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},options);if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");if(3!==relativeTo.length)throw new Error("relativeTo must be an array of length 3");options={axes:axes,relativeTo:relativeTo};const results=objects.map((object=>isA$2(object)||isA$5(object)||isA$3(object)?centerGeometry(options,object):object));return 1===results.length?results[0]:results},centerX=(...objects)=>center({axes:[!0,!1,!1]},objects),centerY=(...objects)=>center({axes:[!1,!0,!1]},objects),centerZ=(...objects)=>center({axes:[!1,!1,!0]},objects),scale=(factors,...objects)=>{if(!Array.isArray(factors))throw new Error("factors must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(factors=factors.slice();factors.length<3;)factors.push(1);if(factors[0]<=0||factors[1]<=0||factors[2]<=0)throw new Error("factors must be positive");const matrix=fromScaling([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],factors),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},scaleX=(factor,...objects)=>scale([factor,1,1],objects),scaleY=(factor,...objects)=>scale([1,factor,1],objects),scaleZ=(factor,...objects)=>scale([1,1,factor],objects),transform=(matrix,...objects)=>{if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results};export{EPS,NEPS,TAU,align,arc,index$4 as bezier,center,centerX,centerY,centerZ,circle,colorNameToRgb,colorize,cos,cssColors,cube,cuboid,cylinder,cylinderElliptic,degToRad,ellipse,ellipsoid,extrudeFromSlices,extrudeHelical,extrudeLinear,extrudeRotate,flatten,generalize,geodesicSphere,index$a as geom2,index$6 as geom3,hexToRgb,hslToRgb,hsvToRgb,hueToColorComponent,hull,hullChain,intersect,line,index$1 as line2,index as line3,index$c as mat4,measureAggregateArea,measureAggregateBoundingBox,measureAggregateEpsilon,measureAggregateVolume,measureArea,measureBoundingBox,measureBoundingSphere,measureCenter,measureCenterOfMass,measureDimensions,measureEpsilon,measureVolume,mirror,mirrorX,mirrorY,mirrorZ,offset,offsetFromPoints,index$5 as path2,index$9 as plane,index$3 as poly2,index$7 as poly3,polygon,polyhedron,project,radToDeg,radiusToSegments,rectangle,retessellate,rgbToHex,rgbToHsl,rgbToHsv,rotate,rotateX,rotateY,rotateZ,roundedCuboid,roundedCylinder,roundedRectangle,scale,scaleX,scaleY,scaleZ,scission,sin,index$2 as slice,snap,sphere,square,star,subtract,torus,transform,translate,translateX,translateY,translateZ,triangle,union,index$b as vec2,index$d as vec3,index$8 as vec4,vectorChar,vectorText}; +const cssColors={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]},colorNameToRgb=s=>cssColors[s.toLowerCase()],clone$b=geometry=>Object.assign({},geometry),create$c=()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,NEPS=1e-13,TAU=2*Math.PI,rezero=n=>Math.abs(n)rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation=(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues$4=(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],create$b=()=>[0,0,0],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0]{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale$3=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:create$b,cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:rotateZ$2,scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const fromVectorRotation=(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation=(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation=(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply$1=(out,a,b)=>{const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out},translate$1=(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:create$c,equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:fromScaling,fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:fromValues$4,fromVectorRotation:fromVectorRotation,fromXRotation:fromXRotation,fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:fromZRotation,identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:mirrorByPlane,multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:translate$1});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),create$9=()=>[0,0],clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),snap$1=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};var index$b=Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:create$9,cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:snap$1,squaredDistance:squaredDistance,squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const toPointMap=sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap},fromSides=sides=>{const pointMap=toPointMap(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides=geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1)return;if(!endpointTouch&&(0===ua||1===ua||0===ub||1===ub))return;return[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:fromSides,fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:toSides,toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromNormalAndPoint=(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},projectionOfPoint=(plane,point)=>{const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;var index$9=Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:fromNormalAndPoint,fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,measureBoundingSphere$1=polygon=>{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;ipolygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>NEPS)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;iMath.sqrt(((p,a,b)=>{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b));class VertexList{constructor(){this.head=null,this.tail=null}clear(){this.head=this.tail=null}insertBefore(target,node){node.prev=target.prev,node.next=target,node.prev?node.prev.next=node:this.head=node,target.prev=node}insertAfter(target,node){node.prev=target,node.next=target.next,node.next?node.next.prev=node:this.tail=node,target.next=node}add(node){this.head?this.tail.next=node:this.head=node,node.prev=this.tail,node.next=null,this.tail=node}addAll(node){for(this.head?this.tail.next=node:this.head=node,node.prev=this.tail;node.next;)node=node.next;this.tail=node}remove(node){node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev}removeChain(a,b){a.prev?a.prev.next=b.next:this.head=b.next,b.next?b.next.prev=a.prev:this.tail=a.prev}first(){return this.head}isEmpty(){return!this.head}}class Vertex{constructor(point,index){this.point=point,this.index=index,this.next=null,this.prev=null,this.face=null}}class HalfEdge{constructor(vertex,face){this.vertex=vertex,this.face=face,this.next=null,this.prev=null,this.opposite=null}head(){return this.vertex}tail(){return this.prev?this.prev.vertex:null}length(){return this.tail()?distance$1(this.tail().point,this.head().point):-1}lengthSquared(){return this.tail()?squaredDistance$1(this.tail().point,this.head().point):-1}setOpposite(edge){this.opposite=edge,edge.opposite=this}}class Face{constructor(){this.normal=[],this.centroid=[],this.offset=0,this.outside=null,this.mark=0,this.edge=null,this.nVertices=0}getEdge(i){if("number"!=typeof i)throw Error("requires a number");let it=this.edge;for(;i>0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;imaxDistance&&(maxDistance=distance,v2=vertex)}}const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)},toPolygons$1=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),toPoints$2=geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validateManifold=object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${`${v}`}/${`${vertices[(i+1)%vertices.length]}`}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)};var index$6=Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=runner(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:toPoints$2,toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),validateManifold(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");controlPoints=controlPoints.slice();if(null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");3===color.length&&(color=[color[0],color[1],color[2],1]);const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):Array.isArray(object)?colorize(color,...object):(object.color=color,object)));return 1===results.length?results[0]:results},hexToRgb=notation=>{if((notation=notation.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const r=parseInt(notation.substring(0,2),16)/255,g=parseInt(notation.substring(2,4),16)/255,b=parseInt(notation.substring(4,6),16)/255;if(notation.length>=8){return[r,g,b,parseInt(notation.substring(6,8),16)/255]}return[r,g,b]},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),hueToColorComponent=(p,q,t)=>(t<0&&(t+=1),t>1&&(t-=1),t<1/6?p+6*(q-p)*t:t<.5?q:t<2/3?p+(q-p)*(2/3-t)*6:p),hslToRgb=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain H, S and L values");const h=values[0],s=values[1],l=values[2];let r=l,g=l,b=l;if(0!==s){const q=l<.5?l*(1+s):l+s-l*s,p=2*l-q;r=hueToColorComponent(p,q,h+1/3),g=hueToColorComponent(p,q,h),b=hueToColorComponent(p,q,h-1/3)}if(values.length>3){return[r,g,b,values[3]]}return[r,g,b]},hsvToRgb=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain H, S and V values");const h=values[0],s=values[1],v=values[2];let r=0,g=0,b=0;const i=Math.floor(6*h),f=6*h-i,p=v*(1-s),q=v*(1-f*s),t=v*(1-(1-f)*s);switch(i%6){case 0:r=v,g=t,b=p;break;case 1:r=q,g=v,b=p;break;case 2:r=p,g=v,b=t;break;case 3:r=p,g=q,b=v;break;case 4:r=t,g=p,b=v;break;case 5:r=v,g=p,b=q}if(values.length>3){return[r,g,b,values[3]]}return[r,g,b]},rgbToHex=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=255*values[0],g=255*values[1],b=255*values[2];let s=`#${Number(16777216+65536*r+256*g+b).toString(16).substring(1,7)}`;return values.length>3&&(s+=Number(255*values[3]).toString(16)),s},rgbToHsl=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=values[0],g=values[1],b=values[2],max=Math.max(r,g,b),min=Math.min(r,g,b);let h,s;const l=(max+min)/2;if(max===min)h=s=0;else{const d=max-min;switch(s=l>.5?d/(2-max-min):d/(max+min),max){case r:h=(g-b)/d+(g3){return[h,s,l,values[3]]}return[h,s,l]},rgbToHsv=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=values[0],g=values[1],b=values[2],max=Math.max(r,g,b),min=Math.min(r,g,b);let h;const v=max,d=max-min,s=0===max?0:d/max;if(max===min)h=0;else{switch(max){case r:h=(g-b)/d+(g3){return[h,s,v,values[3]]}return[h,s,v]},getPointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=getPointType(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>{if(0===points.length)return 0;if(polygon.points.length<3)return 0;measureArea$1(polygon)<0&&(polygon=reverse$3(polygon));return points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0},isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),equals$3=(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices=vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours)),reverse$2=slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges=slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges};class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||(!(0!==o1||!onSegment(p1,p2,q1))||(!(0!==o2||!onSegment(p1,q2,q1))||(!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2)))))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles},earcutLinked=(ear,triangles,dim,minX,minY,invSize,pass)=>{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1,minIndex=(list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuepart.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=minIndex(parents[j],(p=>children[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}const toPolygons=slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),data=vertices.flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=triangulate(data,holesIndex);for(let i=0;i{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)};var index$2=Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:equals$3,fromGeom2:fromGeom2,fromVertices:fromVertices,isA:isA,reverse:reverse$2,toEdges:toEdges,toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:toPolygons,toString:slice=>{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:transform$3,validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i[0,1,0],direction$1=line=>{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]},intersectPointOfLines=(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)};var index$1=Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:create$1,direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:intersectPointOfLines,origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];if(Number.isNaN(x)){x=origin$1(line)[0]}return x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};var index=Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$3=new WeakMap,measureArea=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?0:isA$5(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=toSides(geometry).reduce(((area,side)=>area+(side[0][0]*side[1][1]-side[0][1]*side[1][0])),0),area*=.5,cache$3.set(geometry,area),area)})(geometry):isA$3(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=toPolygons$1(geometry).reduce(((area,polygon)=>area+measureArea$2(polygon)),0),cache$3.set(geometry,area),area)})(geometry):isA(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=0,geometry.contours.forEach((contour=>{area+=measureArea$2(create$7(contour))})),cache$3.set(geometry,area),area)})(geometry):0));return 1===results.length?results[0]:results},measureAggregateArea=(...geometries)=>{geometries=flatten(geometries);const areas=measureArea(geometries);if(1===geometries.length)return areas;return areas.reduce(((result,area)=>result+area),0)},cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},measureAggregateBoundingBox=(...geometries)=>{geometries=flatten(geometries);const bounds=measureBoundingBox(geometries);if(1===geometries.length)return bounds;const result=[[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],[-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE]];return bounds.reduce(((result,item)=>result=[min$2(result[0],result[0],item[0]),max$2(result[1],result[1],item[1])]),result)},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{geometries=flatten(geometries);const bounds=measureAggregateBoundingBox(geometries);let dimensions=0;return dimensions=geometries.reduce(((dimensions,geometry)=>isA$2(geometry)||isA$5(geometry)?Math.max(dimensions,2):isA$3(geometry)?Math.max(dimensions,3):0),dimensions),calculateEpsilonFromBounds(bounds,dimensions)},cache$1=new WeakMap,measureVolume=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$3(geometry)?(geometry=>{let volume=cache$1.get(geometry);return volume||(volume=toPolygons$1(geometry).reduce(((volume,polygon)=>volume+measureSignedVolume(polygon)),0),cache$1.set(geometry,volume),volume)})(geometry):0));return 1===results.length?results[0]:results},measureAggregateVolume=(...geometries)=>{geometries=flatten(geometries);const volumes=measureVolume(geometries);if(1===geometries.length)return volumes;return volumes.reduce(((result,volume)=>result+volume),0)},cache=new WeakMap,measureCached=(geometry,measureFn)=>{let boundingSphere=cache.get(geometry);return boundingSphere||(boundingSphere=measureFn(geometry),0===boundingSphere.length&&(boundingSphere[0]=[0,0,0],boundingSphere[1]=0),cache.set(geometry,boundingSphere),boundingSphere)},measureBoundingSphereOfPoints=points=>{const centroid=[0,0,0];let radius=0;if(points.length>0){let numPoints=0;const temp=[0,0,0];points.forEach((point=>{add$1(centroid,centroid,fromVec2(temp,point,0)),numPoints++})),scale$3(centroid,centroid,1/numPoints),points.forEach((point=>{radius=Math.max(radius,squaredDistance(centroid,point))})),radius=Math.sqrt(radius)}return[centroid,radius]},measureBoundingSphereOfPath2=points=>measureBoundingSphereOfPoints(toPoints$1(points)),measureBoundingSphereOfGeom2=geometry=>measureBoundingSphereOfPoints(toPoints$3(geometry)),measureBoundingSphereOfGeom3=geometry=>{const centroid=[0,0,0];let radius=0;const polygons=toPolygons$1(geometry);if(polygons.length>0){let numVertices=0;polygons.forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{add$1(centroid,centroid,vertex),numVertices++}))})),scale$3(centroid,centroid,1/numVertices),polygons.forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{radius=Math.max(radius,squaredDistance$1(centroid,vertex))}))})),radius=Math.sqrt(radius)}return[centroid,radius]},measureBoundingSphereOfSlice=geometry=>{const centroid=[0,0,0];let radius=0,numVertices=0;return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(centroid,centroid,vertex),numVertices++}))})),numVertices>0&&(scale$3(centroid,centroid,1/numVertices),geometry.contours.forEach((contour=>{contour.forEach((vertex=>{radius=Math.max(radius,squaredDistance$1(centroid,vertex))}))})),radius=Math.sqrt(radius)),[centroid,radius]},measureBoundingSphere=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?measureCached(geometry,measureBoundingSphereOfPath2):isA$5(geometry)?measureCached(geometry,measureBoundingSphereOfGeom2):isA$3(geometry)?measureCached(geometry,measureBoundingSphereOfGeom3):isA(geometry)?measureCached(geometry,measureBoundingSphereOfSlice):[[0,0,0],0]));return 1===results.length?results[0]:results},measureCenter=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>{const bounds=measureBoundingBox(geometry);return[bounds[0][0]+(bounds[1][0]-bounds[0][0])/2,bounds[0][1]+(bounds[1][1]-bounds[0][1])/2,bounds[0][2]+(bounds[1][2]-bounds[0][2])/2]}));return 1===results.length?results[0]:results},cacheOfCenterOfMass=new WeakMap,measureCenterOfMass=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$5(geometry)?(geometry=>{let centerOfMass=cacheOfCenterOfMass.get(geometry);if(void 0!==centerOfMass)return centerOfMass;const sides=toSides(geometry);let area=0,x=0,y=0;if(sides.length>0){for(let i=0;i{let centerOfMass=cacheOfCenterOfMass.get(geometry);if(void 0!==centerOfMass)return centerOfMass;centerOfMass=[0,0,0];const polygons=toPolygons$1(geometry);if(0===polygons.length)return centerOfMass;let totalVolume=0;const vector=[0,0,0];return polygons.forEach((polygon=>{const vertices=polygon.vertices;for(let i=0;i{const results=(geometries=flatten(geometries)).map((geometry=>{const boundingBox=measureBoundingBox(geometry);return[boundingBox[1][0]-boundingBox[0][0],boundingBox[1][1]-boundingBox[0][1],boundingBox[1][2]-boundingBox[0][2]]}));return 1===results.length?results[0]:results},measureEpsilon=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results},isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGT=(value,constant)=>Number.isFinite(value)&&value>constant,isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGT(radius,0))throw new Error("radius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS*EPS)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps));point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})},cuboid=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0,0],size:[2,2,2]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of width, depth and height values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1]||0===size[2])return create$8();return create$8([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((info=>{const vertices=info[0].map((i=>[center[0]+size[0]/2*(2*!!(1&i)-1),center[1]+size[1]/2*(2*!!(2&i)-1),center[2]+size[2]/2*(2*!!(4&i)-1)]));return create$7(vertices)})))},cube=options=>{let{center:center,size:size}=Object.assign({},{center:[0,0,0],size:2},options);if(!isGTE(size,0))throw new Error("size must be positive");return size=[size,size,size],cuboid({center:center,size:size})},cylinderElliptic=options=>{const defaults={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:TAU,segments:32};let{center:center,height:height,startRadius:startRadius,startAngle:startAngle,endRadius:endRadius,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGT(height,0))throw new Error("height must be greater then zero");if(!isNumberArray(startRadius,2))throw new Error("startRadius must be an array of X and Y values");if(!startRadius.every((n=>n>=0)))throw new Error("startRadius values must be positive");if(!isNumberArray(endRadius,2))throw new Error("endRadius must be an array of X and Y values");if(!endRadius.every((n=>n>=0)))throw new Error("endRadius values must be positive");if(endRadius.every((n=>0===n))&&startRadius.every((n=>0===n)))throw new Error("at least one radius must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(startRadius[0],startRadius[1],endRadius[0],endRadius[1]),minAngle=Math.acos((minRadius*minRadius+minRadius*minRadius-EPS*EPS)/(2*minRadius*minRadius));if(rotation{const angle=slice*rotation+startAngle;return scale$3(v1,axisX,radius[0]*cos(angle)),scale$3(v2,axisY,radius[1]*sin(angle)),add$1(v1,v1,v2),scale$3(v3,ray,stack),add$1(v3,v3,start),add$1([0,0,0],v1,v3)},fromVertices=(...vertices)=>{const newVertices=vertices.map((vertex=>add$1([0,0,0],vertex,center)));return create$7(newVertices)},polygons=[];for(let i=0;i0&&startRadius[1]>0&&polygons.push(fromVertices(start,genVertex(0,t1,startRadius),genVertex(0,t0,startRadius))),(startRadius[0]>0||startRadius[1]>0)&&polygons.push(fromVertices(genVertex(0,t0,startRadius),genVertex(0,t1,startRadius),genVertex(1,t0,endRadius))),endRadius[0]>0&&endRadius[1]>0&&polygons.push(fromVertices(end,genVertex(1,t0,endRadius),genVertex(1,t1,endRadius))),(endRadius[0]>0||endRadius[1]>0)&&polygons.push(fromVertices(genVertex(1,t0,endRadius),genVertex(0,t1,startRadius),genVertex(1,t1,endRadius))))}rotation{const{center:center,height:height,radius:radius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},options);if(!isGTE(radius,0))throw new Error("radius must be positive");if(0===height||0===radius)return create$8();return cylinderElliptic({center:center,height:height,startRadius:[radius,radius],endRadius:[radius,radius],segments:segments})},ellipsoid=options=>{const{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(radius,3))throw new Error("radius must be an array of X, Y and Z values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===radius[0]||0===radius[1]||0===radius[2])return create$8();const xVector=scale$3([0,0,0],normalize$1([0,0,0],axes[0]),radius[0]),yVector=scale$3([0,0,0],normalize$1([0,0,0],axes[1]),radius[1]),zVector=scale$3([0,0,0],normalize$1([0,0,0],axes[2]),radius[2]),qSegments=Math.round(segments/4);let prevCylinderVertex;const polygons=[],p1=[0,0,0],p2=[0,0,0];for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(p1,xVector,cos(angle)),scale$3(p2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch;for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);if(slice2>0){let vertex,vertices=[];vertex=subtract$3([0,0,0],scale$3(p1,prevCylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),vertex=subtract$3([0,0,0],scale$3(p1,cylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),slice2{const defaults={points:[],faces:[],colors:void 0,orientation:"outward"},{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},defaults,options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)},geodesicSphere=options=>{let{radius:radius,frequency:frequency}=Object.assign({},{radius:1,frequency:6},options);if(!isGTE(radius,0))throw new Error("radius must be positive");if(!isGTE(frequency,6))throw new Error("frequency must be six or more");if(0===radius)return create$8();frequency=Math.floor(frequency/6);const ci=[[.850651,0,-.525731],[.850651,-0,.525731],[-.850651,-0,.525731],[-.850651,0,-.525731],[0,-.525731,.850651],[0,.525731,.850651],[0,.525731,-.850651],[0,-.525731,-.850651],[-.525731,-.850651,-0],[.525731,-.850651,-0],[.525731,.850651,0],[-.525731,.850651,0]],ti=[[0,9,1],[1,10,0],[6,7,0],[10,6,0],[7,9,0],[5,1,4],[4,1,9],[5,10,1],[2,8,3],[3,11,2],[2,5,4],[4,8,2],[2,11,5],[3,7,6],[6,11,3],[8,7,3],[9,8,4],[11,10,5],[10,11,6],[8,9,7]],geodesicSubDivide=(p,frequency,offset)=>{const p1=p[0],p2=p[1],p3=p[2];let n=offset;const c=[],f=[];for(let i=0;i{const _f=1-f,c=[];for(let i=0;i<3;i++)c[i]=a[i]*_f+b[i]*f;return c};let vertices=[],faces=[],offset=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},polygon=options=>{const{points:points,paths:paths,orientation:orientation}=Object.assign({},{points:[],paths:[],orientation:"counterclockwise"},options);if(!Array.isArray(points)||!Array.isArray(paths))throw new Error("points and paths must be arrays");let listOfPolys=points;Array.isArray(points[0])&&(Array.isArray(points[0][0])||(listOfPolys=[points])),listOfPolys.forEach(((list,i)=>{if(!Array.isArray(list))throw new Error("list of points "+i+" must be an array");if(list.length<3)throw new Error("list of points "+i+" must contain three or more points");list.forEach(((point,j)=>{if(!Array.isArray(point))throw new Error("list of points "+i+", point "+j+" must be an array");if(point.length<2)throw new Error("list of points "+i+", point "+j+" must contain by X and Y values")}))}));let listOfPaths=paths;if(0===paths.length){let count=0;listOfPaths=listOfPolys.map((list=>list.map((point=>count++))))}const allPoints=[];listOfPolys.forEach((list=>list.forEach((point=>allPoints.push(point)))));const outlines=[];listOfPaths.forEach((path=>{const setOfPoints=path.map((index=>allPoints[index]));outlines.push(setOfPoints)}));let geometry=create$a(outlines);return"clockwise"===orientation&&(geometry=reverse$5(geometry)),geometry},rectangle=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])},createCorners=(center,size,radius,segments,slice,positive)=>{const pitch=TAU/4*slice/segments,cosPitch=cos(pitch),sinPitch=sin(pitch),layerSegments=segments-slice;let layerRadius=radius*cosPitch,layerOffset=size[2]-(radius-radius*sinPitch);positive||(layerOffset=radius-radius*sinPitch-size[2]),layerRadius=layerRadius>EPS?layerRadius:0;const corner0=add$1([0,0,0],center,[size[0]-radius,size[1]-radius,layerOffset]),corner1=add$1([0,0,0],center,[radius-size[0],size[1]-radius,layerOffset]),corner2=add$1([0,0,0],center,[radius-size[0],radius-size[1],layerOffset]),corner3=add$1([0,0,0],center,[size[0]-radius,radius-size[1],layerOffset]),corner0Vertices=[],corner1Vertices=[],corner2Vertices=[],corner3Vertices=[];for(let i=0;i<=layerSegments;i++){const point2d=fromAngleRadians([0,0],layerSegments>0?TAU/4*i/layerSegments:0);scale$1(point2d,point2d,layerRadius);const point3d=fromVec2([0,0,0],point2d);corner0Vertices.push(add$1([0,0,0],corner0,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner1Vertices.push(add$1([0,0,0],corner1,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner2Vertices.push(add$1([0,0,0],corner2,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner3Vertices.push(add$1([0,0,0],corner3,point3d))}return positive?[corner0Vertices,corner1Vertices,corner2Vertices,corner3Vertices]:(corner0Vertices.reverse(),corner1Vertices.reverse(),corner2Vertices.reverse(),corner3Vertices.reverse(),[corner3Vertices,corner2Vertices,corner1Vertices,corner0Vertices])},stitchCorners=(previousCorners,currentCorners)=>{const polygons=[];for(let i=0;i{const polygons=[];for(let i=0;i{bottomCorners=(bottomCorners=[bottomCorners[3],bottomCorners[2],bottomCorners[1],bottomCorners[0]]).map((corner=>corner.slice().reverse()));const bottomVertices=[];bottomCorners.forEach((corner=>{corner.forEach((vertex=>bottomVertices.push(vertex)))}));const topVertices=[];topCorners.forEach((corner=>{corner.forEach((vertex=>topVertices.push(vertex)))}));const polygons=[];for(let i=0;i{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0,0],size:[2,2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of X, Y and Z values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1]||0===size[2])return create$8();if(0===roundRadius)return cuboid({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS||roundRadius>size[2]-EPS)throw new Error("roundRadius must be smaller than the radius of all dimensions");segments=Math.floor(segments/4);let prevCornersPos=null,prevCornersNeg=null,polygons=[];for(let slice=0;slice<=segments;slice++){const cornersPos=createCorners(center,size,roundRadius,segments,slice,!0),cornersNeg=createCorners(center,size,roundRadius,segments,slice,!1);if(0===slice&&(polygons=polygons.concat(stitchSides(cornersNeg,cornersPos))),prevCornersPos&&(polygons=polygons.concat(stitchCorners(prevCornersPos,cornersPos),stitchWalls(prevCornersPos,cornersPos))),prevCornersNeg&&(polygons=polygons.concat(stitchCorners(prevCornersNeg,cornersNeg),stitchWalls(prevCornersNeg,cornersNeg))),slice===segments){let vertices=cornersPos.map((corner=>corner[0]));polygons.push(create$7(vertices)),vertices=cornersNeg.map((corner=>corner[0])),polygons.push(create$7(vertices))}prevCornersPos=cornersPos,prevCornersNeg=cornersNeg}return create$8(polygons)},roundedCylinder=options=>{const{center:center,height:height,radius:radius,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,roundRadius:.2,segments:32},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGTE(height,0))throw new Error("height must be positive");if(!isGTE(radius,0))throw new Error("radius must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(roundRadius>radius)throw new Error("roundRadius must be smaller than the radius");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===height||0===radius)return create$8();if(0===roundRadius)return cylinder({center:center,height:height,radius:radius});const start=[0,0,-height/2],end=[0,0,height/2],direction=subtract$3([0,0,0],end,start);if(2*roundRadius>length$2(direction)-EPS)throw new Error("height must be larger than twice roundRadius");let defaultNormal;defaultNormal=Math.abs(direction[0])>Math.abs(direction[1])?fromValues$3(0,1,0):fromValues$3(1,0,0);const zVector=scale$3([0,0,0],normalize$1([0,0,0],direction),roundRadius),xVector=scale$3([0,0,0],normalize$1([0,0,0],cross$1([0,0,0],zVector,defaultNormal)),radius),yVector=scale$3([0,0,0],normalize$1([0,0,0],cross$1([0,0,0],xVector,zVector)),radius);add$1(start,start,zVector),subtract$3(end,end,zVector);const qSegments=Math.floor(.25*segments),fromVertices=vertices=>{const newVertices=vertices.map((vertex=>add$1(vertex,vertex,center)));return create$7(newVertices)},polygons=[],v1=[0,0,0],v2=[0,0,0];let prevCylinderVertex;for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(v1,xVector,cos(angle)),scale$3(v2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch,vertex,vertices=[];vertices.push(add$1([0,0,0],start,cylinderVertex)),vertices.push(add$1([0,0,0],start,prevCylinderVertex)),vertices.push(add$1([0,0,0],end,prevCylinderVertex)),vertices.push(add$1([0,0,0],end,cylinderVertex)),polygons.push(fromVertices(vertices));for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);slice2>0&&(vertices=[],vertex=add$1([0,0,0],start,subtract$3(v1,scale$3(v1,prevCylinderVertex,prevCosPitch),scale$3(v2,zVector,prevSinPitch))),vertices.push(vertex),vertex=add$1([0,0,0],start,subtract$3(v1,scale$3(v1,cylinderVertex,prevCosPitch),scale$3(v2,zVector,prevSinPitch))),vertices.push(vertex),slice2{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1])return create$a();if(0===roundRadius)return rectangle({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS)throw new Error("roundRadius must be smaller than the radius of all dimensions");const cornerSegments=Math.floor(segments/4),corner0=add([0,0],center,[size[0]-roundRadius,size[1]-roundRadius]),corner1=add([0,0],center,[roundRadius-size[0],size[1]-roundRadius]),corner2=add([0,0],center,[roundRadius-size[0],roundRadius-size[1]]),corner3=add([0,0],center,[size[0]-roundRadius,roundRadius-size[1]]),corner0Points=[],corner1Points=[],corner2Points=[],corner3Points=[];for(let i=0;i<=cornerSegments;i++){const point=fromAngleRadians([0,0],TAU/4*i/cornerSegments);scale$1(point,point,roundRadius),corner0Points.push(add([0,0],corner0,point)),rotate$1(point,point,[0,0],TAU/4),corner1Points.push(add([0,0],corner1,point)),rotate$1(point,point,[0,0],TAU/4),corner2Points.push(add([0,0],corner2,point)),rotate$1(point,point,[0,0],TAU/4),corner3Points.push(add([0,0],corner3,point))}const points=corner0Points.concat(corner1Points,corner2Points,corner3Points);return create$a([points])},sphere=options=>{let{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius,radius],ellipsoid({center:center,radius:radius,segments:segments,axes:axes})},square=options=>{let{center:center,size:size}=Object.assign({},{center:[0,0],size:2},options);if(!isGTE(size,0))throw new Error("size must be positive");return size=[size,size],rectangle({center:center,size:size})},getPoints=(vertices,radius,startAngle,center)=>{const a=TAU/vertices,points=[];for(let i=0;i{let{center:center,vertices:vertices,outerRadius:outerRadius,innerRadius:innerRadius,density:density,startAngle:startAngle}=Object.assign({},{center:[0,0],vertices:5,outerRadius:1,innerRadius:0,density:2,startAngle:0},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGTE(vertices,2))throw new Error("vertices must be two or more");if(!isGT(outerRadius,0))throw new Error("outerRadius must be greater than zero");if(!isGTE(innerRadius,0))throw new Error("innerRadius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be greater than zero");if(vertices=Math.floor(vertices),density=Math.floor(density),startAngle%=TAU,0===innerRadius){if(!isGTE(density,2))throw new Error("density must be two or more");innerRadius=outerRadius*((vertices,density)=>vertices>0&&density>1&&density{const{origin:origin,normal:normal}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},options),planeOfMirror=fromNormalAndPoint([0,0,0,0],normal,origin);if(Number.isNaN(planeOfMirror[0]))throw new Error("the given origin and normal do not define a proper plane");const matrix=mirrorByPlane([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],planeOfMirror),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?mirror(options,...object):object));return 1===results.length?results[0]:results},mirrorX=(...objects)=>mirror({normal:[1,0,0]},...objects),mirrorY=(...objects)=>mirror({normal:[0,1,0]},...objects),mirrorZ=(...objects)=>mirror({normal:[0,0,1]},...objects),gcd=(a,b)=>a===b?a:a{const multiple=newLength/edges.length;if(1===multiple)return edges;const divisor=fromValues$3(multiple,multiple,multiple),newEdges=[];return edges.forEach((edge=>{const increment=subtract$3([0,0,0],edge[1],edge[0]);divide$1(increment,increment,divisor);let prev=edge[0];for(let i=1;i<=multiple;++i){const next=add$1([0,0,0],prev,increment);newEdges.push([prev,next]),prev=next}})),newEdges},EPSAREA=EPS*EPS/2*Math.sin(Math.PI/3),extrudeWalls=(slice0,slice1)=>{let edges0=toEdges(slice0),edges1=toEdges(slice1);if(edges0.length!==edges1.length){const newLength=(a=edges0.length,b=edges1.length,a*b/gcd(a,b));newLength!==edges0.length&&(edges0=repartitionEdges(newLength,edges0)),newLength!==edges1.length&&(edges1=repartitionEdges(newLength,edges1))}var a,b;const walls=[];return edges0.forEach(((edge0,i)=>{const edge1=edges1[i],poly0=create$7([edge0[0],edge0[1],edge1[1]]),poly0area=measureArea$2(poly0);Number.isFinite(poly0area)&&poly0area>EPSAREA&&walls.push(poly0);const poly1=create$7([edge0[0],edge1[1],edge1[0]]),poly1area=measureArea$2(poly1);Number.isFinite(poly1area)&&poly1area>EPSAREA&&walls.push(poly1)})),walls},defaultCallback=(progress,index,base)=>{let baseSlice=null;return isA$5(base)&&(baseSlice=fromGeom2(base)),isA$4(base)&&(baseSlice=fromVertices(toVertices$1(base))),0===progress||1===progress?transform$3(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[0,0,progress]),baseSlice):null},extrudeFromSlices=(options,base)=>{const defaults={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,callback:defaultCallback},{numberOfSlices:numberOfSlices,capStart:capStart,capEnd:capEnd,close:close,callback:generate}=Object.assign({},defaults,options);if(numberOfSlices<2)throw new Error("numberOfSlices must be 2 or more");const sMax=numberOfSlices-1;let startSlice=null,endSlice=null,prevSlice=null,polygons=[];for(let s=0;s{const defaults={segments:12,startAngle:0,angle:TAU,overflow:"cap"};let{segments:segments,startAngle:startAngle,angle:angle,overflow:overflow}=Object.assign({},defaults,options);if(segments<3)throw new Error("segments must be greater then 3");startAngle=Math.abs(startAngle)>TAU?startAngle%TAU:startAngle,angle=Math.abs(angle)>TAU?angle%TAU:angle;let endAngle=startAngle+angle;if(endAngle=Math.abs(endAngle)>TAU?endAngle%TAU:endAngle,endAnglesegments*anglePerSegment&&segments++}let shapeSides=toSides(geometry);if(0===shapeSides.length)return create$8();let sliceGeometry=geometry;const pointsWithNegativeX=shapeSides.filter((s=>s[0][0]<0)),pointsWithPositiveX=shapeSides.filter((s=>s[0][0]>=0));pointsWithNegativeX.length>0&&pointsWithPositiveX.length>0&&"cap"===overflow&&(pointsWithNegativeX.length>pointsWithPositiveX.length?(shapeSides=shapeSides.map((side=>{let point0=side[0],point1=side[1];return point0=[Math.min(point0[0],0),point0[1]],point1=[Math.min(point1[0],0),point1[1]],[point0,point1]})),sliceGeometry=fromSides(shapeSides),sliceGeometry=mirrorX(sliceGeometry)):pointsWithPositiveX.length>=pointsWithNegativeX.length&&(shapeSides=shapeSides.map((side=>{let point0=side[0],point1=side[1];return point0=[Math.max(point0[0],0),point0[1]],point1=[Math.max(point1[0],0),point1[1]],[point0,point1]})),sliceGeometry=fromSides(shapeSides)));const rotationPerSlice=totalRotation/segments,isCapped=Math.abs(totalRotation){let Zrotation=rotationPerSlice*index+startAngle;return totalRotation===TAU&&index===segments&&(Zrotation=startAngle),multiply$1(matrix,fromZRotation(matrix,Zrotation),fromXRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],TAU/4)),transform$3(matrix,base)}};const output=extrudeFromSlices(options,baseSlice);return geometry.color&&(output.color=geometry.color),output},rotate=(angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?rotate(angles,...object):object));return 1===results.length?results[0]:results},rotateX=(angle,...objects)=>rotate([angle,0,0],...objects),rotateY=(angle,...objects)=>rotate([0,angle,0],...objects),rotateZ=(angle,...objects)=>rotate([0,0,angle],...objects),translate=(offset,...objects)=>{if(!Array.isArray(offset))throw new Error("offset must be an array");for(offset=offset.slice();offset.length<3;)offset.push(0);const matrix=fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offset),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?translate(offset,...object):object));return 1===results.length?results[0]:results},translateX=(offset,...objects)=>translate([offset,0,0],...objects),translateY=(offset,...objects)=>translate([0,offset,0],...objects),translateZ=(offset,...objects)=>translate([0,0,offset],...objects),torus=options=>{const defaults={innerRadius:1,innerSegments:32,outerRadius:4,outerSegments:32,innerRotation:0,startAngle:0,outerRotation:TAU},{innerRadius:innerRadius,innerSegments:innerSegments,outerRadius:outerRadius,outerSegments:outerSegments,innerRotation:innerRotation,startAngle:startAngle,outerRotation:outerRotation}=Object.assign({},defaults,options);if(!isGT(innerRadius,0))throw new Error("innerRadius must be greater than zero");if(!isGTE(innerSegments,3))throw new Error("innerSegments must be three or more");if(!isGT(outerRadius,0))throw new Error("outerRadius must be greater than zero");if(!isGTE(outerSegments,3))throw new Error("outerSegments must be three or more");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGT(outerRotation,0))throw new Error("outerRotation must be greater than zero");if(innerRadius>=outerRadius)throw new Error("inner circle is too large to rotate about the outer circle");let innerCircle=circle({radius:innerRadius,segments:innerSegments});0!==innerRotation&&(innerCircle=rotate([0,0,innerRotation],innerCircle)),innerCircle=translate([outerRadius,0],innerCircle);return extrudeRotate({startAngle:startAngle,angle:outerRotation,segments:outerSegments},innerCircle)},solveAngleFromSSS=(a,b,c)=>Math.acos((a*a+b*b-c*c)/(2*a*b)),solveSAS=values=>{const c=values[0],B=values[1],a=values[2],b=((a,C,b)=>C>NEPS?Math.sqrt(a*a+b*b-2*a*b*Math.cos(C)):Math.sqrt((a-b)*(a-b)+a*b*C*C*(1-C*C/12)))(c,B,a),A=solveAngleFromSSS(b,c,a),C=Math.PI-A-B;return createTriangle(A,B,C,a,b,c)},createTriangle=(A,B,C,a,b,c)=>{const p0=fromValues$2(0,0),p1=fromValues$2(c,0),p2=fromValues$2(a,0);return add(p2,rotate$1(p2,p2,[0,0],Math.PI-B),p1),create$a([[p0,p1,p2]])},triangle=options=>{let{type:type,values:values}=Object.assign({},{type:"SSS",values:[1,1,1]},options);if("string"!=typeof type)throw new Error("triangle type must be a string");if(type=type.toUpperCase(),"A"!==type[0]&&"S"!==type[0]||"A"!==type[1]&&"S"!==type[1]||"A"!==type[2]&&"S"!==type[2])throw new Error("triangle type must contain three letters; A or S");if(!isNumberArray(values,3))throw new Error("triangle values must contain three values");if(!values.every((n=>n>0)))throw new Error("triangle values must be greater than zero");switch(type){case"AAA":return(angles=>{if(Math.abs(angles[0]+angles[1]+angles[2]-Math.PI)>NEPS)throw new Error("AAA triangles require angles that sum to PI");const A=angles[0],B=angles[1],C=Math.PI-A-B,a=1/Math.sin(C)*Math.sin(A),b=1/Math.sin(C)*Math.sin(B);return createTriangle(A,B,C,a,b,1)})(values);case"AAS":return(values=>{const A=values[0],B=values[1],C=Math.PI+NEPS-A-B;if(C{const A=values[0],B=values[2],C=Math.PI+NEPS-A-B;if(C{const c=values[0],a=values[1],C=values[2],A=Math.asin(a*Math.sin(C)/c),B=Math.PI-A-C,b=c/Math.sin(C)*Math.sin(B);return createTriangle(A,B,C,a,b,c)})(values);case"SSS":return(lengths=>{const a=lengths[1],b=lengths[2],c=lengths[0];if(a+b<=c||b+c<=a||c+a<=b)throw new Error("SSS triangle is incorrect, as the longest side is longer than the sum of the other sides");const A=solveAngleFromSSS(b,c,a),B=solveAngleFromSSS(c,a,b),C=Math.PI-A-B;return createTriangle(A,B,C,a,b,c)})(values);default:throw new Error("invalid triangle type, try again")}},simplex={height:14,32:[16],33:[10,5,21,5,7,void 0,5,2,4,1,5,0,6,1,5,2],34:[16,4,21,4,14,void 0,12,21,12,14],35:[21,11,25,4,-7,void 0,17,25,10,-7,void 0,4,12,18,12,void 0,3,6,17,6],36:[20,8,25,8,-4,void 0,12,25,12,-4,void 0,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],37:[24,21,21,3,0,void 0,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,void 0,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7],38:[26,23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2],39:[10,5,19,4,20,5,21,6,20,6,18,5,16,4,15],40:[14,11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7],41:[14,3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7],42:[16,8,21,8,9,void 0,3,18,13,12,void 0,13,18,3,12],43:[26,13,18,13,0,void 0,4,9,22,9],44:[10,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],45:[26,4,9,22,9],46:[10,5,2,4,1,5,0,6,1,5,2],47:[22,20,25,2,-7],48:[20,9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21],49:[20,6,17,8,18,11,21,11,0],50:[20,4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0],51:[20,5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],52:[20,13,21,3,7,18,7,void 0,13,21,13,0],53:[20,15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],54:[20,16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7],55:[20,17,21,7,0,void 0,3,21,17,21],56:[20,8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21],57:[20,16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3],58:[10,5,14,4,13,5,12,6,13,5,14,void 0,5,2,4,1,5,0,6,1,5,2],59:[10,5,14,4,13,5,12,6,13,5,14,void 0,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],60:[24,20,18,4,9,20,0],61:[26,4,12,22,12,void 0,4,6,22,6],62:[24,4,18,20,9,4,0],63:[18,3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,void 0,9,2,8,1,9,0,10,1,9,2],64:[27,18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,void 0,12,16,10,14,9,11,9,8,10,6,11,5,void 0,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,void 0,19,16,18,8,18,6,19,5],65:[18,9,21,1,0,void 0,9,21,17,0,void 0,4,7,14,7],66:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,void 0,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0],67:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5],68:[21,4,21,4,0,void 0,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0],69:[19,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11,void 0,4,0,17,0],70:[18,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11],71:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,void 0,13,8,18,8],72:[22,4,21,4,0,void 0,18,21,18,0,void 0,4,11,18,11],73:[8,4,21,4,0],74:[16,12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7],75:[21,4,21,4,0,void 0,18,21,4,7,void 0,9,12,18,0],76:[17,4,21,4,0,void 0,4,0,16,0],77:[24,4,21,4,0,void 0,4,21,12,0,void 0,20,21,12,0,void 0,20,21,20,0],78:[22,4,21,4,0,void 0,4,21,18,0,void 0,18,21,18,0],79:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21],80:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10],81:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,void 0,12,4,18,-2],82:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,void 0,11,11,18,0],83:[20,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],84:[16,8,21,8,0,void 0,1,21,15,21],85:[22,4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21],86:[18,1,21,9,0,void 0,17,21,9,0],87:[24,2,21,7,0,void 0,12,21,7,0,void 0,12,21,17,0,void 0,22,21,17,0],88:[20,3,21,17,0,void 0,17,21,3,0],89:[18,1,21,9,11,9,0,void 0,17,21,9,11],90:[20,17,21,3,0,void 0,3,21,17,21,void 0,3,0,17,0],91:[14,4,25,4,-7,void 0,5,25,5,-7,void 0,4,25,11,25,void 0,4,-7,11,-7],92:[14,0,21,14,-3],93:[14,9,25,9,-7,void 0,10,25,10,-7,void 0,3,25,10,25,void 0,3,-7,10,-7],94:[16,6,15,8,18,10,15,void 0,3,12,8,17,13,12,void 0,8,17,8,0],95:[16,0,-2,16,-2],96:[10,6,21,5,20,4,18,4,16,5,15,6,16,5,17],97:[19,15,14,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],98:[19,4,21,4,0,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],99:[18,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],100:[19,15,21,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],101:[18,3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],102:[12,10,21,8,21,6,20,5,17,5,0,void 0,2,14,9,14],103:[19,15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],104:[19,4,21,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],105:[8,3,21,4,20,5,21,4,22,3,21,void 0,4,14,4,0],106:[10,5,21,6,20,7,21,6,22,5,21,void 0,6,14,6,-3,5,-6,3,-7,1,-7],107:[17,4,21,4,0,void 0,14,14,4,4,void 0,8,8,15,0],108:[8,4,21,4,0],109:[30,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0,void 0,15,10,18,13,20,14,23,14,25,13,26,10,26,0],110:[19,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],111:[19,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14],112:[19,4,14,4,-7,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],113:[19,15,14,15,-7,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],114:[13,4,14,4,0,void 0,4,8,5,11,7,13,9,14,12,14],115:[17,14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3],116:[12,5,21,5,4,6,1,8,0,10,0,void 0,2,14,9,14],117:[19,4,14,4,4,5,1,7,0,10,0,12,1,15,4,void 0,15,14,15,0],118:[16,2,14,8,0,void 0,14,14,8,0],119:[22,3,14,7,0,void 0,11,14,7,0,void 0,11,14,15,0,void 0,19,14,15,0],120:[17,3,14,14,0,void 0,14,14,3,0],121:[16,2,14,8,0,void 0,14,14,8,0,6,-4,4,-6,2,-7,1,-7],122:[17,14,14,3,0,void 0,3,14,14,14,void 0,3,0,14,0],123:[14,9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,void 0,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,void 0,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7],124:[8,4,25,4,-7],125:[14,5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,void 0,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,void 0,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7],126:[24,3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,void 0,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]},defaultsVectorParams$1={xOffset:0,yOffset:0,font:simplex,height:14,extrudeOffset:0},vectorChar=(options,text)=>{const{xOffset:xOffset,yOffset:yOffset,font:font,height:height,extrudeOffset:extrudeOffset}=Object.assign({},defaultsVectorParams$1,options);if("string"!=typeof text||1!==text.length)throw new Error("text must be a single character");let code=text.charCodeAt(0);code&&font[code]||(code=63);const glyph=[].concat(font[code]),ratio=(height-extrudeOffset)/font.height,extrudeYOffset=extrudeOffset/2,width=glyph.shift()*ratio,paths=[];let polyline=[];for(let i=0,il=glyph.length;i{const{x:x,y:y}=Object.assign({x:0,y:0},options);return identity(matrix),translate$1(matrix,matrix,[x,y,0]),line.chars=line.chars.map((vchar=>(vchar.paths=vchar.paths.map((path=>transform$5(matrix,path))),vchar))),line},vectorText=(options,text)=>{const{xOffset:xOffset,yOffset:yOffset,font:font,height:height,align:align,extrudeOffset:extrudeOffset,lineSpacing:lineSpacing,letterSpacing:letterSpacing}=Object.assign({},defaultsVectorParams,options);if("string"!=typeof text)throw new Error("text must be a string");const extraLetterSpacing=height*letterSpacing;let maxWidth=0,line={width:0,height:0,chars:[]},lines=[];const pushLine=()=>{maxWidth=Math.max(maxWidth,line.width),line.chars.length&&lines.push(line),line={width:0,height:0,chars:[]}};let vchar,x=xOffset,y=yOffset;const il=text.length;for(let i=0;i{const diff=maxWidth-line.width;return"right"===align?translateLine({x:diff},line):"center"===align?translateLine({x:diff/2},line):line})),lines},degToRad=degrees=>.017453292519943295*degrees,radiusToSegments=(radius,minimumLength,minimumAngle)=>{const ss=minimumLength>0?radius*TAU/minimumLength:0,as=minimumAngle>0?TAU/minimumAngle:0;return Math.ceil(Math.max(ss,as,4))},radToDeg=radians=>57.29577951308232*radians,areAllShapesTheSameType=shapes=>{let previousType;for(const shape of shapes){let currentType=0;if(isA$5(shape)&&(currentType=1),isA$3(shape)&&(currentType=2),isA$2(shape)&&(currentType=3),previousType&¤tType!==previousType)return!1;previousType=currentType}return!0},coalesce=arr=>flattenHelper(arr,[]),flattenHelper=(arr,out)=>(Array.isArray(arr)?arr.forEach((child=>flattenHelper(child,out))):null!=arr&&void 0!==arr&&out.push(arr),out),DEFAULT_COMPARE=(a,b)=>a>b?1:a{const N=new Node$1(null,null);let l=N,r=N;for(;;){const cmp=comparator(i,t.key);if(cmp<0){if(null===t.left)break;if(comparator(i,t.left.key)<0){const y=t.left;if(t.left=y.right,y.right=t,null===(t=y).left)break}r.left=t,r=t,t=t.left}else{if(!(cmp>0))break;if(null===t.right)break;if(comparator(i,t.right.key)>0){const y=t.right;if(t.right=y.left,y.left=t,null===(t=y).right)break}l.right=t,l=t,t=t.right}}return l.right=t.left,r.left=t.right,t.left=N.right,t.right=N.left,t},insert=(i,data,t,comparator)=>{const node=new Node$1(i,data);if(null===t)return node.left=node.right=null,node;const cmp=comparator(i,(t=splay(i,t,comparator)).key);return cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>=0&&(node.right=t.right,node.left=t,t.right=null),node},split=(key,v,comparator)=>{let left=null,right=null;if(v){const cmp=comparator((v=splay(key,v,comparator)).key,key);0===cmp?(left=v.left,right=v.right):cmp<0?(right=v.right,v.right=null,left=v):(left=v.left,v.left=null,right=v)}return{left:left,right:right}},printRow=(root,prefix,isTail,out,printNode)=>{if(root){out(`${prefix}${isTail?"└── ":"├── "}${printNode(root)}\n`);const indent=prefix+(isTail?" ":"│ ");root.left&&printRow(root.left,indent,!1,out,printNode),root.right&&printRow(root.right,indent,!0,out,printNode)}};class Tree$1{constructor(comparator=DEFAULT_COMPARE){this._comparator=comparator,this._root=null,this._size=0}insert(key,data){return this._size++,this._root=insert(key,data,this._root,this._comparator),this._root}add(key,data){const node=new Node$1(key,data);null===this._root&&(node.left=node.right=null,this._size++,this._root=node);const comparator=this._comparator,t=splay(key,this._root,comparator),cmp=comparator(key,t.key);return 0===cmp?this._root=t:(cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>0&&(node.right=t.right,node.left=t,t.right=null),this._size++,this._root=node),this._root}remove(key){this._root=this._remove(key,this._root,this._comparator)}_remove(i,t,comparator){let x;if(null===t)return null;return 0===comparator(i,(t=splay(i,t,comparator)).key)?(null===t.left?x=t.right:(x=splay(i,t.left,comparator),x.right=t.right),this._size--,x):t}pop(){let node=this._root;if(node){for(;node.left;)node=node.left;return this._root=splay(node.key,this._root,this._comparator),this._root=this._remove(node.key,this._root,this._comparator),{key:node.key,data:node.data}}return null}findStatic(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return current;current=cmp<0?current.left:current.right}return null}find(key){return this._root&&(this._root=splay(key,this._root,this._comparator),0!==this._comparator(key,this._root.key))?null:this._root}contains(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return!0;current=cmp<0?current.left:current.right}return!1}forEach(visitor,ctx){let current=this._root;const Q=[];let done=!1;for(;!done;)null!==current?(Q.push(current),current=current.left):0!==Q.length?(current=Q.pop(),visitor.call(ctx,current),current=current.right):done=!0;return this}range(low,high,fn,ctx){const Q=[],compare=this._comparator;let cmp,node=this._root;for(;0!==Q.length||node;)if(node)Q.push(node),node=node.left;else{if(node=Q.pop(),cmp=compare(node.key,high),cmp>0)break;if(compare(node.key,low)>=0&&fn.call(ctx,node))return this;node=node.right}return this}keys(){const keys=[];return this.forEach((({key:key})=>keys.push(key))),keys}values(){const values=[];return this.forEach((({data:data})=>values.push(data))),values}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(index){let current=this._root,done=!1,i=0;const Q=[];for(;!done;)if(current)Q.push(current),current=current.left;else if(Q.length>0){if(current=Q.pop(),i===index)return current;i++,current=current.right}else done=!0;return null}next(d){let root=this._root,successor=null;if(d.right){for(successor=d.right;successor.left;)successor=successor.left;return successor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?(successor=root,root=root.left):root=root.right}return successor}prev(d){let root=this._root,predecessor=null;if(null!==d.left){for(predecessor=d.left;predecessor.right;)predecessor=predecessor.right;return predecessor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?root=root.left:(predecessor=root,root=root.right)}return predecessor}clear(){return this._root=null,this._size=0,this}toList(){return toList(this._root)}load(keys,values=[],presort=!1){let size=keys.length;const comparator=this._comparator;if(presort&&sort(keys,values,0,size-1,comparator),null===this._root)this._root=loadRecursive(keys,values,0,size),this._size=size;else{const mergedList=mergeLists(this.toList(),createList(keys,values),comparator);size=this._size+size,this._root=sortedListToBST({head:mergedList},0,size)}return this}isEmpty(){return null===this._root}size(){return this._size}root(){return this._root}toString(printNode=(n=>String(n.key))){const out=[];return printRow(this._root,"",!0,(v=>out.push(v)),printNode),out.join("")}update(key,newKey,newData){const comparator=this._comparator;let{left:left,right:right}=split(key,this._root,comparator);comparator(key,newKey)<0?right=insert(newKey,newData,right,comparator):left=insert(newKey,newData,left,comparator),this._root=((left,right,comparator)=>null===right?left:(null===left||((right=splay(left.key,right,comparator)).left=left),right))(left,right,comparator)}split(key){return split(key,this._root,this._comparator)}*[Symbol.iterator](){let n=this.minNode();for(;n;)yield n,n=this.next(n)}}const loadRecursive=(keys,values,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),key=keys[middle],data=values[middle],node=new Node$1(key,data);return node.left=loadRecursive(keys,values,start,middle),node.right=loadRecursive(keys,values,middle+1,end),node}return null},createList=(keys,values)=>{const head=new Node$1(null,null);let p=head;for(let i=0;i{let current=root;const Q=[];let done=!1;const head=new Node$1(null,null);let p=head;for(;!done;)current?(Q.push(current),current=current.left):Q.length>0?(current=p=p.next=Q.pop(),current=current.right):done=!0;return p.next=null,head.next},sortedListToBST=(list,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),left=sortedListToBST(list,start,middle),root=list.head;return root.left=left,list.head=list.head.next,root.right=sortedListToBST(list,middle+1,end),root}return null},mergeLists=(l1,l2,compare)=>{const head=new Node$1(null,null);let p=head,p1=l1,p2=l2;for(;null!==p1&&null!==p2;)compare(p1.key,p2.key)<0?(p.next=p1,p1=p1.next):(p.next=p2,p2=p2.next),p=p.next;return null!==p1?p.next=p1:null!==p2&&(p.next=p2),head.next},sort=(keys,values,left,right,compare)=>{if(left>=right)return;const pivot=keys[left+right>>1];let i=left-1,j=right+1;for(;;){do{i++}while(compare(keys[i],pivot)<0);do{j--}while(compare(keys[j],pivot)>0);if(i>=j)break;let tmp=keys[i];keys[i]=keys[j],keys[j]=tmp,tmp=values[i],values[i]=values[j],values[j]=tmp}sort(keys,values,left,j,compare),sort(keys,values,j+1,right,compare)},computeFields=(event,prev,operation)=>{null===prev?(event.inOut=!1,event.otherInOut=!0):(event.isSubject===prev.isSubject?(event.inOut=!prev.inOut,event.otherInOut=prev.otherInOut):(event.inOut=!prev.otherInOut,event.otherInOut=prev.isVertical()?!prev.inOut:prev.inOut),prev&&(event.prevInResult=!inResult(prev,operation)||prev.isVertical()?prev.prevInResult:prev));const isInResult=inResult(event,operation);event.resultTransition=isInResult?determineResultTransition(event,operation):0},inResult=(event,operation)=>{switch(event.type){case 0:switch(operation){case 0:return!event.otherInOut;case 1:return event.otherInOut;case 2:return event.isSubject&&event.otherInOut||!event.isSubject&&!event.otherInOut;case 3:return!0}break;case 2:return 0===operation||1===operation;case 3:return 2===operation;case 1:return!1}return!1},determineResultTransition=(event,operation)=>{const thisIn=!event.inOut,thatIn=!event.otherInOut;let isIn;switch(operation){case 0:isIn=thisIn&&thatIn;break;case 1:isIn=thisIn||thatIn;break;case 3:isIn=thisIn^thatIn;break;case 2:isIn=event.isSubject?thisIn&&!thatIn:thatIn&&!thisIn}return isIn?1:-1};class SweepEvent{constructor(point,left,otherEvent,isSubject,edgeType){this.left=left,this.point=point,this.otherEvent=otherEvent,this.isSubject=isSubject,this.type=edgeType||0,this.inOut=!1,this.otherInOut=!1,this.prevInResult=null,this.resultTransition=0,this.otherPos=-1,this.outputContourId=-1,this.isExteriorRing=!0}isBelow(p){const p0=this.point,p1=this.otherEvent.point;return this.left?(p0[0]-p[0])*(p1[1]-p[1])-(p1[0]-p[0])*(p0[1]-p[1])>0:(p1[0]-p[0])*(p0[1]-p[1])-(p0[0]-p[0])*(p1[1]-p[1])>0}isAbove(p){return!this.isBelow(p)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return 0!==this.resultTransition}clone(){const copy=new SweepEvent(this.point,this.left,this.otherEvent,this.isSubject,this.type);return copy.contourId=this.contourId,copy.resultTransition=this.resultTransition,copy.prevInResult=this.prevInResult,copy.isExteriorRing=this.isExteriorRing,copy.inOut=this.inOut,copy.otherInOut=this.otherInOut,copy}}const signedArea=(p0,p1,p2)=>{const res=(ax=p0[0],ay=p0[1],bx=p1[0],by=p1[1],cx=p2[0],cy=p2[1],(ay-cy)*(bx-cx)-(ax-cx)*(by-cy));var ax,ay,bx,by,cx,cy;return res>0?-1:res<0?1:0},compareEvents=(e1,e2)=>{const p1=e1.point,p2=e2.point;return p1[0]>p2[0]?1:p1[0]p2[1]?1:-1:specialCases(e1,e2,p1)},specialCases=(e1,e2,p1,p2)=>e1.left!==e2.left?e1.left?1:-1:0!==signedArea(p1,e1.otherEvent.point,e2.otherEvent.point)?e1.isBelow(e2.otherEvent.point)?-1:1:!e1.isSubject&&e2.isSubject?1:-1,divideSegment=(se,p,queue)=>{const r=new SweepEvent(p,!1,se,se.isSubject),l=new SweepEvent(p,!0,se.otherEvent,se.isSubject);return r.contourId=l.contourId=se.contourId,compareEvents(l,se.otherEvent)>0&&(se.otherEvent.left=!0,l.left=!1),se.otherEvent.otherEvent=l,se.otherEvent=r,queue.push(l),queue.push(r),queue},crossProduct=(a,b)=>a[0]*b[1]-a[1]*b[0],possibleIntersection=(se1,se2,queue)=>{const inter=((a1,a2,b1,b2,noEndpointTouch)=>{const va=[a2[0]-a1[0],a2[1]-a1[1]],vb=[b2[0]-b1[0],b2[1]-b1[1]],toPoint=(p,s,d)=>[p[0]+s*d[0],p[1]+s*d[1]],e=[b1[0]-a1[0],b1[1]-a1[1]];let kross=crossProduct(va,vb),sqrKross=kross*kross;const sqrLenA=dot$1(va,va);if(sqrKross>0){const s=crossProduct(e,vb)/kross;if(s<0||s>1)return null;const t=crossProduct(e,va)/kross;return t<0||t>1?null:0===s||1===s?noEndpointTouch?null:[toPoint(a1,s,va)]:0===t||1===t?noEndpointTouch?null:[toPoint(b1,t,vb)]:[toPoint(a1,s,va)]}if(kross=crossProduct(e,va),sqrKross=kross*kross,sqrKross>0)return null;const sa=dot$1(va,e)/sqrLenA,sb=sa+dot$1(va,vb)/sqrLenA,smin=Math.min(sa,sb),smax=Math.max(sa,sb);return smin<=1&&smax>=0?1===smin?noEndpointTouch?null:[toPoint(a1,smin>0?smin:0,va)]:0===smax?noEndpointTouch?null:[toPoint(a1,smax<1?smax:1,va)]:noEndpointTouch&&0===smin&&1===smax?null:[toPoint(a1,smin>0?smin:0,va),toPoint(a1,smax<1?smax:1,va)]:null})(se1.point,se1.otherEvent.point,se2.point,se2.otherEvent.point),nIntersections=inter?inter.length:0;if(0===nIntersections)return 0;if(1===nIntersections&&(equals$6(se1.point,se2.point)||equals$6(se1.otherEvent.point,se2.otherEvent.point)))return 0;if(2===nIntersections&&se1.isSubject===se2.isSubject)return 0;if(1===nIntersections)return equals$6(se1.point,inter[0])||equals$6(se1.otherEvent.point,inter[0])||divideSegment(se1,inter[0],queue),equals$6(se2.point,inter[0])||equals$6(se2.otherEvent.point,inter[0])||divideSegment(se2,inter[0],queue),1;const events=[];let leftCoincide=!1,rightCoincide=!1;return equals$6(se1.point,se2.point)?leftCoincide=!0:1===compareEvents(se1,se2)?events.push(se2,se1):events.push(se1,se2),equals$6(se1.otherEvent.point,se2.otherEvent.point)?rightCoincide=!0:1===compareEvents(se1.otherEvent,se2.otherEvent)?events.push(se2.otherEvent,se1.otherEvent):events.push(se1.otherEvent,se2.otherEvent),leftCoincide&&rightCoincide||leftCoincide?(se2.type=1,se1.type=se2.inOut===se1.inOut?2:3,leftCoincide&&!rightCoincide&÷Segment(events[1].otherEvent,events[0].point,queue),2):rightCoincide?(divideSegment(events[0],events[1].point,queue),3):events[0]!==events[3].otherEvent?(divideSegment(events[0],events[1].point,queue),divideSegment(events[1],events[2].point,queue),3):(divideSegment(events[0],events[1].point,queue),divideSegment(events[3].otherEvent,events[2].point,queue),3)},compareSegments=(le1,le2)=>{if(le1===le2)return 0;if(0!==signedArea(le1.point,le1.otherEvent.point,le2.point)||0!==signedArea(le1.point,le1.otherEvent.point,le2.otherEvent.point))return equals$6(le1.point,le2.point)?le1.isBelow(le2.otherEvent.point)?-1:1:le1.point[0]===le2.point[0]?le1.point[1]le2.contourId?1:-1}return 1===compareEvents(le1,le2)?1:-1};class Contour{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return null==this.holeOf}}const nextPos=(pos,resultEvents,processed,origPos)=>{let newPos=pos+1;const p=resultEvents[pos].point;let p1;const length=resultEvents.length;for(newPosorigPos;)newPos--;return newPos},initializeContourFromContext=(event,contours,contourId)=>{const contour=new Contour;if(null!=event.prevInResult){const prevInResult=event.prevInResult,lowerContourId=prevInResult.outputContourId,lowerResultTransition=prevInResult.resultTransition;if(lowerContourId<0)contour.holeOf=null,contour.depth=0;else if(lowerResultTransition>0){const lowerContour=contours[lowerContourId];if(null!=lowerContour.holeOf){const parentContourId=lowerContour.holeOf;contours[parentContourId].holeIds.push(contourId),contour.holeOf=parentContourId,contour.depth=contours[lowerContourId].depth}else contours[lowerContourId].holeIds.push(contourId),contour.holeOf=lowerContourId,contour.depth=contours[lowerContourId].depth+1}else contour.holeOf=null,contour.depth=contours[lowerContourId].depth}else contour.holeOf=null,contour.depth=0;return contour},connectEdges=sortedEvents=>{const resultEvents=(sortedEvents=>{let event,i,len,tmp;const resultEvents=[];for(i=0,len=sortedEvents.length;i{processed[pos]=!0,pos=resultEvents.length)&&resultEvents[pos];);contours.push(contour)}return contours};class Queue{constructor(data,compare){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this._up(this.length++)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return--this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos=0)break;data[pos]=data[bestChild],pos=bestChild}data[pos]=item}}const max=Math.max,min=Math.min;let contourId=0;const processPolygon=(contourOrHole,isSubject,depth,queue,bbox,isExteriorRing)=>{const len=contourOrHole.length-1;let s1,s2,e1,e2;for(let i=0;i0?e2.left=!0:e1.left=!0;const x=s1[0],y=s1[1];bbox[0]=min(bbox[0],x),bbox[1]=min(bbox[1],y),bbox[2]=max(bbox[2],x),bbox[3]=max(bbox[3],y),queue.push(e1),queue.push(e2)}},EMPTY=[],toMartinez=geometry=>{const outlines=[];return toOutlines(geometry).forEach((outline=>{equals$6(outline[0],outline[outline.length-1])?outlines.push(outline):outlines.push([...outline,outline[0]])})),[outlines]},fromOutlines=outlines=>(outlines.forEach((outline=>{equals$6(outline[0],outline[outline.length-1])&&outline.pop()})),outlines=outlines.filter((o=>o.length>=3)),create$a(outlines)),boolean=(subjectGeom,clippingGeom,operation)=>{const subject=toMartinez(subjectGeom),clipping=toMartinez(clippingGeom);let trivial=((subject,clipping,operation)=>{let result=null;if(subject.length*clipping.length==0){if(0===operation)return EMPTY;2===operation?result=subject:1!==operation&&3!==operation||(result=0===subject.length?clipping:subject)}return result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,operation);if(trivial)return trivial;const sbbox=[1/0,1/0,-1/0,-1/0],cbbox=[1/0,1/0,-1/0,-1/0],eventQueue=((subject,clipping,sbbox,cbbox,operation)=>{const eventQueue=new Queue([],compareEvents);let polygonSet,isExteriorRing,i,ii,j,jj;for(i=0,ii=subject.length;i{let result=null;return(sbbox[0]>cbbox[2]||cbbox[0]>sbbox[2]||sbbox[1]>cbbox[3]||cbbox[1]>sbbox[3])&&(0===operation?result=EMPTY:2===operation?result=subject:1!==operation&&3!==operation||(result=subject.concat(clipping))),result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,sbbox,cbbox,operation),trivial)return trivial;const sortedEvents=((eventQueue,subject,clipping,sbbox,cbbox,operation)=>{const sweepLine=new Tree$1(compareSegments),sortedEvents=[],rightBound=Math.min(sbbox[2],cbbox[2]);let prev,next,begin;for(;0!==eventQueue.length;){let event=eventQueue.pop();if(sortedEvents.push(event),0===operation&&event.point[0]>rightBound||2===operation&&event.point[0]>sbbox[2])break;if(event.left){next=prev=sweepLine.insert(event),begin=sweepLine.minNode(),prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next);const prevEvent=prev?prev.key:null;let prevprevEvent;if(computeFields(event,prevEvent,operation),next&&2===possibleIntersection(event,next.key,eventQueue)&&(computeFields(event,prevEvent,operation),computeFields(next.key,event,operation)),prev&&2===possibleIntersection(prev.key,event,eventQueue)){let prevprev=prev;prevprev=prevprev!==begin?sweepLine.prev(prevprev):null,prevprevEvent=prevprev?prevprev.key:null,computeFields(prevEvent,prevprevEvent,operation),computeFields(event,prevEvent,operation)}}else event=event.otherEvent,next=prev=sweepLine.find(event),prev&&next&&(prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next),sweepLine.remove(event),next&&prev&&possibleIntersection(prev.key,next.key,eventQueue))}return sortedEvents})(eventQueue,0,0,sbbox,cbbox,operation),contours=connectEdges(sortedEvents),polygons=[];for(let i=0;i=0;k--)hole.push(holePoints[k]);rings.push(hole)}polygons.push(rings)}}return polygons?fromOutlines(polygons.flat()):create$a()},interpolateBetween2DPointsForY=(point1,point2,y)=>{let t,f1=y-point1[1],f2=point2[1]-point1[1];f2<0&&(f1=-f1,f2=-f2),t=f1<=0?0:f1>=f2?1:f2<1e-10?.5:f1/f2;return point1[0]+t*(point2[0]-point1[0])};class OrthonormalFormula{constructor(plane){this.plane=plane;const rightVector=orthogonal([0,0,0],plane);this.v=normalize$1(rightVector,cross$1(rightVector,plane,rightVector)),this.u=cross$1([0,0,0],this.v,plane),this.planeOrigin=scale$3([0,0,0],plane,plane[3]),this.basisMap=new Map}getProjectionMatrix(){return fromValues$4(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)}getInverseProjectionMatrix(){return fromValues$4(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,this.planeOrigin[0],this.planeOrigin[1],this.planeOrigin[2],1)}to2D(vertex){const point=fromValues$2(dot$2(vertex,this.u),dot$2(vertex,this.v));return this.basisMap.set(point,vertex),point}to3D(point){const original=this.basisMap.get(point);if(original)return original;const v1=scale$3([0,0,0],this.u,point[0]),v2=scale$3([0,0,0],this.v,point[1]),v3=add$1(v1,v1,this.planeOrigin);return add$1(v2,v2,v3)}}const insertSorted=(array,element,compareFunc)=>{let leftBound=0,rightBound=array.length;for(;rightBound>leftBound;){const testIndex=Math.floor((leftBound+rightBound)/2);compareFunc(element,array[testIndex])>0?leftBound=testIndex+1:rightBound=testIndex}array.splice(leftBound,0,element)},fnNumberSort=(a,b)=>a-b,retessellate=geometry=>{if(geometry.isRetesselated)return geometry;const polygons=toPolygons$1(geometry).map(((polygon,index)=>({vertices:polygon.vertices,plane:plane(polygon),index:index}))),classified=classifyPolygons(polygons),destPolygons=[];classified.forEach((group=>{if(Array.isArray(group)){const reTessellateCoplanarPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const destPolygons=[],numPolygons=sourcePolygons.length,plane$1=plane(sourcePolygons[0]),orthonormalFormula=new OrthonormalFormula(plane$1),polygonVertices2d=[],polygonTopVertexIndexes=[],topy2polygonIndexes=new Map,yCoordinateToPolygonIndexes=new Map,yCoordinateBins=new Map;for(let polygonIndex=0;polygonIndex0){let miny,maxy;for(let i=0;imaxy)&&(maxy=y);let polygonIndexes=yCoordinateToPolygonIndexes.get(y);polygonIndexes||(polygonIndexes={},yCoordinateToPolygonIndexes.set(y,polygonIndexes)),polygonIndexes[polygonIndex]=!0}if(miny>=maxy)vertices2d=[],numVertices=0,minIndex=-1;else{let polygonIndexes=topy2polygonIndexes.get(miny);polygonIndexes||(polygonIndexes=[],topy2polygonIndexes.set(miny,polygonIndexes)),polygonIndexes.push(polygonIndex)}}vertices2d.reverse(),minIndex=numVertices-minIndex-1,polygonVertices2d.push(vertices2d),polygonTopVertexIndexes.push(minIndex)}const yCoordinates=[];yCoordinateToPolygonIndexes.forEach(((polylist,y)=>yCoordinates.push(y))),yCoordinates.sort(fnNumberSort);let activePolygons=[],prevOutPolygonRow=[];for(let yIndex=0;yIndex=numVertices&&(nextLeftVertexIndex=0),vertices2d[nextLeftVertexIndex][1]!==yCoordinate)break;newLeftVertexIndex=nextLeftVertexIndex}let nextRightVertexIndex=newRightVertexIndex-1;if(nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),vertices2d[nextRightVertexIndex][1]===yCoordinate&&(newRightVertexIndex=nextRightVertexIndex),newLeftVertexIndex!==activePolygon.leftVertexIndex&&newLeftVertexIndex===newRightVertexIndex)activePolygons.splice(activePolygonIndex,1),--activePolygonIndex;else{activePolygon.leftVertexIndex=newLeftVertexIndex,activePolygon.rightVertexIndex=newRightVertexIndex,activePolygon.topLeft=vertices2d[newLeftVertexIndex],activePolygon.topRight=vertices2d[newRightVertexIndex];let nextLeftVertexIndex=newLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0),activePolygon.bottomLeft=vertices2d[nextLeftVertexIndex];let nextRightVertexIndex=newRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),activePolygon.bottomRight=vertices2d[nextRightVertexIndex]}}}let nextYcoordinate;if(yIndex>=yCoordinates.length-1)activePolygons=[],nextYcoordinate=null;else{nextYcoordinate=Number(yCoordinates[yIndex+1]);const middleYcoordinate=.5*(yCoordinate+nextYcoordinate),startingPolygonIndexes=topy2polygonIndexes.get(yCoordinate);for(const polygonIndexKey in startingPolygonIndexes){const polygonIndex=startingPolygonIndexes[polygonIndexKey],vertices2d=polygonVertices2d[polygonIndex],numVertices=vertices2d.length,topVertexIndex=polygonTopVertexIndexes[polygonIndex];let topLeftVertexIndex=topVertexIndex;for(;;){let i=topLeftVertexIndex+1;if(i>=numVertices&&(i=0),vertices2d[i][1]!==yCoordinate)break;if(i===topVertexIndex)break;topLeftVertexIndex=i}let topRightVertexIndex=topVertexIndex;for(;;){let i=topRightVertexIndex-1;if(i<0&&(i=numVertices-1),vertices2d[i][1]!==yCoordinate)break;if(i===topLeftVertexIndex)break;topRightVertexIndex=i}let nextLeftVertexIndex=topLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0);let nextRightVertexIndex=topRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1);const newActivePolygon={polygonIndex:polygonIndex,leftVertexIndex:topLeftVertexIndex,rightVertexIndex:topRightVertexIndex,topLeft:vertices2d[topLeftVertexIndex],topRight:vertices2d[topRightVertexIndex],bottomLeft:vertices2d[nextLeftVertexIndex],bottomRight:vertices2d[nextRightVertexIndex]};insertSorted(activePolygons,newActivePolygon,((el1,el2)=>{const x1=interpolateBetween2DPointsForY(el1.topLeft,el1.bottomLeft,middleYcoordinate),x2=interpolateBetween2DPointsForY(el2.topLeft,el2.bottomLeft,middleYcoordinate);return x1>x2?1:x10){const prevOutPolygon=newOutPolygonRow[newOutPolygonRow.length-1],d1=distance(outPolygon.topLeft,prevOutPolygon.topRight),d2=distance(outPolygon.bottomLeft,prevOutPolygon.bottomRight);d10){const prevContinuedIndexes=new Set,matchedIndexes=new Set;for(let i=0;i=0)&&(rightLineContinues||d2>=0)&&(thisPolygon.outPolygon=prevPolygon.outPolygon,thisPolygon.leftLineContinues=leftLineContinues,thisPolygon.rightLineContinues=rightLineContinues,prevContinuedIndexes.add(ii));break}}}for(let ii=0;iiEPS&&prevPolygon.outPolygon.leftPoints.push(prevPolygon.bottomLeft),prevPolygon.outPolygon.leftPoints.reverse();const vertices3d=prevPolygon.outPolygon.rightPoints.concat(prevPolygon.outPolygon.leftPoints).map((point2d=>orthonormalFormula.to3D(point2d))),polygon=fromVerticesAndPlane(vertices3d,plane$1);polygon.vertices.length&&destPolygons.push(polygon)}}for(let i=0;iEPS&&thisPolygon.outPolygon.rightPoints.push(thisPolygon.topRight))}prevOutPolygonRow=newOutPolygonRow}return destPolygons})(group);destPolygons.push(...reTessellateCoplanarPolygons)}else destPolygons.push(group)}));const result=create$8(destPolygons);return result.isRetesselated=!0,result},classifyPolygons=polygons=>{let clusters=[polygons];const nonCoplanar=[];for(let component=3;component>=0;component--){const maybeCoplanar=[],tolerance=3===component?15e-9:NEPS;clusters.forEach((cluster=>{cluster.sort(byPlaneComponent(component,tolerance));let startIndex=0;for(let i=1;itolerance&&(i-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex,i)),startIndex=i);cluster.length-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex))})),clusters=maybeCoplanar}const result=[];return clusters.forEach((cluster=>{cluster[0]&&(result[cluster[0].index]=cluster)})),nonCoplanar.forEach((polygon=>{result[polygon.index]=polygon})),result},byPlaneComponent=(component,tolerance)=>(a,b)=>a.plane[component]-b.plane[component]>tolerance?1:b.plane[component]-a.plane[component]>tolerance?-1:0;class Node{constructor(parent){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=parent}invert(){const queue=[this];let node;for(let i=0;i{treeNode.isRemoved()||treeNode.splitByPlane(plane,coplanarFrontNodes,backNodes,frontNodes,backNodes)})),node.front&&frontNodes.length>0&&stack.push({node:node.front,polygonTreeNodes:frontNodes});const numBackNodes=backNodes.length;if(node.back&&numBackNodes>0)stack.push({node:node.back,polygonTreeNodes:backNodes});else for(let i=0;i0&&tree.rootnode.clipPolygons(node.polygontreenodes,alsoRemoveCoplanarFront),node.front&&stack.push(node.front),node.back&&stack.push(node.back),node=stack.pop()}while(void 0!==node)}addPolygonTreeNodes(newPolygonTreeNodes){let current={node:this,polygonTreeNodes:newPolygonTreeNodes};const stack=[];do{const node=current.node,polygonTreeNodes=current.polygonTreeNodes,len=polygonTreeNodes.length;if(0===len){current=stack.pop();continue}if(!node.plane){let index=0;index=Math.floor(len/2);const bestPoly=polygonTreeNodes[index].getPolygon();node.plane=plane(bestPoly)}const frontNodes=[],backNodes=[];for(let i=0;i0){node.front||(node.front=new Node(node));len===frontNodes.length&&0===backNodes.length?node.front.polygontreenodes=frontNodes:stack.push({node:node.front,polygonTreeNodes:frontNodes})}if(backNodes.length>0){node.back||(node.back=new Node(node));len===backNodes.length&&0===frontNodes.length?node.back.polygontreenodes=backNodes:stack.push({node:node.back,polygonTreeNodes:backNodes})}current=stack.pop()}while(void 0!==current)}}const splitLineSegmentByPlane=(plane,p1,p2)=>{const direction=subtract$3([0,0,0],p2,p1);let lambda=(plane[3]-dot$2(plane,p1))/dot$2(plane,direction);return Number.isNaN(lambda)&&(lambda=0),lambda>1&&(lambda=1),lambda<0&&(lambda=0),scale$3(direction,direction,lambda),add$1(direction,p1,direction),direction};class PolygonTreeNode{constructor(parent,polygon){this.parent=parent,this.children=[],this.polygon=polygon,this.removed=!1}addPolygons(polygons){if(!this.isRootNode())throw new Error("Assertion failed");const _this=this;polygons.forEach((polygon=>{_this.addChild(polygon)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const parentschildren=this.parent.children,i=parentschildren.indexOf(this);if(i<0)throw new Error("Assertion failed");parentschildren.splice(i,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(result){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){if(this.children.length){const queue=[this.children];let i,j,l,node,nodes;for(i=0;i0?queue.push(node.children):node._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}else this._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}_splitByPlane(splane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){const polygon=this.polygon;if(polygon){const bound=measureBoundingSphere$1(polygon),sphereRadius=bound[3]+EPS,d=dot$2(splane,bound)-splane[3];if(d>sphereRadius)frontNodes.push(this);else if(d<-sphereRadius)backNodes.push(this);else{const splitResult=((splane,polygon)=>{const result={type:null,front:null,back:null},vertices=polygon.vertices,numVertices=vertices.length,pplane=plane(polygon);if(equals$5(pplane,splane))result.type=0;else{let hasFront=!1,hasBack=!1;const vertexIsBack=[],MINEPS=-EPS;for(let i=0;iEPS&&(hasFront=!0),t=numVertices&&(nextVertexIndex=0);const nextIsBack=vertexIsBack[nextVertexIndex];if(isback===nextIsBack)isback?backVertices.push(vertex):frontVertices.push(vertex);else{const nextPoint=vertices[nextVertexIndex],intersectionPoint=splitLineSegmentByPlane(splane,vertex,nextPoint);isback?(backVertices.push(vertex),backVertices.push(intersectionPoint),frontVertices.push(intersectionPoint)):(frontVertices.push(vertex),frontVertices.push(intersectionPoint),backVertices.push(intersectionPoint))}isback=nextIsBack}const EPS_SQUARED=EPS*EPS;if(backVertices.length>=3){let prevVertex=backVertices[backVertices.length-1];for(let vertexIndex=0;vertexIndex=3){let prevVertex=frontVertices[frontVertices.length-1];for(let vertexIndex=0;vertexIndex=3&&(result.front=fromVerticesAndPlane(frontVertices,pplane)),backVertices.length>=3&&(result.back=fromVerticesAndPlane(backVertices,pplane))}else result.type=3;else result.type=2;else{const t=dot$2(splane,pplane);result.type=t>=0?0:1}}return result})(splane,polygon);switch(splitResult.type){case 0:coplanarFrontNodes.push(this);break;case 1:coplanarBackNodes.push(this);break;case 2:frontNodes.push(this);break;case 3:backNodes.push(this);break;case 4:if(splitResult.front){const frontNode=this.addChild(splitResult.front);frontNodes.push(frontNode)}if(splitResult.back){const backNode=this.addChild(splitResult.back);backNodes.push(backNode)}}}}}addChild(polygon){const newChild=new PolygonTreeNode(this,polygon);return this.children.push(newChild),newChild}invertSub(){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let children=[this];const queue=[children];for(let i=0;i0&&queue.push(node.children),node.children=[]}}}toString(){let result="",children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}return result}}class Tree{constructor(polygons){this.polygonTree=new PolygonTreeNode,this.rootnode=new Node(null),polygons&&this.addPolygons(polygons)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(tree,alsoRemoveCoplanarFront=!1){this.rootnode.clipTo(tree,alsoRemoveCoplanarFront)}allPolygons(){const result=[];return this.polygonTree.getPolygons(result),result}addPolygons(polygons){const polygonTreeNodes=new Array(polygons.length);for(let i=0;i{if(0===geometry1.polygons.length||0===geometry2.polygons.length)return!1;const bounds1=measureBoundingBox(geometry1),min1=bounds1[0],max1=bounds1[1],bounds2=measureBoundingBox(geometry2),min2=bounds2[0],max2=bounds2[1];return!(min2[0]-max1[0]>EPS)&&(!(min1[0]-max2[0]>EPS)&&(!(min2[1]-max1[1]>EPS)&&(!(min1[1]-max2[1]>EPS)&&(!(min2[2]-max1[2]>EPS)&&!(min1[2]-max2[2]>EPS)))))},intersectGeom3=geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return create$8();const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),b.clipTo(a),b.invert(),a.clipTo(b),b.clipTo(a),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=retessellate(newGeometry),newGeometry},intersect=(...geometries)=>{if(0===(geometries=coalesce(geometries)).length)return;if(!areAllShapesTheSameType(geometries))throw new Error("intersect arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return(geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,0)})),newGeometry})(geometries);if(isA$3(geometry))return intersectGeom3(geometries);throw new Error("intersect unsupported geometry type")},scission=(...objects)=>{const results=objects.map((object=>isA$3(object)?(geometry=>{const eps=measureEpsilon(geometry),polygons=toPolygons$1(geometry),pl=polygons.length,indexesPerVertex=new Map,temp=[0,0,0];polygons.forEach(((polygon,index)=>{polygon.vertices.forEach((vertex=>{((map,vertex,index)=>{const key=`${vertex}`,mapping=map.get(key);void 0===mapping?map.set(key,[index]):mapping.push(index)})(indexesPerVertex,snap$2(temp,vertex,eps),index)}))}));const indexesPerPolygon=polygons.map((polygon=>{let indexes=[];return polygon.vertices.forEach((vertex=>{indexes=indexes.concat(((map,vertex)=>{const key=`${vertex}`;return map.get(key)})(indexesPerVertex,snap$2(temp,vertex,eps)))})),{e:1,d:(array=indexes,array.sort(((a,b)=>a-b)).filter(((item,pos,ary)=>!pos||item!==ary[pos-1])))};var array}));indexesPerVertex.clear();let merges=0;const ippl=indexesPerPolygon.length;for(let i=0;i0){const indexes=new Array(pl);indexes[i]=!0;do{merges=0,indexes.forEach(((e,j)=>{const mapj=indexesPerPolygon[j];if(mapj.e>0){mapj.e=-1;for(let d=0;d0);mapi.indexes=indexes}}const newgeometries=[];for(let i=0;inewpolygons.push(polygons[p]))),newgeometries.push(create$8(newpolygons))}return newgeometries})(object):Array.isArray(object)?scission(...object):object));return 1===results.length?results[0]:results},subtractGeom3=geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return clone$7(geometry1);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),a.clipTo(b),b.clipTo(a,!0),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=retessellate(newGeometry),newGeometry},subtract=(...geometries)=>{if(0===(geometries=coalesce(geometries)).length)return;if(!areAllShapesTheSameType(geometries))throw new Error("subtract arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return(geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,2)})),newGeometry})(geometries);if(isA$3(geometry))return subtractGeom3(geometries);throw new Error("subtract unsupported geometry type")},unionGeom2=geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,1)})),newGeometry},unionGeom3Sub=(geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return unionForNonIntersecting(geometry1,geometry2);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.clipTo(b,!1),b.clipTo(a),b.invert(),b.clipTo(a),b.invert();const newPolygons=a.allPolygons().concat(b.allPolygons());return create$8(newPolygons)},unionForNonIntersecting=(geometry1,geometry2)=>{let newpolygons=toPolygons$1(geometry1);return newpolygons=newpolygons.concat(toPolygons$1(geometry2)),create$8(newpolygons)},union=(...geometries)=>{if(0===(geometries=coalesce(geometries)).length)return;if(!areAllShapesTheSameType(geometries))throw new Error("union arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return unionGeom2(geometries);if(isA$3(geometry))return(geometries=>{let i;for(i=1;i{let{offset:offset,twistAngle:twistAngle,twistSteps:twistSteps,repair:repair}=Object.assign({},{offset:[0,0,1],twistAngle:0,twistSteps:12,repair:!0},options);if(twistSteps<1)throw new Error("twistSteps must be 1 or more");0===twistAngle&&(twistSteps=1);const offsetV=clone$9(offset);let baseSlice=fromGeom2(geometry);offsetV[2]<0&&(baseSlice=reverse$2(baseSlice));const matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];options={numberOfSlices:twistSteps+1,capStart:!0,capEnd:!0,repair:repair,callback:(progress,index,base)=>{const Zrotation=index/twistSteps*twistAngle,Zoffset=scale$3([0,0,0],offsetV,index/twistSteps);return multiply$1(matrix,fromZRotation(matrix,Zrotation),fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],Zoffset)),transform$3(matrix,base)}};const output=extrudeFromSlices(options,baseSlice);return geometry.color&&(output.color=geometry.color),output},extrudeLinear=(options,...objects)=>{const{height:height,twistAngle:twistAngle,twistSteps:twistSteps,repair:repair}=Object.assign({},{height:1,twistAngle:0,twistSteps:1,repair:!0},options);options={offset:[0,0,height],twistAngle:twistAngle,twistSteps:twistSteps,repair:repair};const results=objects.map((object=>isA$2(object)?((options,geometry)=>{if(!geometry.isClosed)throw new Error("extruded path must be closed");const points=toPoints$1(geometry),geometry2=create$a([points]);return geometry.color&&(geometry2.color=geometry.color),extrudeLinearGeom2(options,geometry2)})(options,object):isA$5(object)?extrudeLinearGeom2(options,object):Array.isArray(object)?extrudeLinear(options,...object):object));return 1===results.length?results[0]:results},extrudeHelical=(options,geometry)=>{const defaults={angle:TAU,startAngle:0,pitch:10,endOffset:0,segmentsPerRotation:32},{angle:angle,endOffset:endOffset,segmentsPerRotation:segmentsPerRotation,startAngle:startAngle}=Object.assign({},defaults,options);let pitch;pitch=!options.pitch&&options.height?options.height/(angle/TAU):options.pitch?options.pitch:defaults.pitch;if(segmentsPerRotation<3)throw new Error("The number of segments per rotation needs to be at least 3.");let baseSlice=fromGeom2(geometry);measureBoundingBox(geometry)[1][0]<=0&&(baseSlice=reverse$2(baseSlice));const calculatedSegments=Math.round(segmentsPerRotation/TAU*Math.abs(angle)),segments=calculatedSegments>=2?calculatedSegments:2,step1=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];let matrix;return extrudeFromSlices({numberOfSlices:segments+1,callback:(progress,index,base)=>{const zRotation=startAngle+angle/segments*index;return multiply$1(step1,fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[endOffset/segments*index,0,(zRotation-startAngle)/TAU*pitch*Math.sign(angle)]),fromXRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],-TAU/4*Math.sign(angle))),matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],multiply$1(matrix,fromZRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],zRotation),step1),transform$3(matrix,baseSlice)}},baseSlice)},aboutEqualNormals=(a,b)=>Math.abs(a[0]-b[0])<=NEPS&&Math.abs(a[1]-b[1])<=NEPS&&Math.abs(a[2]-b[2])<=NEPS,project=(options,...objects)=>{const{axis:axis,origin:origin}=Object.assign({},{axis:[0,0,1],origin:[0,0,0]},options);options={axis:axis,origin:origin};const results=objects.map((object=>isA$3(object)?((options,geometry)=>{const projPlane=fromNormalAndPoint([0,0,0,0],options.axis,options.origin);if(Number.isNaN(projPlane[0])||Number.isNaN(projPlane[1])||Number.isNaN(projPlane[2])||Number.isNaN(projPlane[3]))throw new Error("project: invalid axis or origin");const epsilon=measureEpsilon(geometry),epsilonArea=epsilon*epsilon*Math.sqrt(3)/4;if(0===epsilon)return create$a();const polygons=toPolygons$1(geometry);let projPolys=[];for(let i=0;iprojectionOfPoint(projPlane,v))),newPoly=create$7(newVertices),newPlane=plane(newPoly);aboutEqualNormals(projPlane,newPlane)&&(measureArea$2(newPoly)transform$7(rotation,p)))}projPolys=projPolys.sort(((a,b)=>measureArea$2(b)-measureArea$2(a)));const projGeoms=projPolys.map((p=>{const cloned=p.vertices.map(clone$8);return create$a([cloned])})),output=unionGeom2(projGeoms);return geometry.color&&(output.color=geometry.color),output})(options,object):Array.isArray(object)?project(options,...object):object));return 1===results.length?results[0]:results},hullPoints2=uniquePoints=>{let min=fromValues$2(1/0,1/0);uniquePoints.forEach((point=>{(point[1]{const angle=fakeAtan2(point[1]-min[1],point[0]-min[0]),distSq=squaredDistance(point,min);points.push({point:point,angle:angle,distSq:distSq})})),points.sort(((pt1,pt2)=>pt1.angle!==pt2.angle?pt1.angle-pt2.angle:pt1.distSq-pt2.distSq));const stack=[];return points.forEach((point=>{let cnt=stack.length;for(;cnt>1&&ccw(stack[cnt-2],stack[cnt-1],point.point)<=Number.EPSILON;)stack.pop(),cnt=stack.length;stack.push(point.point)})),stack},ccw=(v1,v2,v3)=>(v2[0]-v1[0])*(v3[1]-v1[1])-(v2[1]-v1[1])*(v3[0]-v1[0]),fakeAtan2=(y,x)=>0===y&&0===x?-1/0:-x/y,toUniquePoints=geometries=>{const found=new Set,uniquePoints=[],addPoint=point=>{const key=point.toString();found.has(key)||(uniquePoints.push(point),found.add(key))};return geometries.forEach((geometry=>{isA$5(geometry)?toPoints$3(geometry).forEach(addPoint):isA$3(geometry)?toPoints$2(geometry).forEach((points=>points.forEach(addPoint))):isA$2(geometry)&&toPoints$1(geometry).forEach(addPoint)})),uniquePoints},hullPoints3=uniquePoints=>{const polygons=runner(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return polygons},hull=(...geometries)=>{if(0===(geometries=coalesce(geometries)).length)return;if(!areAllShapesTheSameType(geometries))throw new Error("only hulls of the same type are supported");const geometry=geometries[0];return isA$2(geometry)?(geometries=>{const unique=toUniquePoints(geometries),hullPoints=hullPoints2(unique);return fromPoints$2({closed:!0},hullPoints)})(geometries):isA$5(geometry)?(geometries=>{const unique=toUniquePoints(geometries),hullPoints=hullPoints2(unique);return hullPoints.length<3?create$a():create$a([hullPoints])})(geometries):isA$3(geometry)?(geometries=>{const unique=toUniquePoints(geometries);return 0===unique.length?create$8():create$8(hullPoints3(unique))})(geometries):geometry},hullChain=(...geometries)=>{if(0===(geometries=coalesce(geometries)).length)return;if(1===geometries.length)return geometries[0];if(!areAllShapesTheSameType(geometries))throw new Error("only hulls of the same type are supported");const hulls=[];for(let i=1;i{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons},createEdges=polygon=>{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2;return[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergeCoplanarPolygons=sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&aboutEqualNormals(plane1,plane2);var plane1,plane2}));if(mapping){mapping[1].push(polygon)}else polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const sourcePolygons=mapping[1],retesselatedPolygons=mergeCoplanarPolygons(sourcePolygons);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=measureEpsilon(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=snapPolygons(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},snap=(...geometries)=>{const results=geometries.map((geometry=>isA$2(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry),newPoints=toPoints$1(geometry).map((point=>snap$1([0,0],point,epsilon)));return create$5(newPoints)})(geometry):isA$5(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry);let newOutlines=toOutlines(geometry).map((outline=>{let prev=snap$1([0,0],outline[outline.length-1],epsilon);const newOutline=[];return outline.forEach((point=>{const snapped=snap$1([0,0],point,epsilon);equals$6(prev,snapped)||newOutline.push(snapped),prev=snapped})),newOutline}));return newOutlines=newOutlines.filter((outline=>measureArea$1(create$3(outline)))),create$a(newOutlines)})(geometry):isA$3(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry),polygons=toPolygons$1(geometry),newPolygons=snapPolygons(epsilon,polygons);return create$8(newPolygons)})(geometry):Array.isArray(geometry)?snap(...geometry):geometry));return 1===results.length?results[0]:results},offsetFromPoints=(options,points)=>{let{delta:delta,corners:corners,closed:closed,segments:segments}=Object.assign({},{delta:1,corners:"edge",closed:!1,segments:16},options);if(Math.abs(delta)0&&delta>=0||rotation<0&&delta<0;delta=Math.abs(delta);let previousSegment=null,newPoints=[];const newCorners=[],of=[0,0],n=points.length;for(let i=0;ipointIndex.set(point,index)));const line0=[0,1,0],line1=[0,1,0];newCorners.forEach((corner=>{fromPoints$1(line0,corner.s0[0],corner.s0[1]),fromPoints$1(line1,corner.s1[0],corner.s1[1]);const ip=intersectPointOfLines(line0,line1);if(Number.isFinite(ip[0])&&Number.isFinite(ip[1])){const p0=corner.s0[1],i=pointIndex.get(p0);newPoints[i]=ip,newPoints[(i+1)%newPoints.length]=void 0}else{const p0=corner.s1[0],i=pointIndex.get(p0);newPoints[i]=void 0}})),newPoints=newPoints.filter((p=>void 0!==p))}if("round"===corners){let cornerSegments=Math.floor(segments/4);const v0=[0,0];newCorners.forEach((corner=>{let rotation=angleRadians(subtract$1(v0,corner.s1[0],corner.c));if(rotation-=angleRadians(subtract$1(v0,corner.s0[1],corner.c)),orientation&&rotation<0&&(rotation+=Math.PI,rotation<0&&(rotation+=Math.PI)),!orientation&&rotation>0&&(rotation-=Math.PI,rotation>0&&(rotation-=Math.PI)),0!==rotation){cornerSegments=Math.floor(segments*(Math.abs(rotation)/TAU));const step=rotation/cornerSegments,start=angleRadians(subtract$1(v0,corner.s0[1],corner.c)),cornerPoints=[];for(let i=1;i0){const p0=corner.s0[1];let i=newPoints.findIndex((point=>equals$6(p0,point)));i=(i+1)%newPoints.length,newPoints.splice(i,0,...cornerPoints)}}else{const p0=corner.s1[0],i=newPoints.findIndex((point=>equals$6(p0,point)));newPoints.splice(i,1)}}))}return newPoints},mapPlaneToVertex=(map,vertex,plane)=>{const key=vertex.toString();if(map.has(key)){map.get(key)[1].push(plane)}else{const entry=[vertex,[plane]];map.set(key,entry)}},mapPlaneToEdge=(map,edge,plane)=>{const key0=edge[0].toString(),key1=edge[1].toString(),key=key0{map.findIndex((item=>item===angle))<0&&map.push(angle)},offsetShell=(options,geometry)=>{const{delta:delta,segments:segments}=Object.assign({},{delta:1,segments:12},options);let result=create$8();const vertices2planes=new Map,edges2planes=new Map,v1=[0,0,0],v2=[0,0,0];return toPolygons$1(geometry).forEach((polygon=>{const extrudeVector=scale$3([0,0,0],plane(polygon),2*delta),extrudedFace=((offsetVector,polygon1)=>{dot$2(plane(polygon1),offsetVector)>0&&(polygon1=invert$1(polygon1));const newPolygons=[polygon1],polygon2=transform$7(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offsetVector),polygon1),numVertices=polygon1.vertices.length;for(let i=0;i{const edge=item[0],planes=item[1],startVertex=edge[0],endVertex=edge[1],zBase=subtract$3([0,0,0],endVertex,startVertex);normalize$1(zBase,zBase);const xBase=planes[0],yBase=cross$1([0,0,0],xBase,zBase);let angles=[];for(let i=0;i=0&&distance$1(p1,prevP1)=0){startFaceVertices.push(p1),endFaceVertices.push(p2);const polygon=create$7([prevP2,p2,p1,prevP1]);polygons.push(polygon)}prevP1=p1,prevP2=p2}}endFaceVertices.reverse(),polygons.push(create$7(startFaceVertices)),polygons.push(create$7(endFaceVertices));const cylinder=create$8(polygons);result=unionGeom3Sub(result,cylinder)})),vertices2planes.forEach((item=>{const vertex=item[0],planes=item[1],xaxis=planes[0];let bestzaxis=null,bestzaxisOrthogonality=0;for(let i=1;i.05&&crossLength>bestzaxisOrthogonality&&(bestzaxisOrthogonality=crossLength,bestzaxis=normal)}bestzaxis||(bestzaxis=orthogonal(v1,xaxis));const yaxis=cross$1(v1,xaxis,bestzaxis);normalize$1(yaxis,yaxis);const zaxis=cross$1(v2,yaxis,xaxis),corner=sphere({center:[vertex[0],vertex[1],vertex[2]],radius:delta,segments:segments,axes:[xaxis,yaxis,zaxis]});result=unionGeom3Sub(result,corner)})),retessellate(result)},offsetPath2=(options,geometry)=>{const{delta:delta,corners:corners,segments:segments}=Object.assign({},{delta:1,corners:"edge",segments:16},options);if(delta<=0)throw new Error("the given delta must be positive for paths");if("edge"!==corners&&"chamfer"!==corners&&"round"!==corners)throw new Error('corners must be "edge", "chamfer", or "round"');const closed=geometry.isClosed,points=toPoints$1(geometry),paths={points:points,external:offsetFromPoints({delta:delta,corners:corners,segments:segments,closed:closed},points),internal:offsetFromPoints({delta:-delta,corners:corners,segments:segments,closed:closed},points)},output=geometry.isClosed?(paths=>{let{external:external,internal:internal}=paths;return external.length<2?create$a():(area$1(external)<0?external=external.reverse():internal=internal.reverse(),create$a([external,internal]))})(paths):((paths,segments,corners,delta)=>{const{points:points,external:external,internal:internal}=paths;if(0===points.length)return create$a();if(1===points.length)return circle({center:points[0],radius:delta});const capSegments=Math.floor(segments/2),e2iCap=[],i2eCap=[];if("round"===corners&&capSegments>0){const step=Math.PI/capSegments,eCorner=points[points.length-1],e2iStart=angleRadians(subtract$1([0,0],external[external.length-1],eCorner)),iCorner=points[0],i2eStart=angleRadians(subtract$1([0,0],internal[0],iCorner));for(let i=1;i{const results=objects.map((object=>isA$2(object)?offsetPath2(options,object):isA$5(object)?((options,geometry)=>{const{delta:delta,corners:corners,segments:segments,expandHoles:expandHoles}=Object.assign({},{delta:1,corners:"edge",segments:16,expandHoles:!1},options);if("edge"!==corners&&"chamfer"!==corners&&"round"!==corners)throw new Error('corners must be "edge", "chamfer", or "round"');if(!Number.isFinite(delta))throw new Error("delta must be a finite number");if("round"===corners&&!Number.isFinite(segments))throw new Error("segments must be a finite number");if("round"===corners&&!(segments>0))throw new Error("segments must be greater than zero");const outlines=toOutlines(geometry),newOutlines=outlines.map((outline=>{let outside=!0;if(expandHoles){const level=outlines.reduce(((acc,polygon)=>acc+arePointsInside(outline,create$3(polygon))),0);outside=level%2==0}return offsetFromPoints(options={delta:outside?delta:-delta,corners:corners,closed:!0,segments:segments},outline)})),output=create$a(newOutlines);return geometry.color&&(output.color=geometry.color),output})(options,object):isA$3(object)?((options,geometry)=>{const{delta:delta,corners:corners,segments:segments}=Object.assign({},{delta:1,corners:"round",segments:12},options);if("round"!==corners)throw new Error('corners must be "round" for 3D geometries');const expanded=offsetShell(options={delta:delta,corners:corners,segments:segments},geometry),output=union(geometry,expanded);return geometry.color&&(output.color=geometry.color),output})(options,object):Array.isArray(object)?offset(options,...object):object));return 1===results.length?results[0]:results},padArrayToLength=(anArray,padding,targetLength)=>{for(anArray=anArray.slice();anArray.length{const bounds=measureAggregateBoundingBox(geometries),translation=[0,0,0];for(let i=0;i<3;i++)"center"===modes[i]?translation[i]=relativeTo[i]-(bounds[0][i]+bounds[1][i])/2:"max"===modes[i]?translation[i]=relativeTo[i]-bounds[1][i]:"min"===modes[i]&&(translation[i]=relativeTo[i]-bounds[0][i]);return translate(translation,geometries)},align=(options,...geometries)=>{options=(options=>{if(!Array.isArray(options.modes)||options.modes.length>3)throw new Error("align(): modes must be an array of length <= 3");if(options.modes=padArrayToLength(options.modes,"none",3),3!==options.modes.filter((mode=>["center","max","min","none"].includes(mode))).length)throw new Error('align(): all modes must be one of "center", "max" or "min"');if(!Array.isArray(options.relativeTo)||options.relativeTo.length>3)throw new Error("align(): relativeTo must be an array of length <= 3");if(options.relativeTo=padArrayToLength(options.relativeTo,0,3),3!==options.relativeTo.filter((alignVal=>Number.isFinite(alignVal)||null==alignVal)).length)throw new Error("align(): all relativeTo values must be a number, or null.");if("boolean"!=typeof options.grouped)throw new Error("align(): grouped must be a boolean value.");return options})(options=Object.assign({},{modes:["center","center","min"],relativeTo:[0,0,0],grouped:!1},options));let{modes:modes,relativeTo:relativeTo,grouped:grouped}=options;if(relativeTo.filter((val=>null==val)).length){const bounds=measureAggregateBoundingBox(geometries);relativeTo=((relativeTo,modes,bounds)=>{for(let i=0;i<3;i++)null==relativeTo[i]&&("center"===modes[i]?relativeTo[i]=(bounds[0][i]+bounds[1][i])/2:"max"===modes[i]?relativeTo[i]=bounds[1][i]:"min"===modes[i]&&(relativeTo[i]=bounds[0][i]));return relativeTo})(relativeTo,modes,bounds)}return grouped?(geometries=coalesce(geometries),geometries=alignGeometries(geometries,modes,relativeTo)):geometries=geometries.map((geometry=>alignGeometries(geometry,modes,relativeTo))),1===geometries.length?geometries[0]:geometries},centerGeometry=(options,object)=>{const{axes:axes,relativeTo:relativeTo}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},options),bounds=measureAggregateBoundingBox(object),offset=[0,0,0];return axes[0]&&(offset[0]=relativeTo[0]-(bounds[0][0]+(bounds[1][0]-bounds[0][0])/2)),axes[1]&&(offset[1]=relativeTo[1]-(bounds[0][1]+(bounds[1][1]-bounds[0][1])/2)),axes[2]&&(offset[2]=relativeTo[2]-(bounds[0][2]+(bounds[1][2]-bounds[0][2])/2)),translate(offset,object)},center=(options,...objects)=>{const{axes:axes,relativeTo:relativeTo}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},options);if(3!==relativeTo.length)throw new Error("relativeTo must be an array of length 3");options={axes:axes,relativeTo:relativeTo};const results=objects.map((object=>isA$2(object)||isA$5(object)||isA$3(object)||Array.isArray(object)?centerGeometry(options,object):object));return 1===results.length?results[0]:results},centerX=(...objects)=>center({axes:[!0,!1,!1]},...objects),centerY=(...objects)=>center({axes:[!1,!0,!1]},...objects),centerZ=(...objects)=>center({axes:[!1,!1,!0]},...objects),scale=(factors,...objects)=>{if(!Array.isArray(factors))throw new Error("factors must be an array");for(factors=factors.slice();factors.length<3;)factors.push(1);if(factors[0]<=0||factors[1]<=0||factors[2]<=0)throw new Error("factors must be positive");const matrix=fromScaling([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],factors),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?scale(factors,...object):object));return 1===results.length?results[0]:results},scaleX=(factor,...objects)=>scale([factor,1,1],...objects),scaleY=(factor,...objects)=>scale([1,factor,1],...objects),scaleZ=(factor,...objects)=>scale([1,1,factor],...objects),transform=(matrix,...objects)=>{const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?transform(matrix,...object):object));return 1===results.length?results[0]:results};export{EPS,NEPS,TAU,align,arc,area$1 as area,index$4 as bezier,center,centerX,centerY,centerZ,circle,colorNameToRgb,colorize,cos,cssColors,cube,cuboid,cylinder,cylinderElliptic,degToRad,ellipse,ellipsoid,extrudeFromSlices,extrudeHelical,extrudeLinear,extrudeRotate,flatten,generalize,geodesicSphere,index$a as geom2,index$6 as geom3,hexToRgb,hslToRgb,hsvToRgb,hueToColorComponent,hull,hullChain,hullPoints2,hullPoints3,intersect,line,index$1 as line2,index as line3,index$c as mat4,measureAggregateArea,measureAggregateBoundingBox,measureAggregateEpsilon,measureAggregateVolume,measureArea,measureBoundingBox,measureBoundingSphere,measureCenter,measureCenterOfMass,measureDimensions,measureEpsilon,measureVolume,mirror,mirrorX,mirrorY,mirrorZ,offset,offsetFromPoints,index$5 as path2,index$9 as plane,index$3 as poly2,index$7 as poly3,polygon,polyhedron,project,radToDeg,radiusToSegments,rectangle,retessellate,rgbToHex,rgbToHsl,rgbToHsv,rotate,rotateX,rotateY,rotateZ,roundedCuboid,roundedCylinder,roundedRectangle,scale,scaleX,scaleY,scaleZ,scission,sin,index$2 as slice,snap,sphere,square,star,subtract,torus,transform,translate,translateX,translateY,translateZ,triangle,union,index$b as vec2,index$d as vec3,index$8 as vec4,vectorChar,vectorText}; diff --git a/packages/modeling/dist/jscad-modeling.min.js b/packages/modeling/dist/jscad-modeling.min.js index d87f134e5..67b8e3d85 100644 --- a/packages/modeling/dist/jscad-modeling.min.js +++ b/packages/modeling/dist/jscad-modeling.min.js @@ -1,7 +1,7 @@ /** * Constructive Solid Geometry (CSG) Library for JSCAD * @module @jscad/modeling - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ -var global,factory;global=this,factory=function(exports){const cssColors={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),clone$b=geometry=>Object.assign({},geometry),create$c=()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,NEPS=1e-13,TAU=2*Math.PI,rezero=n=>Math.abs(n)rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation=(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues$4=(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],create$b=()=>[0,0,0],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0]{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale$3=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:create$b,cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:rotateZ$2,scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const fromVectorRotation=(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation=(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation=(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply$1=(out,a,b)=>{const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out},translate$1=(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:create$c,equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:fromScaling,fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:fromValues$4,fromVectorRotation:fromVectorRotation,fromXRotation:fromXRotation,fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:fromZRotation,identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:mirrorByPlane,multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:translate$1});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),create$9=()=>[0,0],clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),snap$1=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};var index$b=Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:create$9,cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:snap$1,squaredDistance:squaredDistance,squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const toPointMap=sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap},fromSides=sides=>{const pointMap=toPointMap(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides=geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:fromSides,fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:toSides,toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromNormalAndPoint=(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},projectionOfPoint=(plane,point)=>{const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;var index$9=Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:fromNormalAndPoint,fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,measureBoundingSphere$1=polygon=>{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;ipolygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>NEPS)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;i(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),toPoints$2=geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validateManifold=object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)};var index$6=Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:toPoints$2,toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),validateManifold(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const hueToColorComponent=(p,q,t)=>(t<0&&(t+=1),t>1&&(t-=1),t<1/6?p+6*(q-p)*t:t<.5?q:t<2/3?p+(q-p)*(2/3-t)*6:p),getPointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=getPointType(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),equals$3=(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices=vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours)),reverse$2=slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges=slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges};class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles},earcutLinked=(ear,triangles,dim,minX,minY,invSize,pass)=>{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1,minIndex=(list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuepart.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=minIndex(parents[j],(p=>children[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}const toPolygons=slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),data=vertices.flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=triangulate(data,holesIndex);for(let i=0;i{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)};var index$2=Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:equals$3,fromGeom2:fromGeom2,fromVertices:fromVertices,isA:isA,reverse:reverse$2,toEdges:toEdges,toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:toPolygons,toString:slice=>{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:transform$3,validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i[0,1,0],direction$1=line=>{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]},intersectPointOfLines=(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)};var index$1=Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:create$1,direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:intersectPointOfLines,origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};var index=Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$3=new WeakMap,measureArea=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?0:isA$5(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=toSides(geometry).reduce(((area,side)=>area+(side[0][0]*side[1][1]-side[0][1]*side[1][0])),0),area*=.5,cache$3.set(geometry,area),area)})(geometry):isA$3(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=toPolygons$1(geometry).reduce(((area,polygon)=>area+measureArea$2(polygon)),0),cache$3.set(geometry,area),area)})(geometry):isA(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=0,geometry.contours.forEach((contour=>{area+=measureArea$2(create$7(contour))})),cache$3.set(geometry,area),area)})(geometry):0));return 1===results.length?results[0]:results},cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},measureAggregateBoundingBox=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("measureAggregateBoundingBox: no geometries supplied");const bounds=measureBoundingBox(geometries);if(1===geometries.length)return bounds;const result=[[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],[-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE]];return bounds.reduce(((result,item)=>result=[min$2(result[0],result[0],item[0]),max$2(result[1],result[1],item[1])]),result)},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$3(geometry)?(geometry=>{let volume=cache$1.get(geometry);return volume||(volume=toPolygons$1(geometry).reduce(((volume,polygon)=>volume+measureSignedVolume(polygon)),0),cache$1.set(geometry,volume),volume)})(geometry):0));return 1===results.length?results[0]:results},cache=new WeakMap,measureCached=(geometry,measureFn)=>{let boundingSphere=cache.get(geometry);return boundingSphere||(boundingSphere=measureFn(geometry),0===boundingSphere.length&&(boundingSphere[0]=[0,0,0],boundingSphere[1]=0),cache.set(geometry,boundingSphere),boundingSphere)},measureBoundingSphereOfPoints=points=>{const centroid=[0,0,0];let radius=0;if(points.length>0){let numPoints=0;const temp=[0,0,0];points.forEach((point=>{add$1(centroid,centroid,fromVec2(temp,point,0)),numPoints++})),scale$3(centroid,centroid,1/numPoints),points.forEach((point=>{radius=Math.max(radius,squaredDistance(centroid,point))})),radius=Math.sqrt(radius)}return[centroid,radius]},measureBoundingSphereOfPath2=points=>measureBoundingSphereOfPoints(toPoints$1(points)),measureBoundingSphereOfGeom2=geometry=>measureBoundingSphereOfPoints(toPoints$3(geometry)),measureBoundingSphereOfGeom3=geometry=>{const centroid=[0,0,0];let radius=0;const polygons=toPolygons$1(geometry);if(polygons.length>0){let numVertices=0;polygons.forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{add$1(centroid,centroid,vertex),numVertices++}))})),scale$3(centroid,centroid,1/numVertices),polygons.forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{radius=Math.max(radius,squaredDistance$1(centroid,vertex))}))})),radius=Math.sqrt(radius)}return[centroid,radius]},measureBoundingSphereOfSlice=geometry=>{const centroid=[0,0,0];let radius=0,numVertices=0;return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(centroid,centroid,vertex),numVertices++}))})),numVertices>0&&(scale$3(centroid,centroid,1/numVertices),geometry.contours.forEach((contour=>{contour.forEach((vertex=>{radius=Math.max(radius,squaredDistance$1(centroid,vertex))}))})),radius=Math.sqrt(radius)),[centroid,radius]},cacheOfCenterOfMass=new WeakMap,measureEpsilon=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results},isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGT=(value,constant)=>Number.isFinite(value)&&value>constant,isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})},cuboid=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0,0],size:[2,2,2]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of width, depth and height values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");return 0===size[0]||0===size[1]||0===size[2]?create$8():create$8([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((info=>{const vertices=info[0].map((i=>[center[0]+size[0]/2*(2*!!(1&i)-1),center[1]+size[1]/2*(2*!!(2&i)-1),center[2]+size[2]/2*(2*!!(4&i)-1)]));return create$7(vertices)})))},cylinderElliptic=options=>{const defaults={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:TAU,segments:32};let{center:center,height:height,startRadius:startRadius,startAngle:startAngle,endRadius:endRadius,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGT(height,0))throw new Error("height must be greater then zero");if(!isNumberArray(startRadius,2))throw new Error("startRadius must be an array of X and Y values");if(!startRadius.every((n=>n>=0)))throw new Error("startRadius values must be positive");if(!isNumberArray(endRadius,2))throw new Error("endRadius must be an array of X and Y values");if(!endRadius.every((n=>n>=0)))throw new Error("endRadius values must be positive");if(endRadius.every((n=>0===n))&&startRadius.every((n=>0===n)))throw new Error("at least one radius must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(startRadius[0],startRadius[1],endRadius[0],endRadius[1]),minAngle=Math.acos((minRadius*minRadius+minRadius*minRadius-EPS*EPS)/(2*minRadius*minRadius));if(rotation{const angle=slice*rotation+startAngle;return scale$3(v1,axisX,radius[0]*cos(angle)),scale$3(v2,axisY,radius[1]*sin(angle)),add$1(v1,v1,v2),scale$3(v3,ray,stack),add$1(v3,v3,start),add$1([0,0,0],v1,v3)},fromVertices=(...vertices)=>{const newVertices=vertices.map((vertex=>add$1([0,0,0],vertex,center)));return create$7(newVertices)},polygons=[];for(let i=0;i0&&startRadius[1]>0&&polygons.push(fromVertices(start,genVertex(0,t1,startRadius),genVertex(0,t0,startRadius))),(startRadius[0]>0||startRadius[1]>0)&&polygons.push(fromVertices(genVertex(0,t0,startRadius),genVertex(0,t1,startRadius),genVertex(1,t0,endRadius))),endRadius[0]>0&&endRadius[1]>0&&polygons.push(fromVertices(end,genVertex(1,t0,endRadius),genVertex(1,t1,endRadius))),(endRadius[0]>0||endRadius[1]>0)&&polygons.push(fromVertices(genVertex(1,t0,endRadius),genVertex(0,t1,startRadius),genVertex(1,t1,endRadius))))}return rotation{const{center:center,height:height,radius:radius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return 0===height||0===radius?create$8():cylinderElliptic({center:center,height:height,startRadius:[radius,radius],endRadius:[radius,radius],segments:segments})},ellipsoid=options=>{const{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(radius,3))throw new Error("radius must be an array of X, Y and Z values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===radius[0]||0===radius[1]||0===radius[2])return create$8();const xVector=scale$3([0,0,0],normalize$1([0,0,0],axes[0]),radius[0]),yVector=scale$3([0,0,0],normalize$1([0,0,0],axes[1]),radius[1]),zVector=scale$3([0,0,0],normalize$1([0,0,0],axes[2]),radius[2]),qSegments=Math.round(segments/4);let prevCylinderVertex;const polygons=[],p1=[0,0,0],p2=[0,0,0];for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(p1,xVector,cos(angle)),scale$3(p2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch;for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);if(slice2>0){let vertex,vertices=[];vertex=subtract$3([0,0,0],scale$3(p1,prevCylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),vertex=subtract$3([0,0,0],scale$3(p1,cylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),slice2{const defaults={points:[],faces:[],colors:void 0,orientation:"outward"},{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},defaults,options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)},rectangle=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])},createCorners=(center,size,radius,segments,slice,positive)=>{const pitch=TAU/4*slice/segments,cosPitch=cos(pitch),sinPitch=sin(pitch),layerSegments=segments-slice;let layerRadius=radius*cosPitch,layerOffset=size[2]-(radius-radius*sinPitch);positive||(layerOffset=radius-radius*sinPitch-size[2]),layerRadius=layerRadius>EPS?layerRadius:0;const corner0=add$1([0,0,0],center,[size[0]-radius,size[1]-radius,layerOffset]),corner1=add$1([0,0,0],center,[radius-size[0],size[1]-radius,layerOffset]),corner2=add$1([0,0,0],center,[radius-size[0],radius-size[1],layerOffset]),corner3=add$1([0,0,0],center,[size[0]-radius,radius-size[1],layerOffset]),corner0Vertices=[],corner1Vertices=[],corner2Vertices=[],corner3Vertices=[];for(let i=0;i<=layerSegments;i++){const point2d=fromAngleRadians([0,0],layerSegments>0?TAU/4*i/layerSegments:0);scale$1(point2d,point2d,layerRadius);const point3d=fromVec2([0,0,0],point2d);corner0Vertices.push(add$1([0,0,0],corner0,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner1Vertices.push(add$1([0,0,0],corner1,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner2Vertices.push(add$1([0,0,0],corner2,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner3Vertices.push(add$1([0,0,0],corner3,point3d))}return positive?[corner0Vertices,corner1Vertices,corner2Vertices,corner3Vertices]:(corner0Vertices.reverse(),corner1Vertices.reverse(),corner2Vertices.reverse(),corner3Vertices.reverse(),[corner3Vertices,corner2Vertices,corner1Vertices,corner0Vertices])},stitchCorners=(previousCorners,currentCorners)=>{const polygons=[];for(let i=0;i{const polygons=[];for(let i=0;i{bottomCorners=(bottomCorners=[bottomCorners[3],bottomCorners[2],bottomCorners[1],bottomCorners[0]]).map((corner=>corner.slice().reverse()));const bottomVertices=[];bottomCorners.forEach((corner=>{corner.forEach((vertex=>bottomVertices.push(vertex)))}));const topVertices=[];topCorners.forEach((corner=>{corner.forEach((vertex=>topVertices.push(vertex)))}));const polygons=[];for(let i=0;i{let{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius,radius],ellipsoid({center:center,radius:radius,segments:segments,axes:axes})},getPoints=(vertices,radius,startAngle,center)=>{const a=TAU/vertices,points=[];for(let i=0;i{const{origin:origin,normal:normal}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},options);if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const planeOfMirror=fromNormalAndPoint([0,0,0,0],normal,origin);if(Number.isNaN(planeOfMirror[0]))throw new Error("the given origin and normal do not define a proper plane");const matrix=mirrorByPlane([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],planeOfMirror),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},mirrorX=(...objects)=>mirror({normal:[1,0,0]},objects),gcd=(a,b)=>a===b?a:a{const multiple=newLength/edges.length;if(1===multiple)return edges;const divisor=fromValues$3(multiple,multiple,multiple),newEdges=[];return edges.forEach((edge=>{const increment=subtract$3([0,0,0],edge[1],edge[0]);divide$1(increment,increment,divisor);let prev=edge[0];for(let i=1;i<=multiple;++i){const next=add$1([0,0,0],prev,increment);newEdges.push([prev,next]),prev=next}})),newEdges},EPSAREA=EPS*EPS/2*Math.sin(Math.PI/3),extrudeWalls=(slice0,slice1)=>{let edges0=toEdges(slice0),edges1=toEdges(slice1);if(edges0.length!==edges1.length){const newLength=(a=edges0.length,b=edges1.length,a*b/gcd(a,b));newLength!==edges0.length&&(edges0=repartitionEdges(newLength,edges0)),newLength!==edges1.length&&(edges1=repartitionEdges(newLength,edges1))}var a,b;const walls=[];return edges0.forEach(((edge0,i)=>{const edge1=edges1[i],poly0=create$7([edge0[0],edge0[1],edge1[1]]),poly0area=measureArea$2(poly0);Number.isFinite(poly0area)&&poly0area>EPSAREA&&walls.push(poly0);const poly1=create$7([edge0[0],edge1[1],edge1[0]]),poly1area=measureArea$2(poly1);Number.isFinite(poly1area)&&poly1area>EPSAREA&&walls.push(poly1)})),walls},defaultCallback=(progress,index,base)=>{let baseSlice=null;return isA$5(base)&&(baseSlice=fromGeom2(base)),isA$4(base)&&(baseSlice=fromVertices(toVertices$1(base))),0===progress||1===progress?transform$3(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[0,0,progress]),baseSlice):null},extrudeFromSlices=(options,base)=>{const defaults={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,callback:defaultCallback},{numberOfSlices:numberOfSlices,capStart:capStart,capEnd:capEnd,close:close,callback:generate}=Object.assign({},defaults,options);if(numberOfSlices<2)throw new Error("numberOfSlices must be 2 or more");const sMax=numberOfSlices-1;let startSlice=null,endSlice=null,prevSlice=null,polygons=[];for(let s=0;s{const defaults={segments:12,startAngle:0,angle:TAU,overflow:"cap"};let{segments:segments,startAngle:startAngle,angle:angle,overflow:overflow}=Object.assign({},defaults,options);if(segments<3)throw new Error("segments must be greater then 3");startAngle=Math.abs(startAngle)>TAU?startAngle%TAU:startAngle,angle=Math.abs(angle)>TAU?angle%TAU:angle;let endAngle=startAngle+angle;if(endAngle=Math.abs(endAngle)>TAU?endAngle%TAU:endAngle,endAnglesegments*anglePerSegment&&segments++}let shapeSides=toSides(geometry);if(0===shapeSides.length)return geometry;let sliceGeometry=geometry;const pointsWithNegativeX=shapeSides.filter((s=>s[0][0]<0)),pointsWithPositiveX=shapeSides.filter((s=>s[0][0]>=0));pointsWithNegativeX.length>0&&pointsWithPositiveX.length>0&&"cap"===overflow&&(pointsWithNegativeX.length>pointsWithPositiveX.length?(shapeSides=shapeSides.map((side=>{let point0=side[0],point1=side[1];return point0=[Math.min(point0[0],0),point0[1]],point1=[Math.min(point1[0],0),point1[1]],[point0,point1]})),sliceGeometry=reverse$5(fromSides(shapeSides)),sliceGeometry=mirrorX(sliceGeometry)):pointsWithPositiveX.length>=pointsWithNegativeX.length&&(shapeSides=shapeSides.map((side=>{let point0=side[0],point1=side[1];return point0=[Math.max(point0[0],0),point0[1]],point1=[Math.max(point1[0],0),point1[1]],[point0,point1]})),sliceGeometry=fromSides(shapeSides)));const rotationPerSlice=totalRotation/segments,isCapped=Math.abs(totalRotation){let Zrotation=rotationPerSlice*index+startAngle;return totalRotation===TAU&&index===segments&&(Zrotation=startAngle),multiply$1(matrix,fromZRotation(matrix,Zrotation),fromXRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],TAU/4)),transform$3(matrix,base)}};const output=extrudeFromSlices(options,baseSlice);return geometry.color&&(output.color=geometry.color),output},rotate=(angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},translate=(offset,...objects)=>{if(!Array.isArray(offset))throw new Error("offset must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(offset=offset.slice();offset.length<3;)offset.push(0);const matrix=fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offset),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},solveAngleFromSSS=(a,b,c)=>Math.acos((a*a+b*b-c*c)/(2*a*b)),solveSAS=values=>{const c=values[0],B=values[1],a=values[2],b=((a,C,b)=>C>NEPS?Math.sqrt(a*a+b*b-2*a*b*Math.cos(C)):Math.sqrt((a-b)*(a-b)+a*b*C*C*(1-C*C/12)))(c,B,a),A=solveAngleFromSSS(b,c,a),C=Math.PI-A-B;return createTriangle(A,B,C,a,b,c)},createTriangle=(A,B,C,a,b,c)=>{const p0=fromValues$2(0,0),p1=fromValues$2(c,0),p2=fromValues$2(a,0);return add(p2,rotate$1(p2,p2,[0,0],Math.PI-B),p1),create$a([[p0,p1,p2]])},simplex={height:14,32:[16],33:[10,5,21,5,7,void 0,5,2,4,1,5,0,6,1,5,2],34:[16,4,21,4,14,void 0,12,21,12,14],35:[21,11,25,4,-7,void 0,17,25,10,-7,void 0,4,12,18,12,void 0,3,6,17,6],36:[20,8,25,8,-4,void 0,12,25,12,-4,void 0,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],37:[24,21,21,3,0,void 0,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,void 0,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7],38:[26,23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2],39:[10,5,19,4,20,5,21,6,20,6,18,5,16,4,15],40:[14,11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7],41:[14,3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7],42:[16,8,21,8,9,void 0,3,18,13,12,void 0,13,18,3,12],43:[26,13,18,13,0,void 0,4,9,22,9],44:[10,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],45:[26,4,9,22,9],46:[10,5,2,4,1,5,0,6,1,5,2],47:[22,20,25,2,-7],48:[20,9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21],49:[20,6,17,8,18,11,21,11,0],50:[20,4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0],51:[20,5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],52:[20,13,21,3,7,18,7,void 0,13,21,13,0],53:[20,15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],54:[20,16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7],55:[20,17,21,7,0,void 0,3,21,17,21],56:[20,8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21],57:[20,16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3],58:[10,5,14,4,13,5,12,6,13,5,14,void 0,5,2,4,1,5,0,6,1,5,2],59:[10,5,14,4,13,5,12,6,13,5,14,void 0,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],60:[24,20,18,4,9,20,0],61:[26,4,12,22,12,void 0,4,6,22,6],62:[24,4,18,20,9,4,0],63:[18,3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,void 0,9,2,8,1,9,0,10,1,9,2],64:[27,18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,void 0,12,16,10,14,9,11,9,8,10,6,11,5,void 0,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,void 0,19,16,18,8,18,6,19,5],65:[18,9,21,1,0,void 0,9,21,17,0,void 0,4,7,14,7],66:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,void 0,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0],67:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5],68:[21,4,21,4,0,void 0,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0],69:[19,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11,void 0,4,0,17,0],70:[18,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11],71:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,void 0,13,8,18,8],72:[22,4,21,4,0,void 0,18,21,18,0,void 0,4,11,18,11],73:[8,4,21,4,0],74:[16,12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7],75:[21,4,21,4,0,void 0,18,21,4,7,void 0,9,12,18,0],76:[17,4,21,4,0,void 0,4,0,16,0],77:[24,4,21,4,0,void 0,4,21,12,0,void 0,20,21,12,0,void 0,20,21,20,0],78:[22,4,21,4,0,void 0,4,21,18,0,void 0,18,21,18,0],79:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21],80:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10],81:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,void 0,12,4,18,-2],82:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,void 0,11,11,18,0],83:[20,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],84:[16,8,21,8,0,void 0,1,21,15,21],85:[22,4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21],86:[18,1,21,9,0,void 0,17,21,9,0],87:[24,2,21,7,0,void 0,12,21,7,0,void 0,12,21,17,0,void 0,22,21,17,0],88:[20,3,21,17,0,void 0,17,21,3,0],89:[18,1,21,9,11,9,0,void 0,17,21,9,11],90:[20,17,21,3,0,void 0,3,21,17,21,void 0,3,0,17,0],91:[14,4,25,4,-7,void 0,5,25,5,-7,void 0,4,25,11,25,void 0,4,-7,11,-7],92:[14,0,21,14,-3],93:[14,9,25,9,-7,void 0,10,25,10,-7,void 0,3,25,10,25,void 0,3,-7,10,-7],94:[16,6,15,8,18,10,15,void 0,3,12,8,17,13,12,void 0,8,17,8,0],95:[16,0,-2,16,-2],96:[10,6,21,5,20,4,18,4,16,5,15,6,16,5,17],97:[19,15,14,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],98:[19,4,21,4,0,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],99:[18,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],100:[19,15,21,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],101:[18,3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],102:[12,10,21,8,21,6,20,5,17,5,0,void 0,2,14,9,14],103:[19,15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],104:[19,4,21,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],105:[8,3,21,4,20,5,21,4,22,3,21,void 0,4,14,4,0],106:[10,5,21,6,20,7,21,6,22,5,21,void 0,6,14,6,-3,5,-6,3,-7,1,-7],107:[17,4,21,4,0,void 0,14,14,4,4,void 0,8,8,15,0],108:[8,4,21,4,0],109:[30,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0,void 0,15,10,18,13,20,14,23,14,25,13,26,10,26,0],110:[19,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],111:[19,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14],112:[19,4,14,4,-7,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],113:[19,15,14,15,-7,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],114:[13,4,14,4,0,void 0,4,8,5,11,7,13,9,14,12,14],115:[17,14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3],116:[12,5,21,5,4,6,1,8,0,10,0,void 0,2,14,9,14],117:[19,4,14,4,4,5,1,7,0,10,0,12,1,15,4,void 0,15,14,15,0],118:[16,2,14,8,0,void 0,14,14,8,0],119:[22,3,14,7,0,void 0,11,14,7,0,void 0,11,14,15,0,void 0,19,14,15,0],120:[17,3,14,14,0,void 0,14,14,3,0],121:[16,2,14,8,0,void 0,14,14,8,0,6,-4,4,-6,2,-7,1,-7],122:[17,14,14,3,0,void 0,3,14,14,14,void 0,3,0,14,0],123:[14,9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,void 0,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,void 0,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7],124:[8,4,25,4,-7],125:[14,5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,void 0,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,void 0,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7],126:[24,3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,void 0,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]},defaultsVectorParams$1={xOffset:0,yOffset:0,font:simplex,height:14,extrudeOffset:0},vectorChar=(options,text)=>{const{xOffset:xOffset,yOffset:yOffset,font:font,height:height,extrudeOffset:extrudeOffset}=Object.assign({},defaultsVectorParams$1,options);if("string"!=typeof text||1!==text.length)throw new Error("text must be a single character");let code=text.charCodeAt(0);code&&font[code]||(code=63);const glyph=[].concat(font[code]),ratio=(height-extrudeOffset)/font.height,extrudeYOffset=extrudeOffset/2,width=glyph.shift()*ratio,paths=[];let polyline=[];for(let i=0,il=glyph.length;i{const{x:x,y:y}=Object.assign({x:0,y:0},options);return identity(matrix),translate$1(matrix,matrix,[x,y,0]),line.chars=line.chars.map((vchar=>(vchar.paths=vchar.paths.map((path=>transform$5(matrix,path))),vchar))),line},areAllShapesTheSameType=shapes=>{let previousType;for(const shape of shapes){let currentType=0;if(isA$5(shape)&&(currentType=1),isA$3(shape)&&(currentType=2),isA$2(shape)&&(currentType=3),previousType&¤tType!==previousType)return!1;previousType=currentType}return!0},DEFAULT_COMPARE=(a,b)=>a>b?1:a{const N=new Node$1(null,null);let l=N,r=N;for(;;){const cmp=comparator(i,t.key);if(cmp<0){if(null===t.left)break;if(comparator(i,t.left.key)<0){const y=t.left;if(t.left=y.right,y.right=t,null===(t=y).left)break}r.left=t,r=t,t=t.left}else{if(!(cmp>0))break;if(null===t.right)break;if(comparator(i,t.right.key)>0){const y=t.right;if(t.right=y.left,y.left=t,null===(t=y).right)break}l.right=t,l=t,t=t.right}}return l.right=t.left,r.left=t.right,t.left=N.right,t.right=N.left,t},insert=(i,data,t,comparator)=>{const node=new Node$1(i,data);if(null===t)return node.left=node.right=null,node;const cmp=comparator(i,(t=splay(i,t,comparator)).key);return cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>=0&&(node.right=t.right,node.left=t,t.right=null),node},split=(key,v,comparator)=>{let left=null,right=null;if(v){const cmp=comparator((v=splay(key,v,comparator)).key,key);0===cmp?(left=v.left,right=v.right):cmp<0?(right=v.right,v.right=null,left=v):(left=v.left,v.left=null,right=v)}return{left:left,right:right}},printRow=(root,prefix,isTail,out,printNode)=>{if(root){out(`${prefix}${isTail?"└── ":"├── "}${printNode(root)}\n`);const indent=prefix+(isTail?" ":"│ ");root.left&&printRow(root.left,indent,!1,out,printNode),root.right&&printRow(root.right,indent,!0,out,printNode)}};class Tree$1{constructor(comparator=DEFAULT_COMPARE){this._comparator=comparator,this._root=null,this._size=0}insert(key,data){return this._size++,this._root=insert(key,data,this._root,this._comparator),this._root}add(key,data){const node=new Node$1(key,data);null===this._root&&(node.left=node.right=null,this._size++,this._root=node);const comparator=this._comparator,t=splay(key,this._root,comparator),cmp=comparator(key,t.key);return 0===cmp?this._root=t:(cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>0&&(node.right=t.right,node.left=t,t.right=null),this._size++,this._root=node),this._root}remove(key){this._root=this._remove(key,this._root,this._comparator)}_remove(i,t,comparator){let x;return null===t?null:0===comparator(i,(t=splay(i,t,comparator)).key)?(null===t.left?x=t.right:(x=splay(i,t.left,comparator),x.right=t.right),this._size--,x):t}pop(){let node=this._root;if(node){for(;node.left;)node=node.left;return this._root=splay(node.key,this._root,this._comparator),this._root=this._remove(node.key,this._root,this._comparator),{key:node.key,data:node.data}}return null}findStatic(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return current;current=cmp<0?current.left:current.right}return null}find(key){return this._root&&(this._root=splay(key,this._root,this._comparator),0!==this._comparator(key,this._root.key))?null:this._root}contains(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return!0;current=cmp<0?current.left:current.right}return!1}forEach(visitor,ctx){let current=this._root;const Q=[];let done=!1;for(;!done;)null!==current?(Q.push(current),current=current.left):0!==Q.length?(current=Q.pop(),visitor.call(ctx,current),current=current.right):done=!0;return this}range(low,high,fn,ctx){const Q=[],compare=this._comparator;let cmp,node=this._root;for(;0!==Q.length||node;)if(node)Q.push(node),node=node.left;else{if(node=Q.pop(),cmp=compare(node.key,high),cmp>0)break;if(compare(node.key,low)>=0&&fn.call(ctx,node))return this;node=node.right}return this}keys(){const keys=[];return this.forEach((({key:key})=>keys.push(key))),keys}values(){const values=[];return this.forEach((({data:data})=>values.push(data))),values}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(index){let current=this._root,done=!1,i=0;const Q=[];for(;!done;)if(current)Q.push(current),current=current.left;else if(Q.length>0){if(current=Q.pop(),i===index)return current;i++,current=current.right}else done=!0;return null}next(d){let root=this._root,successor=null;if(d.right){for(successor=d.right;successor.left;)successor=successor.left;return successor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?(successor=root,root=root.left):root=root.right}return successor}prev(d){let root=this._root,predecessor=null;if(null!==d.left){for(predecessor=d.left;predecessor.right;)predecessor=predecessor.right;return predecessor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?root=root.left:(predecessor=root,root=root.right)}return predecessor}clear(){return this._root=null,this._size=0,this}toList(){return toList(this._root)}load(keys,values=[],presort=!1){let size=keys.length;const comparator=this._comparator;if(presort&&sort(keys,values,0,size-1,comparator),null===this._root)this._root=loadRecursive(keys,values,0,size),this._size=size;else{const mergedList=mergeLists(this.toList(),createList(keys,values),comparator);size=this._size+size,this._root=sortedListToBST({head:mergedList},0,size)}return this}isEmpty(){return null===this._root}size(){return this._size}root(){return this._root}toString(printNode=(n=>String(n.key))){const out=[];return printRow(this._root,"",!0,(v=>out.push(v)),printNode),out.join("")}update(key,newKey,newData){const comparator=this._comparator;let{left:left,right:right}=split(key,this._root,comparator);comparator(key,newKey)<0?right=insert(newKey,newData,right,comparator):left=insert(newKey,newData,left,comparator),this._root=((left,right,comparator)=>null===right?left:(null===left||((right=splay(left.key,right,comparator)).left=left),right))(left,right,comparator)}split(key){return split(key,this._root,this._comparator)}*[Symbol.iterator](){let n=this.minNode();for(;n;)yield n,n=this.next(n)}}const loadRecursive=(keys,values,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),key=keys[middle],data=values[middle],node=new Node$1(key,data);return node.left=loadRecursive(keys,values,start,middle),node.right=loadRecursive(keys,values,middle+1,end),node}return null},createList=(keys,values)=>{const head=new Node$1(null,null);let p=head;for(let i=0;i{let current=root;const Q=[];let done=!1;const head=new Node$1(null,null);let p=head;for(;!done;)current?(Q.push(current),current=current.left):Q.length>0?(current=p=p.next=Q.pop(),current=current.right):done=!0;return p.next=null,head.next},sortedListToBST=(list,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),left=sortedListToBST(list,start,middle),root=list.head;return root.left=left,list.head=list.head.next,root.right=sortedListToBST(list,middle+1,end),root}return null},mergeLists=(l1,l2,compare)=>{const head=new Node$1(null,null);let p=head,p1=l1,p2=l2;for(;null!==p1&&null!==p2;)compare(p1.key,p2.key)<0?(p.next=p1,p1=p1.next):(p.next=p2,p2=p2.next),p=p.next;return null!==p1?p.next=p1:null!==p2&&(p.next=p2),head.next},sort=(keys,values,left,right,compare)=>{if(left>=right)return;const pivot=keys[left+right>>1];let i=left-1,j=right+1;for(;;){do{i++}while(compare(keys[i],pivot)<0);do{j--}while(compare(keys[j],pivot)>0);if(i>=j)break;let tmp=keys[i];keys[i]=keys[j],keys[j]=tmp,tmp=values[i],values[i]=values[j],values[j]=tmp}sort(keys,values,left,j,compare),sort(keys,values,j+1,right,compare)},computeFields=(event,prev,operation)=>{null===prev?(event.inOut=!1,event.otherInOut=!0):(event.isSubject===prev.isSubject?(event.inOut=!prev.inOut,event.otherInOut=prev.otherInOut):(event.inOut=!prev.otherInOut,event.otherInOut=prev.isVertical()?!prev.inOut:prev.inOut),prev&&(event.prevInResult=!inResult(prev,operation)||prev.isVertical()?prev.prevInResult:prev));const isInResult=inResult(event,operation);event.resultTransition=isInResult?determineResultTransition(event,operation):0},inResult=(event,operation)=>{switch(event.type){case 0:switch(operation){case 0:return!event.otherInOut;case 1:return event.otherInOut;case 2:return event.isSubject&&event.otherInOut||!event.isSubject&&!event.otherInOut;case 3:return!0}break;case 2:return 0===operation||1===operation;case 3:return 2===operation;case 1:return!1}return!1},determineResultTransition=(event,operation)=>{const thisIn=!event.inOut,thatIn=!event.otherInOut;let isIn;switch(operation){case 0:isIn=thisIn&&thatIn;break;case 1:isIn=thisIn||thatIn;break;case 3:isIn=thisIn^thatIn;break;case 2:isIn=event.isSubject?thisIn&&!thatIn:thatIn&&!thisIn}return isIn?1:-1};class SweepEvent{constructor(point,left,otherEvent,isSubject,edgeType){this.left=left,this.point=point,this.otherEvent=otherEvent,this.isSubject=isSubject,this.type=edgeType||0,this.inOut=!1,this.otherInOut=!1,this.prevInResult=null,this.resultTransition=0,this.otherPos=-1,this.outputContourId=-1,this.isExteriorRing=!0}isBelow(p){const p0=this.point,p1=this.otherEvent.point;return this.left?(p0[0]-p[0])*(p1[1]-p[1])-(p1[0]-p[0])*(p0[1]-p[1])>0:(p1[0]-p[0])*(p0[1]-p[1])-(p0[0]-p[0])*(p1[1]-p[1])>0}isAbove(p){return!this.isBelow(p)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return 0!==this.resultTransition}clone(){const copy=new SweepEvent(this.point,this.left,this.otherEvent,this.isSubject,this.type);return copy.contourId=this.contourId,copy.resultTransition=this.resultTransition,copy.prevInResult=this.prevInResult,copy.isExteriorRing=this.isExteriorRing,copy.inOut=this.inOut,copy.otherInOut=this.otherInOut,copy}}const signedArea=(p0,p1,p2)=>{const res=(ax=p0[0],ay=p0[1],bx=p1[0],by=p1[1],cx=p2[0],cy=p2[1],(ay-cy)*(bx-cx)-(ax-cx)*(by-cy));var ax,ay,bx,by,cx,cy;return res>0?-1:res<0?1:0},compareEvents=(e1,e2)=>{const p1=e1.point,p2=e2.point;return p1[0]>p2[0]?1:p1[0]p2[1]?1:-1:specialCases(e1,e2,p1)},specialCases=(e1,e2,p1,p2)=>e1.left!==e2.left?e1.left?1:-1:0!==signedArea(p1,e1.otherEvent.point,e2.otherEvent.point)?e1.isBelow(e2.otherEvent.point)?-1:1:!e1.isSubject&&e2.isSubject?1:-1,divideSegment=(se,p,queue)=>{const r=new SweepEvent(p,!1,se,se.isSubject),l=new SweepEvent(p,!0,se.otherEvent,se.isSubject);return r.contourId=l.contourId=se.contourId,compareEvents(l,se.otherEvent)>0&&(se.otherEvent.left=!0,l.left=!1),se.otherEvent.otherEvent=l,se.otherEvent=r,queue.push(l),queue.push(r),queue},crossProduct=(a,b)=>a[0]*b[1]-a[1]*b[0],possibleIntersection=(se1,se2,queue)=>{const inter=((a1,a2,b1,b2,noEndpointTouch)=>{const va=[a2[0]-a1[0],a2[1]-a1[1]],vb=[b2[0]-b1[0],b2[1]-b1[1]],toPoint=(p,s,d)=>[p[0]+s*d[0],p[1]+s*d[1]],e=[b1[0]-a1[0],b1[1]-a1[1]];let kross=crossProduct(va,vb),sqrKross=kross*kross;const sqrLenA=dot$1(va,va);if(sqrKross>0){const s=crossProduct(e,vb)/kross;if(s<0||s>1)return null;const t=crossProduct(e,va)/kross;return t<0||t>1?null:0===s||1===s?noEndpointTouch?null:[toPoint(a1,s,va)]:0===t||1===t?noEndpointTouch?null:[toPoint(b1,t,vb)]:[toPoint(a1,s,va)]}if(kross=crossProduct(e,va),sqrKross=kross*kross,sqrKross>0)return null;const sa=dot$1(va,e)/sqrLenA,sb=sa+dot$1(va,vb)/sqrLenA,smin=Math.min(sa,sb),smax=Math.max(sa,sb);return smin<=1&&smax>=0?1===smin?noEndpointTouch?null:[toPoint(a1,smin>0?smin:0,va)]:0===smax?noEndpointTouch?null:[toPoint(a1,smax<1?smax:1,va)]:noEndpointTouch&&0===smin&&1===smax?null:[toPoint(a1,smin>0?smin:0,va),toPoint(a1,smax<1?smax:1,va)]:null})(se1.point,se1.otherEvent.point,se2.point,se2.otherEvent.point),nIntersections=inter?inter.length:0;if(0===nIntersections)return 0;if(1===nIntersections&&(equals$6(se1.point,se2.point)||equals$6(se1.otherEvent.point,se2.otherEvent.point)))return 0;if(2===nIntersections&&se1.isSubject===se2.isSubject)return 0;if(1===nIntersections)return equals$6(se1.point,inter[0])||equals$6(se1.otherEvent.point,inter[0])||divideSegment(se1,inter[0],queue),equals$6(se2.point,inter[0])||equals$6(se2.otherEvent.point,inter[0])||divideSegment(se2,inter[0],queue),1;const events=[];let leftCoincide=!1,rightCoincide=!1;return equals$6(se1.point,se2.point)?leftCoincide=!0:1===compareEvents(se1,se2)?events.push(se2,se1):events.push(se1,se2),equals$6(se1.otherEvent.point,se2.otherEvent.point)?rightCoincide=!0:1===compareEvents(se1.otherEvent,se2.otherEvent)?events.push(se2.otherEvent,se1.otherEvent):events.push(se1.otherEvent,se2.otherEvent),leftCoincide&&rightCoincide||leftCoincide?(se2.type=1,se1.type=se2.inOut===se1.inOut?2:3,leftCoincide&&!rightCoincide&÷Segment(events[1].otherEvent,events[0].point,queue),2):rightCoincide?(divideSegment(events[0],events[1].point,queue),3):events[0]!==events[3].otherEvent?(divideSegment(events[0],events[1].point,queue),divideSegment(events[1],events[2].point,queue),3):(divideSegment(events[0],events[1].point,queue),divideSegment(events[3].otherEvent,events[2].point,queue),3)},compareSegments=(le1,le2)=>{if(le1===le2)return 0;if(0!==signedArea(le1.point,le1.otherEvent.point,le2.point)||0!==signedArea(le1.point,le1.otherEvent.point,le2.otherEvent.point))return equals$6(le1.point,le2.point)?le1.isBelow(le2.otherEvent.point)?-1:1:le1.point[0]===le2.point[0]?le1.point[1]le2.contourId?1:-1}return 1===compareEvents(le1,le2)?1:-1};class Contour{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return null==this.holeOf}}const nextPos=(pos,resultEvents,processed,origPos)=>{let newPos=pos+1;const p=resultEvents[pos].point;let p1;const length=resultEvents.length;for(newPosorigPos;)newPos--;return newPos},initializeContourFromContext=(event,contours,contourId)=>{const contour=new Contour;if(null!=event.prevInResult){const prevInResult=event.prevInResult,lowerContourId=prevInResult.outputContourId,lowerResultTransition=prevInResult.resultTransition;if(lowerContourId<0)contour.holeOf=null,contour.depth=0;else if(lowerResultTransition>0){const lowerContour=contours[lowerContourId];if(null!=lowerContour.holeOf){const parentContourId=lowerContour.holeOf;contours[parentContourId].holeIds.push(contourId),contour.holeOf=parentContourId,contour.depth=contours[lowerContourId].depth}else contours[lowerContourId].holeIds.push(contourId),contour.holeOf=lowerContourId,contour.depth=contours[lowerContourId].depth+1}else contour.holeOf=null,contour.depth=contours[lowerContourId].depth}else contour.holeOf=null,contour.depth=0;return contour},connectEdges=sortedEvents=>{const resultEvents=(sortedEvents=>{let event,i,len,tmp;const resultEvents=[];for(i=0,len=sortedEvents.length;i{processed[pos]=!0,pos=resultEvents.length)&&resultEvents[pos];);contours.push(contour)}return contours};class Queue{constructor(data,compare){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this._up(this.length++)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return--this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos=0)break;data[pos]=data[bestChild],pos=bestChild}data[pos]=item}}const max=Math.max,min=Math.min;let contourId=0;const processPolygon=(contourOrHole,isSubject,depth,queue,bbox,isExteriorRing)=>{const len=contourOrHole.length-1;let s1,s2,e1,e2;for(let i=0;i0?e2.left=!0:e1.left=!0;const x=s1[0],y=s1[1];bbox[0]=min(bbox[0],x),bbox[1]=min(bbox[1],y),bbox[2]=max(bbox[2],x),bbox[3]=max(bbox[3],y),queue.push(e1),queue.push(e2)}},EMPTY=[],toMartinez=geometry=>{const outlines=[];return toOutlines(geometry).forEach((outline=>{equals$6(outline[0],outline[outline.length-1])?outlines.push(outline):outlines.push([...outline,outline[0]])})),[outlines]},fromOutlines=outlines=>(outlines.forEach((outline=>{equals$6(outline[0],outline[outline.length-1])&&outline.pop()})),outlines=outlines.filter((o=>o.length>=3)),create$a(outlines)),boolean=(subjectGeom,clippingGeom,operation)=>{const subject=toMartinez(subjectGeom),clipping=toMartinez(clippingGeom);let trivial=((subject,clipping,operation)=>{let result=null;if(subject.length*clipping.length==0){if(0===operation)return EMPTY;2===operation?result=subject:1!==operation&&3!==operation||(result=0===subject.length?clipping:subject)}return result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,operation);if(trivial)return trivial;const sbbox=[1/0,1/0,-1/0,-1/0],cbbox=[1/0,1/0,-1/0,-1/0],eventQueue=((subject,clipping,sbbox,cbbox,operation)=>{const eventQueue=new Queue([],compareEvents);let polygonSet,isExteriorRing,i,ii,j,jj;for(i=0,ii=subject.length;i{let result=null;return(sbbox[0]>cbbox[2]||cbbox[0]>sbbox[2]||sbbox[1]>cbbox[3]||cbbox[1]>sbbox[3])&&(0===operation?result=EMPTY:2===operation?result=subject:1!==operation&&3!==operation||(result=subject.concat(clipping))),result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,sbbox,cbbox,operation),trivial)return trivial;const sortedEvents=((eventQueue,subject,clipping,sbbox,cbbox,operation)=>{const sweepLine=new Tree$1(compareSegments),sortedEvents=[],rightBound=Math.min(sbbox[2],cbbox[2]);let prev,next,begin;for(;0!==eventQueue.length;){let event=eventQueue.pop();if(sortedEvents.push(event),0===operation&&event.point[0]>rightBound||2===operation&&event.point[0]>sbbox[2])break;if(event.left){next=prev=sweepLine.insert(event),begin=sweepLine.minNode(),prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next);const prevEvent=prev?prev.key:null;let prevprevEvent;if(computeFields(event,prevEvent,operation),next&&2===possibleIntersection(event,next.key,eventQueue)&&(computeFields(event,prevEvent,operation),computeFields(next.key,event,operation)),prev&&2===possibleIntersection(prev.key,event,eventQueue)){let prevprev=prev;prevprev=prevprev!==begin?sweepLine.prev(prevprev):null,prevprevEvent=prevprev?prevprev.key:null,computeFields(prevEvent,prevprevEvent,operation),computeFields(event,prevEvent,operation)}}else event=event.otherEvent,next=prev=sweepLine.find(event),prev&&next&&(prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next),sweepLine.remove(event),next&&prev&&possibleIntersection(prev.key,next.key,eventQueue))}return sortedEvents})(eventQueue,0,0,sbbox,cbbox,operation),contours=connectEdges(sortedEvents),polygons=[];for(let i=0;i=0;k--)hole.push(holePoints[k]);rings.push(hole)}polygons.push(rings)}}return polygons?fromOutlines(polygons.flat()):create$a()},interpolateBetween2DPointsForY=(point1,point2,y)=>{let t,f1=y-point1[1],f2=point2[1]-point1[1];return f2<0&&(f1=-f1,f2=-f2),t=f1<=0?0:f1>=f2?1:f2<1e-10?.5:f1/f2,point1[0]+t*(point2[0]-point1[0])};class OrthonormalFormula{constructor(plane){this.plane=plane;const rightVector=orthogonal([0,0,0],plane);this.v=normalize$1(rightVector,cross$1(rightVector,plane,rightVector)),this.u=cross$1([0,0,0],this.v,plane),this.planeOrigin=scale$3([0,0,0],plane,plane[3]),this.basisMap=new Map}getProjectionMatrix(){return fromValues$4(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)}getInverseProjectionMatrix(){return fromValues$4(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,this.planeOrigin[0],this.planeOrigin[1],this.planeOrigin[2],1)}to2D(vertex){const point=fromValues$2(dot$2(vertex,this.u),dot$2(vertex,this.v));return this.basisMap.set(point,vertex),point}to3D(point){const original=this.basisMap.get(point);if(original)return original;const v1=scale$3([0,0,0],this.u,point[0]),v2=scale$3([0,0,0],this.v,point[1]),v3=add$1(v1,v1,this.planeOrigin);return add$1(v2,v2,v3)}}const insertSorted=(array,element,compareFunc)=>{let leftBound=0,rightBound=array.length;for(;rightBound>leftBound;){const testIndex=Math.floor((leftBound+rightBound)/2);compareFunc(element,array[testIndex])>0?leftBound=testIndex+1:rightBound=testIndex}array.splice(leftBound,0,element)},fnNumberSort=(a,b)=>a-b,retessellate=geometry=>{if(geometry.isRetesselated)return geometry;const polygons=toPolygons$1(geometry).map(((polygon,index)=>({vertices:polygon.vertices,plane:plane(polygon),index:index}))),classified=classifyPolygons(polygons),destPolygons=[];classified.forEach((group=>{if(Array.isArray(group)){const reTessellateCoplanarPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const destPolygons=[],numPolygons=sourcePolygons.length,plane$1=plane(sourcePolygons[0]),orthonormalFormula=new OrthonormalFormula(plane$1),polygonVertices2d=[],polygonTopVertexIndexes=[],topy2polygonIndexes=new Map,yCoordinateToPolygonIndexes=new Map,yCoordinateBins=new Map;for(let polygonIndex=0;polygonIndex0){let miny,maxy;for(let i=0;imaxy)&&(maxy=y);let polygonIndexes=yCoordinateToPolygonIndexes.get(y);polygonIndexes||(polygonIndexes={},yCoordinateToPolygonIndexes.set(y,polygonIndexes)),polygonIndexes[polygonIndex]=!0}if(miny>=maxy)vertices2d=[],numVertices=0,minIndex=-1;else{let polygonIndexes=topy2polygonIndexes.get(miny);polygonIndexes||(polygonIndexes=[],topy2polygonIndexes.set(miny,polygonIndexes)),polygonIndexes.push(polygonIndex)}}vertices2d.reverse(),minIndex=numVertices-minIndex-1,polygonVertices2d.push(vertices2d),polygonTopVertexIndexes.push(minIndex)}const yCoordinates=[];yCoordinateToPolygonIndexes.forEach(((polylist,y)=>yCoordinates.push(y))),yCoordinates.sort(fnNumberSort);let activePolygons=[],prevOutPolygonRow=[];for(let yIndex=0;yIndex=numVertices&&(nextLeftVertexIndex=0),vertices2d[nextLeftVertexIndex][1]!==yCoordinate)break;newLeftVertexIndex=nextLeftVertexIndex}let nextRightVertexIndex=newRightVertexIndex-1;if(nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),vertices2d[nextRightVertexIndex][1]===yCoordinate&&(newRightVertexIndex=nextRightVertexIndex),newLeftVertexIndex!==activePolygon.leftVertexIndex&&newLeftVertexIndex===newRightVertexIndex)activePolygons.splice(activePolygonIndex,1),--activePolygonIndex;else{activePolygon.leftVertexIndex=newLeftVertexIndex,activePolygon.rightVertexIndex=newRightVertexIndex,activePolygon.topLeft=vertices2d[newLeftVertexIndex],activePolygon.topRight=vertices2d[newRightVertexIndex];let nextLeftVertexIndex=newLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0),activePolygon.bottomLeft=vertices2d[nextLeftVertexIndex];let nextRightVertexIndex=newRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),activePolygon.bottomRight=vertices2d[nextRightVertexIndex]}}}let nextYcoordinate;if(yIndex>=yCoordinates.length-1)activePolygons=[],nextYcoordinate=null;else{nextYcoordinate=Number(yCoordinates[yIndex+1]);const middleYcoordinate=.5*(yCoordinate+nextYcoordinate),startingPolygonIndexes=topy2polygonIndexes.get(yCoordinate);for(const polygonIndexKey in startingPolygonIndexes){const polygonIndex=startingPolygonIndexes[polygonIndexKey],vertices2d=polygonVertices2d[polygonIndex],numVertices=vertices2d.length,topVertexIndex=polygonTopVertexIndexes[polygonIndex];let topLeftVertexIndex=topVertexIndex;for(;;){let i=topLeftVertexIndex+1;if(i>=numVertices&&(i=0),vertices2d[i][1]!==yCoordinate)break;if(i===topVertexIndex)break;topLeftVertexIndex=i}let topRightVertexIndex=topVertexIndex;for(;;){let i=topRightVertexIndex-1;if(i<0&&(i=numVertices-1),vertices2d[i][1]!==yCoordinate)break;if(i===topLeftVertexIndex)break;topRightVertexIndex=i}let nextLeftVertexIndex=topLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0);let nextRightVertexIndex=topRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1);const newActivePolygon={polygonIndex:polygonIndex,leftVertexIndex:topLeftVertexIndex,rightVertexIndex:topRightVertexIndex,topLeft:vertices2d[topLeftVertexIndex],topRight:vertices2d[topRightVertexIndex],bottomLeft:vertices2d[nextLeftVertexIndex],bottomRight:vertices2d[nextRightVertexIndex]};insertSorted(activePolygons,newActivePolygon,((el1,el2)=>{const x1=interpolateBetween2DPointsForY(el1.topLeft,el1.bottomLeft,middleYcoordinate),x2=interpolateBetween2DPointsForY(el2.topLeft,el2.bottomLeft,middleYcoordinate);return x1>x2?1:x10){const prevOutPolygon=newOutPolygonRow[newOutPolygonRow.length-1],d1=distance(outPolygon.topLeft,prevOutPolygon.topRight),d2=distance(outPolygon.bottomLeft,prevOutPolygon.bottomRight);d10){const prevContinuedIndexes=new Set,matchedIndexes=new Set;for(let i=0;i=0)&&(rightLineContinues||d2>=0)&&(thisPolygon.outPolygon=prevPolygon.outPolygon,thisPolygon.leftLineContinues=leftLineContinues,thisPolygon.rightLineContinues=rightLineContinues,prevContinuedIndexes.add(ii));break}}}for(let ii=0;iiEPS&&prevPolygon.outPolygon.leftPoints.push(prevPolygon.bottomLeft),prevPolygon.outPolygon.leftPoints.reverse();const vertices3d=prevPolygon.outPolygon.rightPoints.concat(prevPolygon.outPolygon.leftPoints).map((point2d=>orthonormalFormula.to3D(point2d))),polygon=fromVerticesAndPlane(vertices3d,plane$1);polygon.vertices.length&&destPolygons.push(polygon)}}for(let i=0;iEPS&&thisPolygon.outPolygon.rightPoints.push(thisPolygon.topRight))}prevOutPolygonRow=newOutPolygonRow}return destPolygons})(group);destPolygons.push(...reTessellateCoplanarPolygons)}else destPolygons.push(group)}));const result=create$8(destPolygons);return result.isRetesselated=!0,result},classifyPolygons=polygons=>{let clusters=[polygons];const nonCoplanar=[];for(let component=3;component>=0;component--){const maybeCoplanar=[],tolerance=3===component?15e-9:NEPS;clusters.forEach((cluster=>{cluster.sort(byPlaneComponent(component,tolerance));let startIndex=0;for(let i=1;itolerance&&(i-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex,i)),startIndex=i);cluster.length-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex))})),clusters=maybeCoplanar}const result=[];return clusters.forEach((cluster=>{cluster[0]&&(result[cluster[0].index]=cluster)})),nonCoplanar.forEach((polygon=>{result[polygon.index]=polygon})),result},byPlaneComponent=(component,tolerance)=>(a,b)=>a.plane[component]-b.plane[component]>tolerance?1:b.plane[component]-a.plane[component]>tolerance?-1:0;class Node{constructor(parent){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=parent}invert(){const queue=[this];let node;for(let i=0;i{treeNode.isRemoved()||treeNode.splitByPlane(plane,coplanarFrontNodes,backNodes,frontNodes,backNodes)})),node.front&&frontNodes.length>0&&stack.push({node:node.front,polygonTreeNodes:frontNodes});const numBackNodes=backNodes.length;if(node.back&&numBackNodes>0)stack.push({node:node.back,polygonTreeNodes:backNodes});else for(let i=0;i0&&tree.rootnode.clipPolygons(node.polygontreenodes,alsoRemoveCoplanarFront),node.front&&stack.push(node.front),node.back&&stack.push(node.back),node=stack.pop()}while(void 0!==node)}addPolygonTreeNodes(newPolygonTreeNodes){let current={node:this,polygonTreeNodes:newPolygonTreeNodes};const stack=[];do{const node=current.node,polygonTreeNodes=current.polygonTreeNodes,len=polygonTreeNodes.length;if(0===len){current=stack.pop();continue}if(!node.plane){let index=0;index=Math.floor(len/2);const bestPoly=polygonTreeNodes[index].getPolygon();node.plane=plane(bestPoly)}const frontNodes=[],backNodes=[];for(let i=0;i0&&(node.front||(node.front=new Node(node)),len===frontNodes.length&&0===backNodes.length?node.front.polygontreenodes=frontNodes:stack.push({node:node.front,polygonTreeNodes:frontNodes})),backNodes.length>0&&(node.back||(node.back=new Node(node)),len===backNodes.length&&0===frontNodes.length?node.back.polygontreenodes=backNodes:stack.push({node:node.back,polygonTreeNodes:backNodes})),current=stack.pop()}while(void 0!==current)}}const splitLineSegmentByPlane=(plane,p1,p2)=>{const direction=subtract$3([0,0,0],p2,p1);let lambda=(plane[3]-dot$2(plane,p1))/dot$2(plane,direction);return Number.isNaN(lambda)&&(lambda=0),lambda>1&&(lambda=1),lambda<0&&(lambda=0),scale$3(direction,direction,lambda),add$1(direction,p1,direction),direction};class PolygonTreeNode{constructor(parent,polygon){this.parent=parent,this.children=[],this.polygon=polygon,this.removed=!1}addPolygons(polygons){if(!this.isRootNode())throw new Error("Assertion failed");const _this=this;polygons.forEach((polygon=>{_this.addChild(polygon)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const parentschildren=this.parent.children,i=parentschildren.indexOf(this);if(i<0)throw new Error("Assertion failed");parentschildren.splice(i,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(result){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){if(this.children.length){const queue=[this.children];let i,j,l,node,nodes;for(i=0;i0?queue.push(node.children):node._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}else this._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}_splitByPlane(splane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){const polygon=this.polygon;if(polygon){const bound=measureBoundingSphere$1(polygon),sphereRadius=bound[3]+EPS,d=dot$2(splane,bound)-splane[3];if(d>sphereRadius)frontNodes.push(this);else if(d<-sphereRadius)backNodes.push(this);else{const splitResult=((splane,polygon)=>{const result={type:null,front:null,back:null},vertices=polygon.vertices,numVertices=vertices.length,pplane=plane(polygon);if(equals$5(pplane,splane))result.type=0;else{let hasFront=!1,hasBack=!1;const vertexIsBack=[],MINEPS=-EPS;for(let i=0;iEPS&&(hasFront=!0),t=numVertices&&(nextVertexIndex=0);const nextIsBack=vertexIsBack[nextVertexIndex];if(isback===nextIsBack)isback?backVertices.push(vertex):frontVertices.push(vertex);else{const nextPoint=vertices[nextVertexIndex],intersectionPoint=splitLineSegmentByPlane(splane,vertex,nextPoint);isback?(backVertices.push(vertex),backVertices.push(intersectionPoint),frontVertices.push(intersectionPoint)):(frontVertices.push(vertex),frontVertices.push(intersectionPoint),backVertices.push(intersectionPoint))}isback=nextIsBack}const EPS_SQUARED=EPS*EPS;if(backVertices.length>=3){let prevVertex=backVertices[backVertices.length-1];for(let vertexIndex=0;vertexIndex=3){let prevVertex=frontVertices[frontVertices.length-1];for(let vertexIndex=0;vertexIndex=3&&(result.front=fromVerticesAndPlane(frontVertices,pplane)),backVertices.length>=3&&(result.back=fromVerticesAndPlane(backVertices,pplane))}else result.type=3;else result.type=2;else{const t=dot$2(splane,pplane);result.type=t>=0?0:1}}return result})(splane,polygon);switch(splitResult.type){case 0:coplanarFrontNodes.push(this);break;case 1:coplanarBackNodes.push(this);break;case 2:frontNodes.push(this);break;case 3:backNodes.push(this);break;case 4:if(splitResult.front){const frontNode=this.addChild(splitResult.front);frontNodes.push(frontNode)}if(splitResult.back){const backNode=this.addChild(splitResult.back);backNodes.push(backNode)}}}}}addChild(polygon){const newChild=new PolygonTreeNode(this,polygon);return this.children.push(newChild),newChild}invertSub(){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let children=[this];const queue=[children];for(let i=0;i0&&queue.push(node.children),node.children=[]}}}toString(){let result="",children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}return result}}class Tree{constructor(polygons){this.polygonTree=new PolygonTreeNode,this.rootnode=new Node(null),polygons&&this.addPolygons(polygons)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(tree,alsoRemoveCoplanarFront=!1){this.rootnode.clipTo(tree,alsoRemoveCoplanarFront)}allPolygons(){const result=[];return this.polygonTree.getPolygons(result),result}addPolygons(polygons){const polygonTreeNodes=new Array(polygons.length);for(let i=0;i{if(0===geometry1.polygons.length||0===geometry2.polygons.length)return!1;const bounds1=measureBoundingBox(geometry1),min1=bounds1[0],max1=bounds1[1],bounds2=measureBoundingBox(geometry2),min2=bounds2[0],max2=bounds2[1];return!(min2[0]-max1[0]>EPS||min1[0]-max2[0]>EPS||min2[1]-max1[1]>EPS||min1[1]-max2[1]>EPS||min2[2]-max1[2]>EPS||min1[2]-max2[2]>EPS)},intersectGeom3=(...geometries)=>{let newGeometry=(geometries=flatten(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return create$8();const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),b.clipTo(a),b.invert(),a.clipTo(b),b.clipTo(a),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=retessellate(newGeometry),newGeometry},subtractGeom3=(...geometries)=>{let newGeometry=(geometries=flatten(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return clone$7(geometry1);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),a.clipTo(b),b.clipTo(a,!0),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=retessellate(newGeometry),newGeometry},unionGeom2=(...geometries)=>{let newGeometry=(geometries=flatten(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,1)})),newGeometry},unionGeom3Sub=(geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return unionForNonIntersecting(geometry1,geometry2);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.clipTo(b,!1),b.clipTo(a),b.invert(),b.clipTo(a),b.invert();const newPolygons=a.allPolygons().concat(b.allPolygons());return create$8(newPolygons)},unionForNonIntersecting=(geometry1,geometry2)=>{let newpolygons=toPolygons$1(geometry1);return newpolygons=newpolygons.concat(toPolygons$1(geometry2)),create$8(newpolygons)},union=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("union wrong number of arguments");if(!areAllShapesTheSameType(geometries))throw new Error("union arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return unionGeom2(geometries);if(isA$3(geometry))return((...geometries)=>{let i;for(geometries=flatten(geometries),i=1;i{let{offset:offset,twistAngle:twistAngle,twistSteps:twistSteps,repair:repair}=Object.assign({},{offset:[0,0,1],twistAngle:0,twistSteps:12,repair:!0},options);if(twistSteps<1)throw new Error("twistSteps must be 1 or more");0===twistAngle&&(twistSteps=1);const offsetV=clone$9(offset);let baseSlice=fromGeom2(geometry);offsetV[2]<0&&(baseSlice=reverse$2(baseSlice));const matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];options={numberOfSlices:twistSteps+1,capStart:!0,capEnd:!0,repair:repair,callback:(progress,index,base)=>{const Zrotation=index/twistSteps*twistAngle,Zoffset=scale$3([0,0,0],offsetV,index/twistSteps);return multiply$1(matrix,fromZRotation(matrix,Zrotation),fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],Zoffset)),transform$3(matrix,base)}};const output=extrudeFromSlices(options,baseSlice);return geometry.color&&(output.color=geometry.color),output},aboutEqualNormals=(a,b)=>Math.abs(a[0]-b[0])<=NEPS&&Math.abs(a[1]-b[1])<=NEPS&&Math.abs(a[2]-b[2])<=NEPS,hullPoints2=uniquePoints=>{let min=fromValues$2(1/0,1/0);uniquePoints.forEach((point=>{(point[1]{const angle=fakeAtan2(point[1]-min[1],point[0]-min[0]),distSq=squaredDistance(point,min);points.push({point:point,angle:angle,distSq:distSq})})),points.sort(((pt1,pt2)=>pt1.angle!==pt2.angle?pt1.angle-pt2.angle:pt1.distSq-pt2.distSq));const stack=[];return points.forEach((point=>{let cnt=stack.length;for(;cnt>1&&ccw(stack[cnt-2],stack[cnt-1],point.point)<=Number.EPSILON;)stack.pop(),cnt=stack.length;stack.push(point.point)})),stack},ccw=(v1,v2,v3)=>(v2[0]-v1[0])*(v3[1]-v1[1])-(v2[1]-v1[1])*(v3[0]-v1[0]),fakeAtan2=(y,x)=>0===y&&0===x?-1/0:-x/y,toUniquePoints=geometries=>{const found=new Set,uniquePoints=[],addPoint=point=>{const key=point.toString();found.has(key)||(uniquePoints.push(point),found.add(key))};return geometries.forEach((geometry=>{isA$5(geometry)?toPoints$3(geometry).forEach(addPoint):isA$3(geometry)?toPoints$2(geometry).forEach((points=>points.forEach(addPoint))):isA$2(geometry)&&toPoints$1(geometry).forEach(addPoint)})),uniquePoints},pointLineDistance=(point,a,b)=>Math.sqrt(((p,a,b)=>{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b));class VertexList{constructor(){this.head=null,this.tail=null}clear(){this.head=this.tail=null}insertBefore(target,node){node.prev=target.prev,node.next=target,node.prev?node.prev.next=node:this.head=node,target.prev=node}insertAfter(target,node){node.prev=target,node.next=target.next,node.next?node.next.prev=node:this.tail=node,target.next=node}add(node){this.head?this.tail.next=node:this.head=node,node.prev=this.tail,node.next=null,this.tail=node}addAll(node){for(this.head?this.tail.next=node:this.head=node,node.prev=this.tail;node.next;)node=node.next;this.tail=node}remove(node){node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev}removeChain(a,b){a.prev?a.prev.next=b.next:this.head=b.next,b.next?b.next.prev=a.prev:this.tail=a.prev}first(){return this.head}isEmpty(){return!this.head}}class Vertex{constructor(point,index){this.point=point,this.index=index,this.next=null,this.prev=null,this.face=null}}class HalfEdge{constructor(vertex,face){this.vertex=vertex,this.face=face,this.next=null,this.prev=null,this.opposite=null}head(){return this.vertex}tail(){return this.prev?this.prev.vertex:null}length(){return this.tail()?distance$1(this.tail().point,this.head().point):-1}lengthSquared(){return this.tail()?squaredDistance$1(this.tail().point,this.head().point):-1}setOpposite(edge){this.opposite=edge,edge.opposite=this}}class Face{constructor(){this.normal=[],this.centroid=[],this.offset=0,this.outside=null,this.mark=0,this.edge=null,this.nVertices=0}getEdge(i){if("number"!=typeof i)throw Error("requires a number");let it=this.edge;for(;i>0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;imaxDistance&&(maxDistance=distance,v2=vertex)}}const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i{if(1===(geometries=flatten(geometries)).length)return geometries[0];const unique=toUniquePoints(geometries),polygons=((points,options={})=>{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)})(unique,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>unique[index]));return create$7(vertices)}));return create$8(polygons)},hull=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");if(!areAllShapesTheSameType(geometries))throw new Error("only hulls of the same type are supported");const geometry=geometries[0];return isA$2(geometry)?((...geometries)=>{geometries=flatten(geometries);const unique=toUniquePoints(geometries),hullPoints=hullPoints2(unique);return fromPoints$2({closed:!0},hullPoints)})(geometries):isA$5(geometry)?((...geometries)=>{geometries=flatten(geometries);const unique=toUniquePoints(geometries),hullPoints=hullPoints2(unique);return hullPoints.length<3?create$a():create$a([hullPoints])})(geometries):isA$3(geometry)?hullGeom3(geometries):geometry},snapPolygons=(epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons},createEdges=polygon=>{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergeCoplanarPolygons=sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&aboutEqualNormals(plane1,plane2);var plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const sourcePolygons=mapping[1],retesselatedPolygons=mergeCoplanarPolygons(sourcePolygons);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=measureEpsilon(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=snapPolygons(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){let{delta:delta,corners:corners,closed:closed,segments:segments}=Object.assign({},{delta:1,corners:"edge",closed:!1,segments:16},options);if(Math.abs(delta)0&&delta>=0||rotation<0&&delta<0;delta=Math.abs(delta);let previousSegment=null,newPoints=[];const newCorners=[],of=[0,0],n=points.length;for(let i=0;ipointIndex.set(point,index)));const line0=[0,1,0],line1=[0,1,0];newCorners.forEach((corner=>{fromPoints$1(line0,corner.s0[0],corner.s0[1]),fromPoints$1(line1,corner.s1[0],corner.s1[1]);const ip=intersectPointOfLines(line0,line1);if(Number.isFinite(ip[0])&&Number.isFinite(ip[1])){const p0=corner.s0[1],i=pointIndex.get(p0);newPoints[i]=ip,newPoints[(i+1)%newPoints.length]=void 0}else{const p0=corner.s1[0],i=pointIndex.get(p0);newPoints[i]=void 0}})),newPoints=newPoints.filter((p=>void 0!==p))}if("round"===corners){let cornerSegments=Math.floor(segments/4);const v0=[0,0];newCorners.forEach((corner=>{let rotation=angleRadians(subtract$1(v0,corner.s1[0],corner.c));if(rotation-=angleRadians(subtract$1(v0,corner.s0[1],corner.c)),orientation&&rotation<0&&(rotation+=Math.PI,rotation<0&&(rotation+=Math.PI)),!orientation&&rotation>0&&(rotation-=Math.PI,rotation>0&&(rotation-=Math.PI)),0!==rotation){cornerSegments=Math.floor(segments*(Math.abs(rotation)/TAU));const step=rotation/cornerSegments,start=angleRadians(subtract$1(v0,corner.s0[1],corner.c)),cornerPoints=[];for(let i=1;i0){const p0=corner.s0[1];let i=newPoints.findIndex((point=>equals$6(p0,point)));i=(i+1)%newPoints.length,newPoints.splice(i,0,...cornerPoints)}}else{const p0=corner.s1[0],i=newPoints.findIndex((point=>equals$6(p0,point)));newPoints.splice(i,1)}}))}return newPoints},mapPlaneToVertex=(map,vertex,plane)=>{const key=vertex.toString();if(map.has(key))map.get(key)[1].push(plane);else{const entry=[vertex,[plane]];map.set(key,entry)}},mapPlaneToEdge=(map,edge,plane)=>{const key0=edge[0].toString(),key1=edge[1].toString(),key=key0{map.findIndex((item=>item===angle))<0&&map.push(angle)},offsetShell=(options,geometry)=>{const{delta:delta,segments:segments}=Object.assign({},{delta:1,segments:12},options);let result=create$8();const vertices2planes=new Map,edges2planes=new Map,v1=[0,0,0],v2=[0,0,0];return toPolygons$1(geometry).forEach((polygon=>{const extrudeVector=scale$3([0,0,0],plane(polygon),2*delta),extrudedFace=((offsetVector,polygon1)=>{dot$2(plane(polygon1),offsetVector)>0&&(polygon1=invert$1(polygon1));const newPolygons=[polygon1],polygon2=transform$7(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offsetVector),polygon1),numVertices=polygon1.vertices.length;for(let i=0;i{const edge=item[0],planes=item[1],startVertex=edge[0],endVertex=edge[1],zBase=subtract$3([0,0,0],endVertex,startVertex);normalize$1(zBase,zBase);const xBase=planes[0],yBase=cross$1([0,0,0],xBase,zBase);let angles=[];for(let i=0;i=0&&distance$1(p1,prevP1)=0){startFaceVertices.push(p1),endFaceVertices.push(p2);const polygon=create$7([prevP2,p2,p1,prevP1]);polygons.push(polygon)}prevP1=p1,prevP2=p2}}endFaceVertices.reverse(),polygons.push(create$7(startFaceVertices)),polygons.push(create$7(endFaceVertices));const cylinder=create$8(polygons);result=unionGeom3Sub(result,cylinder)})),vertices2planes.forEach((item=>{const vertex=item[0],planes=item[1],xaxis=planes[0];let bestzaxis=null,bestzaxisOrthogonality=0;for(let i=1;i.05&&crossLength>bestzaxisOrthogonality&&(bestzaxisOrthogonality=crossLength,bestzaxis=normal)}bestzaxis||(bestzaxis=orthogonal(v1,xaxis));const yaxis=cross$1(v1,xaxis,bestzaxis);normalize$1(yaxis,yaxis);const zaxis=cross$1(v2,yaxis,xaxis),corner=sphere({center:[vertex[0],vertex[1],vertex[2]],radius:delta,segments:segments,axes:[xaxis,yaxis,zaxis]});result=unionGeom3Sub(result,corner)})),retessellate(result)},offsetPath2=(options,geometry)=>{const{delta:delta,corners:corners,segments:segments}=Object.assign({},{delta:1,corners:"edge",segments:16},options);if(delta<=0)throw new Error("the given delta must be positive for paths");if("edge"!==corners&&"chamfer"!==corners&&"round"!==corners)throw new Error('corners must be "edge", "chamfer", or "round"');const closed=geometry.isClosed,points=toPoints$1(geometry),paths={points:points,external:offsetFromPoints({delta:delta,corners:corners,segments:segments,closed:closed},points),internal:offsetFromPoints({delta:-delta,corners:corners,segments:segments,closed:closed},points)},output=geometry.isClosed?(paths=>{let{external:external,internal:internal}=paths;return external.length<2?create$a():(area$1(external)<0?external=external.reverse():internal=internal.reverse(),create$a([external,internal]))})(paths):((paths,segments,corners,delta)=>{const{points:points,external:external,internal:internal}=paths;if(0===points.length)return create$a();if(1===points.length)return circle({center:points[0],radius:delta});const capSegments=Math.floor(segments/2),e2iCap=[],i2eCap=[];if("round"===corners&&capSegments>0){const step=Math.PI/capSegments,eCorner=points[points.length-1],e2iStart=angleRadians(subtract$1([0,0],external[external.length-1],eCorner)),iCorner=points[0],i2eStart=angleRadians(subtract$1([0,0],internal[0],iCorner));for(let i=1;i{for(anArray=anArray.slice();anArray.length{const bounds=measureAggregateBoundingBox(geometry),translation=[0,0,0];for(let i=0;i<3;i++)"center"===modes[i]?translation[i]=relativeTo[i]-(bounds[0][i]+bounds[1][i])/2:"max"===modes[i]?translation[i]=relativeTo[i]-bounds[1][i]:"min"===modes[i]&&(translation[i]=relativeTo[i]-bounds[0][i]);return translate(translation,geometry)},centerGeometry=(options,object)=>{const{axes:axes,relativeTo:relativeTo}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},options),bounds=measureBoundingBox(object),offset=[0,0,0];return axes[0]&&(offset[0]=relativeTo[0]-(bounds[0][0]+(bounds[1][0]-bounds[0][0])/2)),axes[1]&&(offset[1]=relativeTo[1]-(bounds[0][1]+(bounds[1][1]-bounds[0][1])/2)),axes[2]&&(offset[2]=relativeTo[2]-(bounds[0][2]+(bounds[1][2]-bounds[0][2])/2)),translate(offset,object)},center=(options,...objects)=>{const{axes:axes,relativeTo:relativeTo}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},options);if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");if(3!==relativeTo.length)throw new Error("relativeTo must be an array of length 3");options={axes:axes,relativeTo:relativeTo};const results=objects.map((object=>isA$2(object)||isA$5(object)||isA$3(object)?centerGeometry(options,object):object));return 1===results.length?results[0]:results},scale=(factors,...objects)=>{if(!Array.isArray(factors))throw new Error("factors must be an array");if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");for(factors=factors.slice();factors.length<3;)factors.push(1);if(factors[0]<=0||factors[1]<=0||factors[2]<=0)throw new Error("factors must be positive");const matrix=fromScaling([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],factors),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results};exports.EPS=EPS,exports.NEPS=NEPS,exports.TAU=TAU,exports.align=(options,...geometries)=>{options=(options=>{if(!Array.isArray(options.modes)||options.modes.length>3)throw new Error("align(): modes must be an array of length <= 3");if(options.modes=padArrayToLength(options.modes,"none",3),3!==options.modes.filter((mode=>["center","max","min","none"].includes(mode))).length)throw new Error('align(): all modes must be one of "center", "max" or "min"');if(!Array.isArray(options.relativeTo)||options.relativeTo.length>3)throw new Error("align(): relativeTo must be an array of length <= 3");if(options.relativeTo=padArrayToLength(options.relativeTo,0,3),3!==options.relativeTo.filter((alignVal=>Number.isFinite(alignVal)||null==alignVal)).length)throw new Error("align(): all relativeTo values must be a number, or null.");if("boolean"!=typeof options.grouped)throw new Error("align(): grouped must be a boolean value.");return options})(options=Object.assign({},{modes:["center","center","min"],relativeTo:[0,0,0],grouped:!1},options));let{modes:modes,relativeTo:relativeTo,grouped:grouped}=options;if(0===(geometries=flatten(geometries)).length)throw new Error("align(): No geometries were provided to act upon");if(relativeTo.filter((val=>null==val)).length){const bounds=measureAggregateBoundingBox(geometries);relativeTo=((relativeTo,modes,bounds)=>{for(let i=0;i<3;i++)null==relativeTo[i]&&("center"===modes[i]?relativeTo[i]=(bounds[0][i]+bounds[1][i])/2:"max"===modes[i]?relativeTo[i]=bounds[1][i]:"min"===modes[i]&&(relativeTo[i]=bounds[0][i]));return relativeTo})(relativeTo,modes,bounds)}return 1===(geometries=grouped?alignGeometries(geometries,modes,relativeTo):geometries.map((geometry=>alignGeometries(geometry,modes,relativeTo)))).length?geometries[0]:geometries},exports.arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGT(radius,0))throw new Error("radius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS*EPS)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps)),point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},exports.bezier=index$4,exports.center=center,exports.centerX=(...objects)=>center({axes:[!0,!1,!1]},objects),exports.centerY=(...objects)=>center({axes:[!1,!0,!1]},objects),exports.centerZ=(...objects)=>center({axes:[!1,!1,!0]},objects),exports.circle=circle,exports.colorNameToRgb=s=>cssColors[s.toLowerCase()],exports.colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");if(3===color.length&&(color=[color[0],color[1],color[2],1]),0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):(object.color=color,object)));return 1===results.length?results[0]:results},exports.cos=cos,exports.cssColors=cssColors,exports.cube=options=>{let{center:center,size:size}=Object.assign({},{center:[0,0,0],size:2},options);if(!isGTE(size,0))throw new Error("size must be positive");return size=[size,size,size],cuboid({center:center,size:size})},exports.cuboid=cuboid,exports.cylinder=cylinder,exports.cylinderElliptic=cylinderElliptic,exports.degToRad=degrees=>.017453292519943295*degrees,exports.ellipse=ellipse,exports.ellipsoid=ellipsoid,exports.extrudeFromSlices=extrudeFromSlices,exports.extrudeHelical=(options,geometry)=>{const defaults={angle:TAU,startAngle:0,pitch:10,endOffset:0,segmentsPerRotation:32},{angle:angle,endOffset:endOffset,segmentsPerRotation:segmentsPerRotation,startAngle:startAngle}=Object.assign({},defaults,options);let pitch;if(pitch=!options.pitch&&options.height?options.height/(angle/TAU):options.pitch?options.pitch:defaults.pitch,segmentsPerRotation<3)throw new Error("The number of segments per rotation needs to be at least 3.");let baseSlice=fromGeom2(geometry);measureBoundingBox(geometry)[1][0]<=0&&(baseSlice=reverse$2(baseSlice));const calculatedSegments=Math.round(segmentsPerRotation/TAU*Math.abs(angle)),segments=calculatedSegments>=2?calculatedSegments:2,step1=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];let matrix;return extrudeFromSlices({numberOfSlices:segments+1,callback:(progress,index,base)=>{const zRotation=startAngle+angle/segments*index;return multiply$1(step1,fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[endOffset/segments*index,0,(zRotation-startAngle)/TAU*pitch*Math.sign(angle)]),fromXRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],-TAU/4*Math.sign(angle))),matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],multiply$1(matrix,fromZRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],zRotation),step1),transform$3(matrix,baseSlice)}},baseSlice)},exports.extrudeLinear=(options,...objects)=>{const{height:height,twistAngle:twistAngle,twistSteps:twistSteps,repair:repair}=Object.assign({},{height:1,twistAngle:0,twistSteps:1,repair:!0},options);if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");options={offset:[0,0,height],twistAngle:twistAngle,twistSteps:twistSteps,repair:repair};const results=objects.map((object=>isA$2(object)?((options,geometry)=>{if(!geometry.isClosed)throw new Error("extruded path must be closed");const points=toPoints$1(geometry),geometry2=create$a([points]);return geometry.color&&(geometry2.color=geometry.color),extrudeLinearGeom2(options,geometry2)})(options,object):isA$5(object)?extrudeLinearGeom2(options,object):object));return 1===results.length?results[0]:results},exports.extrudeRotate=extrudeRotate,exports.flatten=flatten,exports.generalize=(options,...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>{if(isA$2(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$5(geometry))return((options,geometry)=>geometry)(0,geometry);if(isA$3(geometry))return generalizeGeom3(options,geometry);throw new Error("invalid geometry")}));return 1===results.length?results[0]:results},exports.geodesicSphere=options=>{let{radius:radius,frequency:frequency}=Object.assign({},{radius:1,frequency:6},options);if(!isGTE(radius,0))throw new Error("radius must be positive");if(!isGTE(frequency,6))throw new Error("frequency must be six or more");if(0===radius)return create$8();frequency=Math.floor(frequency/6);const ci=[[.850651,0,-.525731],[.850651,-0,.525731],[-.850651,-0,.525731],[-.850651,0,-.525731],[0,-.525731,.850651],[0,.525731,.850651],[0,.525731,-.850651],[0,-.525731,-.850651],[-.525731,-.850651,-0],[.525731,-.850651,-0],[.525731,.850651,0],[-.525731,.850651,0]],ti=[[0,9,1],[1,10,0],[6,7,0],[10,6,0],[7,9,0],[5,1,4],[4,1,9],[5,10,1],[2,8,3],[3,11,2],[2,5,4],[4,8,2],[2,11,5],[3,7,6],[6,11,3],[8,7,3],[9,8,4],[11,10,5],[10,11,6],[8,9,7]],geodesicSubDivide=(p,frequency,offset)=>{const p1=p[0],p2=p[1],p3=p[2];let n=offset;const c=[],f=[];for(let i=0;i{const _f=1-f,c=[];for(let i=0;i<3;i++)c[i]=a[i]*_f+b[i]*f;return c};let vertices=[],faces=[],offset=0;for(let i=0;i{if((notation=notation.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const r=parseInt(notation.substring(0,2),16)/255,g=parseInt(notation.substring(2,4),16)/255,b=parseInt(notation.substring(4,6),16)/255;return notation.length>=8?[r,g,b,parseInt(notation.substring(6,8),16)/255]:[r,g,b]},exports.hslToRgb=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain H, S and L values");const h=values[0],s=values[1],l=values[2];let r=l,g=l,b=l;if(0!==s){const q=l<.5?l*(1+s):l+s-l*s,p=2*l-q;r=hueToColorComponent(p,q,h+1/3),g=hueToColorComponent(p,q,h),b=hueToColorComponent(p,q,h-1/3)}return values.length>3?[r,g,b,values[3]]:[r,g,b]},exports.hsvToRgb=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain H, S and V values");const h=values[0],s=values[1],v=values[2];let r=0,g=0,b=0;const i=Math.floor(6*h),f=6*h-i,p=v*(1-s),q=v*(1-f*s),t=v*(1-(1-f)*s);switch(i%6){case 0:r=v,g=t,b=p;break;case 1:r=q,g=v,b=p;break;case 2:r=p,g=v,b=t;break;case 3:r=p,g=q,b=v;break;case 4:r=t,g=p,b=v;break;case 5:r=v,g=p,b=q}return values.length>3?[r,g,b,values[3]]:[r,g,b]},exports.hueToColorComponent=hueToColorComponent,exports.hull=hull,exports.hullChain=(...geometries)=>{const hulls=[];if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");1===geometries.length&&hulls.push(geometries[0]);for(let i=1;i{if(0===(geometries=flatten(geometries)).length)throw new Error("intersect wrong number of arguments");if(!areAllShapesTheSameType(geometries))throw new Error("intersect arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return((...geometries)=>{let newGeometry=(geometries=flatten(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,0)})),newGeometry})(geometries);if(isA$3(geometry))return intersectGeom3(geometries);throw new Error("intersect unsupported geometry type")},exports.line=points=>{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},exports.line2=index$1,exports.line3=index,exports.mat4=index$c,exports.measureAggregateArea=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("measureAggregateArea: no geometries supplied");const areas=measureArea(geometries);return 1===geometries.length?areas:areas.reduce(((result,area)=>result+area),0)},exports.measureAggregateBoundingBox=measureAggregateBoundingBox,exports.measureAggregateEpsilon=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("measureAggregateEpsilon: no geometries supplied");const bounds=measureAggregateBoundingBox(geometries);let dimensions=0;return dimensions=geometries.reduce(((dimensions,geometry)=>isA$2(geometry)||isA$5(geometry)?Math.max(dimensions,2):isA$3(geometry)?Math.max(dimensions,3):0),dimensions),calculateEpsilonFromBounds(bounds,dimensions)},exports.measureAggregateVolume=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("measureAggregateVolume: no geometries supplied");const volumes=measureVolume(geometries);return 1===geometries.length?volumes:volumes.reduce(((result,volume)=>result+volume),0)},exports.measureArea=measureArea,exports.measureBoundingBox=measureBoundingBox,exports.measureBoundingSphere=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?measureCached(geometry,measureBoundingSphereOfPath2):isA$5(geometry)?measureCached(geometry,measureBoundingSphereOfGeom2):isA$3(geometry)?measureCached(geometry,measureBoundingSphereOfGeom3):isA(geometry)?measureCached(geometry,measureBoundingSphereOfSlice):[[0,0,0],0]));return 1===results.length?results[0]:results},exports.measureCenter=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>{const bounds=measureBoundingBox(geometry);return[bounds[0][0]+(bounds[1][0]-bounds[0][0])/2,bounds[0][1]+(bounds[1][1]-bounds[0][1])/2,bounds[0][2]+(bounds[1][2]-bounds[0][2])/2]}));return 1===results.length?results[0]:results},exports.measureCenterOfMass=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$5(geometry)?(geometry=>{let centerOfMass=cacheOfCenterOfMass.get(geometry);if(void 0!==centerOfMass)return centerOfMass;const sides=toSides(geometry);let area=0,x=0,y=0;if(sides.length>0){for(let i=0;i{let centerOfMass=cacheOfCenterOfMass.get(geometry);if(void 0!==centerOfMass)return centerOfMass;centerOfMass=[0,0,0];const polygons=toPolygons$1(geometry);if(0===polygons.length)return centerOfMass;let totalVolume=0;const vector=[0,0,0];return polygons.forEach((polygon=>{const vertices=polygon.vertices;for(let i=0;i{const results=(geometries=flatten(geometries)).map((geometry=>{const boundingBox=measureBoundingBox(geometry);return[boundingBox[1][0]-boundingBox[0][0],boundingBox[1][1]-boundingBox[0][1],boundingBox[1][2]-boundingBox[0][2]]}));return 1===results.length?results[0]:results},exports.measureEpsilon=measureEpsilon,exports.measureVolume=measureVolume,exports.mirror=mirror,exports.mirrorX=mirrorX,exports.mirrorY=(...objects)=>mirror({normal:[0,1,0]},objects),exports.mirrorZ=(...objects)=>mirror({normal:[0,0,1]},objects),exports.offset=(options,...objects)=>{if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$2(object)?offsetPath2(options,object):isA$5(object)?((options,geometry)=>{const{delta:delta,corners:corners,segments:segments,expandHoles:expandHoles}=Object.assign({},{delta:1,corners:"edge",segments:16,expandHoles:!1},options);if("edge"!==corners&&"chamfer"!==corners&&"round"!==corners)throw new Error('corners must be "edge", "chamfer", or "round"');if(!Number.isFinite(delta))throw new Error("delta must be a finite number");if("round"===corners&&!Number.isFinite(segments))throw new Error("segments must be a finite number");if("round"===corners&&!(segments>0))throw new Error("segments must be greater than zero");const outlines=toOutlines(geometry),newOutlines=outlines.map((outline=>{let outside=!0;if(expandHoles){const level=outlines.reduce(((acc,polygon)=>acc+arePointsInside(outline,create$3(polygon))),0);outside=level%2==0}return offsetFromPoints(options={delta:outside?delta:-delta,corners:corners,closed:!0,segments:segments},outline)})),output=create$a(newOutlines);return geometry.color&&(output.color=geometry.color),output})(options,object):isA$3(object)?((options,geometry)=>{const{delta:delta,corners:corners,segments:segments}=Object.assign({},{delta:1,corners:"round",segments:12},options);if("round"!==corners)throw new Error('corners must be "round" for 3D geometries');const expanded=offsetShell(options={delta:delta,corners:corners,segments:segments},geometry),output=union(geometry,expanded);return geometry.color&&(output.color=geometry.color),output})(options,object):object));return 1===results.length?results[0]:results},exports.offsetFromPoints=offsetFromPoints,exports.path2=index$5,exports.plane=index$9,exports.poly2=index$3,exports.poly3=index$7,exports.polygon=options=>{const{points:points,paths:paths}=Object.assign({},{points:[],paths:[]},options);if(!Array.isArray(points)||!Array.isArray(paths))throw new Error("points and paths must be arrays");let listOfPolys=points;Array.isArray(points[0])&&(Array.isArray(points[0][0])||(listOfPolys=[points])),listOfPolys.forEach(((list,i)=>{if(!Array.isArray(list))throw new Error("list of points "+i+" must be an array");if(list.length<3)throw new Error("list of points "+i+" must contain three or more points");list.forEach(((point,j)=>{if(!Array.isArray(point))throw new Error("list of points "+i+", point "+j+" must be an array");if(point.length<2)throw new Error("list of points "+i+", point "+j+" must contain by X and Y values")}))}));let listOfPaths=paths;if(0===paths.length){let count=0;listOfPaths=listOfPolys.map((list=>list.map((point=>count++))))}const allPoints=[];listOfPolys.forEach((list=>list.forEach((point=>allPoints.push(point)))));const outlines=[];return listOfPaths.forEach((path=>{const setOfPoints=path.map((index=>allPoints[index]));outlines.push(setOfPoints)})),create$a(outlines)},exports.polyhedron=polyhedron,exports.project=(options,...objects)=>{const{axis:axis,origin:origin}=Object.assign({},{axis:[0,0,1],origin:[0,0,0]},options);if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");options={axis:axis,origin:origin};const results=objects.map((object=>isA$3(object)?((options,geometry)=>{const projPlane=fromNormalAndPoint([0,0,0,0],options.axis,options.origin);if(Number.isNaN(projPlane[0])||Number.isNaN(projPlane[1])||Number.isNaN(projPlane[2])||Number.isNaN(projPlane[3]))throw new Error("project: invalid axis or origin");const epsilon=measureEpsilon(geometry),epsilonArea=epsilon*epsilon*Math.sqrt(3)/4;if(0===epsilon)return create$a();const polygons=toPolygons$1(geometry);let projPolys=[];for(let i=0;iprojectionOfPoint(projPlane,v))),newPoly=create$7(newVertices),newPlane=plane(newPoly);aboutEqualNormals(projPlane,newPlane)&&(measureArea$2(newPoly)transform$7(rotation,p)))}projPolys=projPolys.sort(((a,b)=>measureArea$2(b)-measureArea$2(a)));const projGeoms=projPolys.map((p=>{const cloned=p.vertices.map(clone$8);return create$a([cloned])})),output=unionGeom2(projGeoms);return geometry.color&&(output.color=geometry.color),output})(options,object):object));return 1===results.length?results[0]:results},exports.radToDeg=radians=>57.29577951308232*radians,exports.radiusToSegments=(radius,minimumLength,minimumAngle)=>{const ss=minimumLength>0?radius*TAU/minimumLength:0,as=minimumAngle>0?TAU/minimumAngle:0;return Math.ceil(Math.max(ss,as,4))},exports.rectangle=rectangle,exports.retessellate=retessellate,exports.rgbToHex=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=255*values[0],g=255*values[1],b=255*values[2];let s=`#${Number(16777216+65536*r+256*g+b).toString(16).substring(1,7)}`;return values.length>3&&(s+=Number(255*values[3]).toString(16)),s},exports.rgbToHsl=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=values[0],g=values[1],b=values[2],max=Math.max(r,g,b),min=Math.min(r,g,b);let h,s;const l=(max+min)/2;if(max===min)h=s=0;else{const d=max-min;switch(s=l>.5?d/(2-max-min):d/(max+min),max){case r:h=(g-b)/d+(g3?[h,s,l,values[3]]:[h,s,l]},exports.rgbToHsv=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=values[0],g=values[1],b=values[2],max=Math.max(r,g,b),min=Math.min(r,g,b);let h;const v=max,d=max-min,s=0===max?0:d/max;if(max===min)h=0;else{switch(max){case r:h=(g-b)/d+(g3?[h,s,v,values[3]]:[h,s,v]},exports.rotate=rotate,exports.rotateX=(angle,...objects)=>rotate([angle,0,0],objects),exports.rotateY=(angle,...objects)=>rotate([0,angle,0],objects),exports.rotateZ=(angle,...objects)=>rotate([0,0,angle],objects),exports.roundedCuboid=options=>{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0,0],size:[2,2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of X, Y and Z values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1]||0===size[2])return create$8();if(0===roundRadius)return cuboid({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS||roundRadius>size[2]-EPS)throw new Error("roundRadius must be smaller then the radius of all dimensions");segments=Math.floor(segments/4);let prevCornersPos=null,prevCornersNeg=null,polygons=[];for(let slice=0;slice<=segments;slice++){const cornersPos=createCorners(center,size,roundRadius,segments,slice,!0),cornersNeg=createCorners(center,size,roundRadius,segments,slice,!1);if(0===slice&&(polygons=polygons.concat(stitchSides(cornersNeg,cornersPos))),prevCornersPos&&(polygons=polygons.concat(stitchCorners(prevCornersPos,cornersPos),stitchWalls(prevCornersPos,cornersPos))),prevCornersNeg&&(polygons=polygons.concat(stitchCorners(prevCornersNeg,cornersNeg),stitchWalls(prevCornersNeg,cornersNeg))),slice===segments){let vertices=cornersPos.map((corner=>corner[0]));polygons.push(create$7(vertices)),vertices=cornersNeg.map((corner=>corner[0])),polygons.push(create$7(vertices))}prevCornersPos=cornersPos,prevCornersNeg=cornersNeg}return create$8(polygons)},exports.roundedCylinder=options=>{const{center:center,height:height,radius:radius,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,roundRadius:.2,segments:32},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGTE(height,0))throw new Error("height must be positive");if(!isGTE(radius,0))throw new Error("radius must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(roundRadius>radius)throw new Error("roundRadius must be smaller then the radius");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===height||0===radius)return create$8();if(0===roundRadius)return cylinder({center:center,height:height,radius:radius});const start=[0,0,-height/2],end=[0,0,height/2],direction=subtract$3([0,0,0],end,start);if(2*roundRadius>length$2(direction)-EPS)throw new Error("height must be larger than twice roundRadius");let defaultNormal;defaultNormal=Math.abs(direction[0])>Math.abs(direction[1])?fromValues$3(0,1,0):fromValues$3(1,0,0);const zVector=scale$3([0,0,0],normalize$1([0,0,0],direction),roundRadius),xVector=scale$3([0,0,0],normalize$1([0,0,0],cross$1([0,0,0],zVector,defaultNormal)),radius),yVector=scale$3([0,0,0],normalize$1([0,0,0],cross$1([0,0,0],xVector,zVector)),radius);add$1(start,start,zVector),subtract$3(end,end,zVector);const qSegments=Math.floor(.25*segments),fromVertices=vertices=>{const newVertices=vertices.map((vertex=>add$1(vertex,vertex,center)));return create$7(newVertices)},polygons=[],v1=[0,0,0],v2=[0,0,0];let prevCylinderVertex;for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(v1,xVector,cos(angle)),scale$3(v2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch,vertex,vertices=[];vertices.push(add$1([0,0,0],start,cylinderVertex)),vertices.push(add$1([0,0,0],start,prevCylinderVertex)),vertices.push(add$1([0,0,0],end,prevCylinderVertex)),vertices.push(add$1([0,0,0],end,cylinderVertex)),polygons.push(fromVertices(vertices));for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);slice2>0&&(vertices=[],vertex=add$1([0,0,0],start,subtract$3(v1,scale$3(v1,prevCylinderVertex,prevCosPitch),scale$3(v2,zVector,prevSinPitch))),vertices.push(vertex),vertex=add$1([0,0,0],start,subtract$3(v1,scale$3(v1,cylinderVertex,prevCosPitch),scale$3(v2,zVector,prevSinPitch))),vertices.push(vertex),slice2{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1])return create$a();if(0===roundRadius)return rectangle({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS)throw new Error("roundRadius must be smaller then the radius of all dimensions");const cornerSegments=Math.floor(segments/4),corner0=add([0,0],center,[size[0]-roundRadius,size[1]-roundRadius]),corner1=add([0,0],center,[roundRadius-size[0],size[1]-roundRadius]),corner2=add([0,0],center,[roundRadius-size[0],roundRadius-size[1]]),corner3=add([0,0],center,[size[0]-roundRadius,roundRadius-size[1]]),corner0Points=[],corner1Points=[],corner2Points=[],corner3Points=[];for(let i=0;i<=cornerSegments;i++){const point=fromAngleRadians([0,0],TAU/4*i/cornerSegments);scale$1(point,point,roundRadius),corner0Points.push(add([0,0],corner0,point)),rotate$1(point,point,[0,0],TAU/4),corner1Points.push(add([0,0],corner1,point)),rotate$1(point,point,[0,0],TAU/4),corner2Points.push(add([0,0],corner2,point)),rotate$1(point,point,[0,0],TAU/4),corner3Points.push(add([0,0],corner3,point))}const points=corner0Points.concat(corner1Points,corner2Points,corner3Points);return create$a([points])},exports.scale=scale,exports.scaleX=(factor,...objects)=>scale([factor,1,1],objects),exports.scaleY=(factor,...objects)=>scale([1,factor,1],objects),exports.scaleZ=(factor,...objects)=>scale([1,1,factor],objects),exports.scission=(...objects)=>{if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$3(object)?(geometry=>{const eps=measureEpsilon(geometry),polygons=toPolygons$1(geometry),pl=polygons.length,indexesPerVertex=new Map,temp=[0,0,0];polygons.forEach(((polygon,index)=>{polygon.vertices.forEach((vertex=>{((map,vertex,index)=>{const key=`${vertex}`,mapping=map.get(key);void 0===mapping?map.set(key,[index]):mapping.push(index)})(indexesPerVertex,snap$2(temp,vertex,eps),index)}))}));const indexesPerPolygon=polygons.map((polygon=>{let indexes=[];return polygon.vertices.forEach((vertex=>{indexes=indexes.concat(((map,vertex)=>{const key=`${vertex}`;return map.get(key)})(indexesPerVertex,snap$2(temp,vertex,eps)))})),{e:1,d:(array=indexes,array.sort(((a,b)=>a-b)).filter(((item,pos,ary)=>!pos||item!==ary[pos-1])))};var array}));indexesPerVertex.clear();let merges=0;const ippl=indexesPerPolygon.length;for(let i=0;i0){const indexes=new Array(pl);indexes[i]=!0;do{merges=0,indexes.forEach(((e,j)=>{const mapj=indexesPerPolygon[j];if(mapj.e>0){mapj.e=-1;for(let d=0;d0);mapi.indexes=indexes}}const newgeometries=[];for(let i=0;inewpolygons.push(polygons[p]))),newgeometries.push(create$8(newpolygons))}return newgeometries})(object):object));return 1===results.length?results[0]:results},exports.sin=sin,exports.slice=index$2,exports.snap=(...geometries)=>{if(0===(geometries=flatten(geometries)).length)throw new Error("wrong number of arguments");const results=geometries.map((geometry=>isA$2(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry),newPoints=toPoints$1(geometry).map((point=>snap$1([0,0],point,epsilon)));return create$5(newPoints)})(geometry):isA$5(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry);let newOutlines=toOutlines(geometry).map((outline=>{let prev=snap$1([0,0],outline[outline.length-1],epsilon);const newOutline=[];return outline.forEach((point=>{const snapped=snap$1([0,0],point,epsilon);equals$6(prev,snapped)||newOutline.push(snapped),prev=snapped})),newOutline}));return newOutlines=newOutlines.filter((outline=>measureArea$1(create$3(outline)))),create$a(newOutlines)})(geometry):isA$3(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry),polygons=toPolygons$1(geometry),newPolygons=snapPolygons(epsilon,polygons);return create$8(newPolygons)})(geometry):geometry));return 1===results.length?results[0]:results},exports.sphere=sphere,exports.square=options=>{let{center:center,size:size}=Object.assign({},{center:[0,0],size:2},options);if(!isGTE(size,0))throw new Error("size must be positive");return size=[size,size],rectangle({center:center,size:size})},exports.star=options=>{let{center:center,vertices:vertices,outerRadius:outerRadius,innerRadius:innerRadius,density:density,startAngle:startAngle}=Object.assign({},{center:[0,0],vertices:5,outerRadius:1,innerRadius:0,density:2,startAngle:0},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGTE(vertices,2))throw new Error("vertices must be two or more");if(!isGT(outerRadius,0))throw new Error("outerRadius must be greater than zero");if(!isGTE(innerRadius,0))throw new Error("innerRadius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be greater than zero");if(vertices=Math.floor(vertices),density=Math.floor(density),startAngle%=TAU,0===innerRadius){if(!isGTE(density,2))throw new Error("density must be two or more");innerRadius=outerRadius*((vertices,density)=>vertices>0&&density>1&&density{if(0===(geometries=flatten(geometries)).length)throw new Error("subtract wrong number of arguments");if(!areAllShapesTheSameType(geometries))throw new Error("subtract arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return((...geometries)=>{let newGeometry=(geometries=flatten(geometries)).shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,2)})),newGeometry})(geometries);if(isA$3(geometry))return subtractGeom3(geometries);throw new Error("subtract unsupported geometry type")},exports.torus=options=>{const defaults={innerRadius:1,innerSegments:32,outerRadius:4,outerSegments:32,innerRotation:0,startAngle:0,outerRotation:TAU},{innerRadius:innerRadius,innerSegments:innerSegments,outerRadius:outerRadius,outerSegments:outerSegments,innerRotation:innerRotation,startAngle:startAngle,outerRotation:outerRotation}=Object.assign({},defaults,options);if(!isGT(innerRadius,0))throw new Error("innerRadius must be greater than zero");if(!isGTE(innerSegments,3))throw new Error("innerSegments must be three or more");if(!isGT(outerRadius,0))throw new Error("outerRadius must be greater than zero");if(!isGTE(outerSegments,3))throw new Error("outerSegments must be three or more");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGT(outerRotation,0))throw new Error("outerRotation must be greater than zero");if(innerRadius>=outerRadius)throw new Error("inner circle is two large to rotate about the outer circle");let innerCircle=circle({radius:innerRadius,segments:innerSegments});return 0!==innerRotation&&(innerCircle=rotate([0,0,innerRotation],innerCircle)),innerCircle=translate([outerRadius,0],innerCircle),extrudeRotate({startAngle:startAngle,angle:outerRotation,segments:outerSegments},innerCircle)},exports.transform=(matrix,...objects)=>{if(0===(objects=flatten(objects)).length)throw new Error("wrong number of arguments");const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):object));return 1===results.length?results[0]:results},exports.translate=translate,exports.translateX=(offset,...objects)=>translate([offset,0,0],objects),exports.translateY=(offset,...objects)=>translate([0,offset,0],objects),exports.translateZ=(offset,...objects)=>translate([0,0,offset],objects),exports.triangle=options=>{let{type:type,values:values}=Object.assign({},{type:"SSS",values:[1,1,1]},options);if("string"!=typeof type)throw new Error("triangle type must be a string");if(type=type.toUpperCase(),"A"!==type[0]&&"S"!==type[0]||"A"!==type[1]&&"S"!==type[1]||"A"!==type[2]&&"S"!==type[2])throw new Error("triangle type must contain three letters; A or S");if(!isNumberArray(values,3))throw new Error("triangle values must contain three values");if(!values.every((n=>n>0)))throw new Error("triangle values must be greater than zero");switch(type){case"AAA":return(angles=>{if(Math.abs(angles[0]+angles[1]+angles[2]-Math.PI)>NEPS)throw new Error("AAA triangles require angles that sum to PI");const A=angles[0],B=angles[1],C=Math.PI-A-B,a=1/Math.sin(C)*Math.sin(A),b=1/Math.sin(C)*Math.sin(B);return createTriangle(A,B,C,a,b,1)})(values);case"AAS":return(values=>{const A=values[0],B=values[1],C=Math.PI+NEPS-A-B;if(C{const A=values[0],B=values[2],C=Math.PI+NEPS-A-B;if(C{const c=values[0],a=values[1],C=values[2],A=Math.asin(a*Math.sin(C)/c),B=Math.PI-A-C,b=c/Math.sin(C)*Math.sin(B);return createTriangle(A,B,C,a,b,c)})(values);case"SSS":return(lengths=>{const a=lengths[1],b=lengths[2],c=lengths[0];if(a+b<=c||b+c<=a||c+a<=b)throw new Error("SSS triangle is incorrect, as the longest side is longer than the sum of the other sides");const A=solveAngleFromSSS(b,c,a),B=solveAngleFromSSS(c,a,b),C=Math.PI-A-B;return createTriangle(A,B,C,a,b,c)})(values);default:throw new Error("invalid triangle type, try again")}},exports.union=union,exports.vec2=index$b,exports.vec3=index$d,exports.vec4=index$8,exports.vectorChar=vectorChar,exports.vectorText=(options,text)=>{const{xOffset:xOffset,yOffset:yOffset,font:font,height:height,align:align,extrudeOffset:extrudeOffset,lineSpacing:lineSpacing,letterSpacing:letterSpacing}=Object.assign({},defaultsVectorParams,options);if("string"!=typeof text)throw new Error("text must be a string");const extraLetterSpacing=height*letterSpacing;let maxWidth=0,line={width:0,height:0,chars:[]},lines=[];const pushLine=()=>{maxWidth=Math.max(maxWidth,line.width),line.chars.length&&lines.push(line),line={width:0,height:0,chars:[]}};let vchar,x=xOffset,y=yOffset;const il=text.length;for(let i=0;i{const diff=maxWidth-line.width;return"right"===align?translateLine({x:diff},line):"center"===align?translateLine({x:diff/2},line):line})),lines},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadModeling={}); +var global,factory;global=this,factory=function(exports){const cssColors={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]},clone$b=geometry=>Object.assign({},geometry),create$c=()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],clone$a=matrix=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},copy$5=(out,matrix)=>(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out),EPS=1e-5,NEPS=1e-13,TAU=2*Math.PI,rezero=n=>Math.abs(n)rezero(Math.sin(radians)),cos=radians=>rezero(Math.cos(radians)),identity=out=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromRotation=(out,rad,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared)(out[0]=vector[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=vector[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=vector[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out),fromTaitBryanRotation=(out,yaw,pitch,roll)=>{const sy=sin(yaw),cy=cos(yaw),sp=sin(pitch),cp=cos(pitch),sr=sin(roll),cr=cos(roll);return out[0]=cp*cy,out[1]=cp*sy,out[2]=-sp,out[3]=0,out[4]=sr*sp*cy-cr*sy,out[5]=cr*cy+sr*sp*sy,out[6]=sr*cp,out[7]=0,out[8]=sr*sy+cr*sp*cy,out[9]=cr*sp*sy-sr*cy,out[10]=cr*cp,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation=(out,vector)=>(out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=vector[0],out[13]=vector[1],out[14]=vector[2],out[15]=1,out),fromValues$4=(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33)=>{const out=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return out[0]=m00,out[1]=m01,out[2]=m02,out[3]=m03,out[4]=m10,out[5]=m11,out[6]=m12,out[7]=m13,out[8]=m20,out[9]=m21,out[10]=m22,out[11]=m23,out[12]=m30,out[13]=m31,out[14]=m32,out[15]=m33,out},abs$1=(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out[2]=Math.abs(vector[2]),out),add$1=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out),dot$2=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],create$b=()=>[0,0,0],clone$9=vector=>{const out=[0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out},copy$4=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out),cross$1=(out,a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out},distance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)},divide$1=(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out),equals$7=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2],fromScalar$2=(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out),fromValues$3=(x,y,z)=>{const out=[0,0,0];return out[0]=x,out[1]=y,out[2]=z,out},fromVec2=(out,vector,z=0)=>(out[0]=vector[0],out[1]=vector[1],out[2]=z,out),length$2=vector=>{const x=vector[0],y=vector[1],z=vector[2];return Math.sqrt(x*x+y*y+z*z)},max$2=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out),min$2=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out),multiply$2=(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out),negate$1=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out[2]=-vector[2],out),normalize$1=(out,vector)=>{const x=vector[0],y=vector[1],z=vector[2];let len=x*x+y*y+z*z;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out[2]=z*len,out},orthogonal=(out,vector)=>{const bV=abs$1([0,0,0],vector),b0=0+(bV[0]{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],r[0]=p[0]*Math.cos(radians)-p[1]*Math.sin(radians),r[1]=p[0]*Math.sin(radians)+p[1]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=vector[2],out},scale$3=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out[2]=vector[2]*amount,out),snap$2=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out[2]=Math.round(vector[2]/epsilon)*epsilon+0,out),squaredDistance$1=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z},squaredLength$1=vector=>{const x=vector[0],y=vector[1],z=vector[2];return x*x+y*y+z*z},subtract$3=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out),toString$b=vec=>`[${vec[0].toFixed(7)}, ${vec[1].toFixed(7)}, ${vec[2].toFixed(7)}]`,transform$c=(out,vector,matrix)=>{const x=vector[0],y=vector[1],z=vector[2];let w=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15];return w=w||1,out[0]=(matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12])/w,out[1]=(matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13])/w,out[2]=(matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14])/w,out};var index$d=Object.freeze({__proto__:null,abs:abs$1,add:add$1,angle:(a,b)=>{const ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt(ax*ax+ay*ay+az*az)*Math.sqrt(bx*bx+by*by+bz*bz),cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))},clone:clone$9,copy:copy$4,create:create$b,cross:cross$1,distance:distance$1,divide:divide$1,dot:dot$2,equals:equals$7,fromScalar:fromScalar$2,fromValues:fromValues$3,fromVec2:fromVec2,length:length$2,lerp:(out,a,b,t)=>(out[0]=a[0]+t*(b[0]-a[0]),out[1]=a[1]+t*(b[1]-a[1]),out[2]=a[2]+t*(b[2]-a[2]),out),max:max$2,min:min$2,multiply:multiply$2,negate:negate$1,normalize:normalize$1,orthogonal:orthogonal,rotateX:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[0],r[1]=p[1]*Math.cos(radians)-p[2]*Math.sin(radians),r[2]=p[1]*Math.sin(radians)+p[2]*Math.cos(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateY:(out,vector,origin,radians)=>{const p=[],r=[];return p[0]=vector[0]-origin[0],p[1]=vector[1]-origin[1],p[2]=vector[2]-origin[2],r[0]=p[2]*Math.sin(radians)+p[0]*Math.cos(radians),r[1]=p[1],r[2]=p[2]*Math.cos(radians)-p[0]*Math.sin(radians),out[0]=r[0]+origin[0],out[1]=r[1]+origin[1],out[2]=r[2]+origin[2],out},rotateZ:rotateZ$2,scale:scale$3,snap:snap$2,squaredDistance:squaredDistance$1,squaredLength:squaredLength$1,subtract:subtract$3,toString:toString$b,transform:transform$c});const fromVectorRotation=(out,source,target)=>{const sourceNormal=normalize$1([0,0,0],source),targetNormal=normalize$1([0,0,0],target),axis=cross$1([0,0,0],targetNormal,sourceNormal),cosA=dot$2(targetNormal,sourceNormal);if(-1===cosA)return fromRotation(out,Math.PI,orthogonal(axis,sourceNormal));const k=1/(1+cosA);return out[0]=axis[0]*axis[0]*k+cosA,out[1]=axis[1]*axis[0]*k-axis[2],out[2]=axis[2]*axis[0]*k+axis[1],out[3]=0,out[4]=axis[0]*axis[1]*k+axis[2],out[5]=axis[1]*axis[1]*k+cosA,out[6]=axis[2]*axis[1]*k-axis[0],out[7]=0,out[8]=axis[0]*axis[2]*k-axis[1],out[9]=axis[1]*axis[2]*k+axis[0],out[10]=axis[2]*axis[2]*k+cosA,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromXRotation=(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation=(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},isIdentity=matrix=>1===matrix[0]&&0===matrix[1]&&0===matrix[2]&&0===matrix[3]&&0===matrix[4]&&1===matrix[5]&&0===matrix[6]&&0===matrix[7]&&0===matrix[8]&&0===matrix[9]&&1===matrix[10]&&0===matrix[11]&&0===matrix[12]&&0===matrix[13]&&0===matrix[14]&&1===matrix[15],isMirroring=matrix=>{const x=matrix[4]*matrix[9]-matrix[8]*matrix[5],y=matrix[8]*matrix[1]-matrix[0]*matrix[9],z=matrix[0]*matrix[5]-matrix[4]*matrix[1];return x*matrix[2]+y*matrix[6]+z*matrix[10]<0},isZero=num=>Math.abs(num){const[nx,ny,nz,w]=plane;return out[0]=1-2*nx*nx,out[1]=-2*ny*nx,out[2]=-2*nz*nx,out[3]=0,out[4]=-2*nx*ny,out[5]=1-2*ny*ny,out[6]=-2*nz*ny,out[7]=0,out[8]=-2*nx*nz,out[9]=-2*ny*nz,out[10]=1-2*nz*nz,out[11]=0,out[12]=2*nx*w,out[13]=2*ny*w,out[14]=2*nz*w,out[15]=1,out},multiply$1=(out,a,b)=>{const a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];let b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out},translate$1=(out,matrix,offsets)=>{const x=offsets[0],y=offsets[1],z=offsets[2];let a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23;return matrix===out?(out[12]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12],out[13]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13],out[14]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14],out[15]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]):(a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+matrix[12],out[13]=a01*x+a11*y+a21*z+matrix[13],out[14]=a02*x+a12*y+a22*z+matrix[14],out[15]=a03*x+a13*y+a23*z+matrix[15]),out};var index$c=Object.freeze({__proto__:null,add:(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out[3]=a[3]+b[3],out[4]=a[4]+b[4],out[5]=a[5]+b[5],out[6]=a[6]+b[6],out[7]=a[7]+b[7],out[8]=a[8]+b[8],out[9]=a[9]+b[9],out[10]=a[10]+b[10],out[11]=a[11]+b[11],out[12]=a[12]+b[12],out[13]=a[13]+b[13],out[14]=a[14]+b[14],out[15]=a[15]+b[15],out),clone:clone$a,copy:copy$5,create:create$c,equals:(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15],fromRotation:fromRotation,fromScaling:fromScaling,fromTaitBryanRotation:fromTaitBryanRotation,fromTranslation:fromTranslation,fromValues:fromValues$4,fromVectorRotation:fromVectorRotation,fromXRotation:fromXRotation,fromYRotation:(out,radians)=>{const s=sin(radians),c=cos(radians);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:fromZRotation,identity:identity,invert:(out,matrix)=>{const a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11],a30=matrix[12],a31=matrix[13],a32=matrix[14],a33=matrix[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32;let det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;return det?(det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out):null},isIdentity:isIdentity,isMirroring:isMirroring,isOnlyTransformScale:matrix=>isZero(matrix[1])&&isZero(matrix[2])&&isZero(matrix[3])&&isZero(matrix[4])&&isZero(matrix[6])&&isZero(matrix[7])&&isZero(matrix[8])&&isZero(matrix[9])&&isZero(matrix[11])&&1===matrix[15],mirrorByPlane:mirrorByPlane,multiply:multiply$1,rotate:(out,matrix,radians,axis)=>{let[x,y,z]=axis;const lengthSquared=x*x+y*y+z*z;if(Math.abs(lengthSquared){const s=sin(radians),c=cos(radians),a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[0]=matrix[0],out[1]=matrix[1],out[2]=matrix[2],out[3]=matrix[3],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a20=matrix[8],a21=matrix[9],a22=matrix[10],a23=matrix[11];return matrix!==out&&(out[4]=matrix[4],out[5]=matrix[5],out[6]=matrix[6],out[7]=matrix[7],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:(out,matrix,radians)=>{const s=sin(radians),c=cos(radians),a00=matrix[0],a01=matrix[1],a02=matrix[2],a03=matrix[3],a10=matrix[4],a11=matrix[5],a12=matrix[6],a13=matrix[7];return matrix!==out&&(out[8]=matrix[8],out[9]=matrix[9],out[10]=matrix[10],out[11]=matrix[11],out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15]),out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},scale:(out,matrix,dimensions)=>{const x=dimensions[0],y=dimensions[1],z=dimensions[2];return out[0]=matrix[0]*x,out[1]=matrix[1]*x,out[2]=matrix[2]*x,out[3]=matrix[3]*x,out[4]=matrix[4]*y,out[5]=matrix[5]*y,out[6]=matrix[6]*y,out[7]=matrix[7]*y,out[8]=matrix[8]*z,out[9]=matrix[9]*z,out[10]=matrix[10]*z,out[11]=matrix[11]*z,out[12]=matrix[12],out[13]=matrix[13],out[14]=matrix[14],out[15]=matrix[15],out},subtract:(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out[3]=a[3]-b[3],out[4]=a[4]-b[4],out[5]=a[5]-b[5],out[6]=a[6]-b[6],out[7]=a[7]-b[7],out[8]=a[8]-b[8],out[9]=a[9]-b[9],out[10]=a[10]-b[10],out[11]=a[11]-b[11],out[12]=a[12]-b[12],out[13]=a[13]-b[13],out[14]=a[14]-b[14],out[15]=a[15]-b[15],out),toString:mat=>mat.map((n=>n.toFixed(7))).toString(),translate:translate$1});const create$a=(outlines=[])=>({outlines:outlines,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),add=(out,a,b)=>(out[0]=a[0]+b[0],out[1]=a[1]+b[1],out),angleRadians=vector=>Math.atan2(vector[1],vector[0]),angleDegrees=vector=>57.29577951308232*angleRadians(vector),create$9=()=>[0,0],clone$8=vector=>{const out=[0,0];return out[0]=vector[0],out[1]=vector[1],out},cross=(out,a,b)=>(out[0]=0,out[1]=0,out[2]=a[0]*b[1]-a[1]*b[0],out),distance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return Math.sqrt(x*x+y*y)},dot$1=(a,b)=>a[0]*b[0]+a[1]*b[1],equals$6=(a,b)=>a[0]===b[0]&&a[1]===b[1],fromAngleRadians=(out,radians)=>(out[0]=cos(radians),out[1]=sin(radians),out),fromValues$2=(x,y)=>{const out=[0,0];return out[0]=x,out[1]=y,out},max$1=(out,a,b)=>(out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out),min$1=(out,a,b)=>(out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out),negate=(out,vector)=>(out[0]=-vector[0],out[1]=-vector[1],out),rotate$1=(out,vector,origin,radians)=>{const x=vector[0]-origin[0],y=vector[1]-origin[1],c=Math.cos(radians),s=Math.sin(radians);return out[0]=x*c-y*s+origin[0],out[1]=x*s+y*c+origin[1],out},normal=(out,vector)=>rotate$1(out,vector,[0,0],TAU/4),normalize=(out,vector)=>{const x=vector[0],y=vector[1];let len=x*x+y*y;return len>0&&(len=1/Math.sqrt(len)),out[0]=x*len,out[1]=y*len,out},scale$1=(out,vector,amount)=>(out[0]=vector[0]*amount,out[1]=vector[1]*amount,out),snap$1=(out,vector,epsilon)=>(out[0]=Math.round(vector[0]/epsilon)*epsilon+0,out[1]=Math.round(vector[1]/epsilon)*epsilon+0,out),squaredDistance=(a,b)=>{const x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y},subtract$1=(out,a,b)=>(out[0]=a[0]-b[0],out[1]=a[1]-b[1],out),toString$9=vector=>`[${vector[0].toFixed(7)}, ${vector[1].toFixed(7)}]`,transform$b=(out,vector,matrix)=>{const x=vector[0],y=vector[1];return out[0]=matrix[0]*x+matrix[4]*y+matrix[12],out[1]=matrix[1]*x+matrix[5]*y+matrix[13],out};var index$b=Object.freeze({__proto__:null,abs:(out,vector)=>(out[0]=Math.abs(vector[0]),out[1]=Math.abs(vector[1]),out),add:add,angle:angleRadians,angleDegrees:angleDegrees,angleRadians:angleRadians,clone:clone$8,copy:(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out),create:create$9,cross:cross,distance:distance,divide:(out,a,b)=>(out[0]=a[0]/b[0],out[1]=a[1]/b[1],out),dot:dot$1,equals:equals$6,fromAngleDegrees:(out,degrees)=>fromAngleRadians(out,.017453292519943295*degrees),fromAngleRadians:fromAngleRadians,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out),fromValues:fromValues$2,length:vector=>Math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]),lerp:(out,a,b,t)=>{const ax=a[0],ay=a[1];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out},max:max$1,min:min$1,multiply:(out,a,b)=>(out[0]=a[0]*b[0],out[1]=a[1]*b[1],out),negate:negate,normal:normal,normalize:normalize,rotate:rotate$1,scale:scale$1,snap:snap$1,squaredDistance:squaredDistance,squaredLength:vector=>{const x=vector[0],y=vector[1];return x*x+y*y},subtract:subtract$1,toString:toString$9,transform:transform$b});const toPointMap=sides=>{const pointMap=new Map,edges=(sides=>{const unique=new Map,getUniquePoint=point=>{const key=point.toString();return unique.has(key)?unique.get(key):(unique.set(key,point),point)};return sides.map((side=>side.map(getUniquePoint)))})(sides);return edges.forEach((edge=>{pointMap.has(edge[0])?pointMap.get(edge[0]).push(edge):pointMap.set(edge[0],[edge])})),pointMap},fromSides=sides=>{const pointMap=toPointMap(sides),outlines=[];for(;;){let startSide;for(const[point,edges]of pointMap){if(startSide=edges.shift(),startSide)break;pointMap.delete(point)}if(void 0===startSide)break;const connectedPoints=[],startPoint=startSide[0];for(;;){connectedPoints.push(startSide[0]);const nextPoint=startSide[1];if(nextPoint===startPoint)break;const nextPossibleSides=pointMap.get(nextPoint);if(!nextPossibleSides)throw new Error(`geometry is not closed at point ${nextPoint}`);const nextSide=popNextSide(startSide,nextPossibleSides);0===nextPossibleSides.length&&pointMap.delete(nextPoint),startSide=nextSide}connectedPoints.length>0&&connectedPoints.push(connectedPoints.shift()),outlines.push(connectedPoints)}return pointMap.clear(),create$a(outlines)},popNextSide=(startSide,nextSides)=>{if(1===nextSides.length)return nextSides.pop();const v0=[0,0],startAngle=angleDegrees(subtract$1(v0,startSide[1],startSide[0]));let bestAngle,bestIndex;nextSides.forEach(((nextSide,index)=>{let angle=angleDegrees(subtract$1(v0,nextSide[1],nextSide[0]))-startAngle;angle<-180&&(angle+=360),angle>=180&&(angle-=360),(void 0===bestIndex||angle>bestAngle)&&(bestIndex=index,bestAngle=angle)}));const nextSide=nextSides[bestIndex];return nextSides.splice(bestIndex,1),nextSide},isA$5=object=>!!(object&&"object"==typeof object&&"outlines"in object&&"transforms"in object&&Array.isArray(object.outlines)&&"length"in object.transforms),toOutlines=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.outlines=geometry.outlines.map((outline=>outline.map((point=>transform$b([0,0],point,geometry.transforms))))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).outlines,reverse$5=geometry=>{const outlines=toOutlines(geometry).map((outline=>outline.slice().reverse())),reversed=create$a(outlines);return geometry.color&&(reversed.color=geometry.color),reversed},toPoints$3=geometry=>{const points=[];return toOutlines(geometry).forEach((outline=>{outline.forEach((point=>{points.push(point)}))})),points},toSides=geometry=>{const sides=[];return toOutlines(geometry).forEach((outline=>{outline.forEach(((point,i)=>{const j=(i+1)%outline.length;sides.push([point,outline[j]])}))})),sides},transform$a=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms),transformed=Object.assign({},geometry,{transforms:transforms});return matrix[0]*matrix[5]-matrix[4]*matrix[1]<0?reverse$5(transformed):transformed},intersect$1=(p1,p2,p3,p4,endpointTouch=!0)=>{if(p1[0]===p2[0]&&p1[1]===p2[1]||p3[0]===p4[0]&&p3[1]===p4[1])return;const denominator=(p4[1]-p3[1])*(p2[0]-p1[0])-(p4[0]-p3[0])*(p2[1]-p1[1]);if(Math.abs(denominator)1||ub<0||ub>1||!(endpointTouch||0!==ua&&1!==ua&&0!==ub&&1!==ub)?void 0:[p1[0]+ua*(p2[0]-p1[0]),p1[1]+ua*(p2[1]-p1[1])]};var index$a=Object.freeze({__proto__:null,clone:clone$b,create:create$a,fromSides:fromSides,fromCompactBinary:data=>{if(0!==data[0])throw new Error("invalid compact binary data");const created=create$a();created.transforms=clone$a(data.slice(1,17));for(let i=21;idata.length)throw new Error("invalid compact binary data");const outline=[];for(let j=0;j=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},isA:isA$5,reverse:reverse$5,toOutlines:toOutlines,toPoints:toPoints$3,toSides:toSides,toString:geometry=>{const outlines=toOutlines(geometry);let result="geom2 ("+outlines.length+" outlines):\n[\n";return outlines.forEach((outline=>{result+=" ["+outline.map(toString$9).join()+"]\n"})),result+="]\n",result},toCompactBinary:geometry=>{const transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);let size=21;geometry.outlines.forEach((outline=>{size+=2*outline.length+1}));const compacted=new Float32Array(size);compacted[0]=0,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3];let index=21;return geometry.outlines.forEach((outline=>{compacted[index++]=outline.length,outline.forEach((point=>{compacted[index++]=point[0],compacted[index++]=point[1]}))})),compacted},transform:transform$a,validate:object=>{if(!isA$5(object))throw new Error("invalid geom2 structure");if(object.outlines.forEach(((outline,i)=>{if(outline.length<3)throw new Error(`geom2 outline ${i} must contain at least 3 points`);for(let i=0;i{for(let a1=0;a1Object.assign({},geometry),create$8=polygons=>(void 0===polygons&&(polygons=[]),{polygons:polygons,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),create$7=vertices=>((void 0===vertices||vertices.length<3)&&(vertices=[]),{vertices:vertices}),clone$6=(...params)=>{let out,poly3;return 1===params.length?(out=create$7(),poly3=params[0]):(out=params[0],poly3=params[1]),out.vertices=poly3.vertices.map((vec=>clone$9(vec))),out},fromVerticesAndPlane=(vertices,plane)=>{const poly=create$7(vertices);return poly.plane=plane,poly},create$6=()=>[0,0,0,0],clone$5=vector=>{const out=[0,0,0,0];return out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out},copy$2=(out,vector)=>(out[0]=vector[0],out[1]=vector[1],out[2]=vector[2],out[3]=vector[3],out),equals$5=(a,b)=>a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3],flip=(out,plane)=>(out[0]=-plane[0],out[1]=-plane[1],out[2]=-plane[2],out[3]=-plane[3],out),fromNormalAndPoint=(out,normal,point)=>{const u=normalize$1([0,0,0],normal),w=dot$2(point,u);return out[0]=u[0],out[1]=u[1],out[2]=u[2],out[3]=w,out},fromValues$1=(x,y,z,w)=>{const out=[0,0,0,0];return out[0]=x,out[1]=y,out[2]=z,out[3]=w,out},fromPoints$4=(out,...vertices)=>{const len=vertices.length,ba=[0,0,0],ca=[0,0,0],vertexNormal=index=>{const a=vertices[index],b=vertices[(index+1)%len],c=vertices[(index+2)%len];return subtract$3(ba,b,a),subtract$3(ca,c,a),cross$1(ba,ba,ca),normalize$1(ba,ba),ba};return out[0]=0,out[1]=0,out[2]=0,3===len?copy$4(out,vertexNormal(0)):(vertices.forEach(((v,i)=>{add$1(out,out,vertexNormal(i))})),normalize$1(out,out)),out[3]=dot$2(out,vertices[0]),out},projectionOfPoint=(plane,point)=>{const a=point[0]*plane[0]+point[1]*plane[1]+point[2]*plane[2]-plane[3],x=point[0]-a*plane[0],y=point[1]-a*plane[1],z=point[2]-a*plane[2];return fromValues$3(x,y,z)},signedDistanceToPoint=(plane,point)=>dot$2(plane,point)-plane[3],toString$7=vec=>`(${vec[0].toFixed(9)}, ${vec[1].toFixed(9)}, ${vec[2].toFixed(9)}, ${vec[3].toFixed(9)})`;var index$9=Object.freeze({__proto__:null,clone:clone$5,copy:copy$2,create:create$6,equals:equals$5,flip:flip,fromNormalAndPoint:fromNormalAndPoint,fromValues:fromValues$1,fromPoints:fromPoints$4,fromPointsRandom:(out,a,b,c)=>{let ba=subtract$3([0,0,0],b,a),ca=subtract$3([0,0,0],c,a);length$2(ba){const isMirror=isMirroring(matrix),r=orthogonal([0,0,0],plane),u=cross$1(r,plane,r),v=cross$1([0,0,0],plane,u);let point1=fromScalar$2([0,0,0],plane[3]);multiply$2(point1,point1,plane);let point2=add$1([0,0,0],point1,u),point3=add$1([0,0,0],point1,v);return point1=transform$c(point1,point1,matrix),point2=transform$c(point2,point2,matrix),point3=transform$c(point3,point3,matrix),fromPoints$4(out,point1,point2,point3),isMirror&&flip(out,out),out}});const invert$1=polygon=>{const vertices=polygon.vertices.slice().reverse(),inverted=create$7(vertices);return polygon.plane&&(inverted.plane=flip([0,0,0,0],polygon.plane)),inverted},isA$4=object=>!!(object&&"object"==typeof object&&"vertices"in object&&Array.isArray(object.vertices)),isConvex$1=polygon=>areVerticesConvex(polygon.vertices),areVerticesConvex=vertices=>{const numVertices=vertices.length;if(numVertices>2){const normal=fromPoints$4([0,0,0,0],...vertices);let prevPrevPos=vertices[numVertices-2],prevPos=vertices[numVertices-1];for(let i=0;i{const crossProduct=cross$1([0,0,0],subtract$3([0,0,0],vertex,prevVertex),subtract$3([0,0,0],nextVertex,vertex));return dot$2(crossProduct,normal)>=0},plane=polygon=>(polygon.plane||(polygon.plane=fromPoints$4([0,0,0,0],...polygon.vertices)),polygon.plane),measureArea$2=polygon=>{const n=polygon.vertices.length;if(n<3)return 0;const vertices=polygon.vertices,normal=plane(polygon),ax=Math.abs(normal[0]),ay=Math.abs(normal[1]),az=Math.abs(normal[2]);if(ax+ay+az===0)return 0;let coord=3;ax>ay&&ax>az?coord=1:ay>az&&(coord=2);let area=0,h=0,i=1,j=2;switch(coord){case 1:for(i=1;ia[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3],equals:equals$5,fromScalar:(out,scalar)=>(out[0]=scalar,out[1]=scalar,out[2]=scalar,out[3]=scalar,out),fromValues:fromValues$1,toString:toString$7,transform:(out,vector,matrix)=>{const[x,y,z,w]=vector;return out[0]=matrix[0]*x+matrix[4]*y+matrix[8]*z+matrix[12]*w,out[1]=matrix[1]*x+matrix[5]*y+matrix[9]*z+matrix[13]*w,out[2]=matrix[2]*x+matrix[6]*y+matrix[10]*z+matrix[14]*w,out[3]=matrix[3]*x+matrix[7]*y+matrix[11]*z+matrix[15]*w,out}});const cache$4=new WeakMap,measureBoundingSphere$1=polygon=>{const boundingSphere=cache$4.get(polygon);if(boundingSphere)return boundingSphere;const vertices=polygon.vertices,out=[0,0,0,0];if(0===vertices.length)return out[0]=0,out[1]=0,out[2]=0,out[3]=0,out;let minx=vertices[0],miny=minx,minz=minx,maxx=minx,maxy=minx,maxz=minx;vertices.forEach((v=>{minx[0]>v[0]&&(minx=v),miny[1]>v[1]&&(miny=v),minz[2]>v[2]&&(minz=v),maxx[0]{let signedVolume=0;const vertices=polygon.vertices,cross=[0,0,0];for(let i=0;ipolygon.vertices,toString$6=polygon=>`poly3: [${polygon.vertices.map(toString$b).join(", ")}]`,transform$7=(matrix,polygon)=>{const vertices=polygon.vertices.map((vertex=>transform$c([0,0,0],vertex,matrix)));return isMirroring(matrix)&&vertices.reverse(),create$7(vertices)},validate$4=object=>{if(!isA$4(object))throw new Error("invalid poly3 structure");if(object.vertices.length<3)throw new Error(`poly3 not enough vertices ${object.vertices.length}`);if(measureArea$2(object)<=0)throw new Error("poly3 area must be greater than zero");for(let i=0;i{if(!vertex.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${vertex}`)})),object.vertices.length>3){const normal=plane(object);object.vertices.forEach((vertex=>{const dist=Math.abs(signedDistanceToPoint(normal,vertex));if(dist>NEPS)throw new Error(`poly3 must be coplanar: vertex ${vertex} distance ${dist}`)}))}};var index$7=Object.freeze({__proto__:null,clone:clone$6,create:create$7,fromVerticesAndPlane:fromVerticesAndPlane,invert:invert$1,isA:isA$4,isConvex:isConvex$1,measureArea:measureArea$2,measureBoundingBox:polygon=>{const vertices=polygon.vertices,numVertices=vertices.length,min=0===numVertices?[0,0,0]:clone$9(vertices[0]),max=clone$9(min);for(let i=1;iMath.sqrt(((p,a,b)=>{const ab=[],ap=[];subtract$3(ab,b,a),subtract$3(ap,p,a);const area=squaredLength$1(cross$1([],ap,ab)),s=squaredLength$1(ab);if(0===s)throw Error("a and b are the same point");return area/s})(point,a,b));class VertexList{constructor(){this.head=null,this.tail=null}clear(){this.head=this.tail=null}insertBefore(target,node){node.prev=target.prev,node.next=target,node.prev?node.prev.next=node:this.head=node,target.prev=node}insertAfter(target,node){node.prev=target,node.next=target.next,node.next?node.next.prev=node:this.tail=node,target.next=node}add(node){this.head?this.tail.next=node:this.head=node,node.prev=this.tail,node.next=null,this.tail=node}addAll(node){for(this.head?this.tail.next=node:this.head=node,node.prev=this.tail;node.next;)node=node.next;this.tail=node}remove(node){node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev}removeChain(a,b){a.prev?a.prev.next=b.next:this.head=b.next,b.next?b.next.prev=a.prev:this.tail=a.prev}first(){return this.head}isEmpty(){return!this.head}}class Vertex{constructor(point,index){this.point=point,this.index=index,this.next=null,this.prev=null,this.face=null}}class HalfEdge{constructor(vertex,face){this.vertex=vertex,this.face=face,this.next=null,this.prev=null,this.opposite=null}head(){return this.vertex}tail(){return this.prev?this.prev.vertex:null}length(){return this.tail()?distance$1(this.tail().point,this.head().point):-1}lengthSquared(){return this.tail()?squaredDistance$1(this.tail().point,this.head().point):-1}setOpposite(edge){this.opposite=edge,edge.opposite=this}}class Face{constructor(){this.normal=[],this.centroid=[],this.offset=0,this.outside=null,this.mark=0,this.edge=null,this.nVertices=0}getEdge(i){if("number"!=typeof i)throw Error("requires a number");let it=this.edge;for(;i>0;)it=it.next,i-=1;for(;i<0;)it=it.prev,i+=1;return it}computeNormal(){const e0=this.edge,e1=e0.next;let e2=e1.next;const v2=subtract$3([],e1.head().point,e0.head().point),t=[],v1=[];for(this.nVertices=2,this.normal=[0,0,0];e2!==e0;)copy$4(v1,v2),subtract$3(v2,e2.head().point,e0.head().point),add$1(this.normal,this.normal,cross$1(t,v1,v2)),e2=e2.next,this.nVertices+=1;this.area=length$2(this.normal),this.normal=scale$3(this.normal,this.normal,1/this.area)}computeNormalMinArea(minArea){if(this.computeNormal(),this.areamaxSquaredLength&&(maxEdge=edge,maxSquaredLength=lengthSquared),edge=edge.next}while(edge!==this.edge);const p1=maxEdge.tail().point,p2=maxEdge.head().point,maxVector=subtract$3([],p2,p1),maxLength=Math.sqrt(maxSquaredLength);scale$3(maxVector,maxVector,1/maxLength);const maxProjection=dot$2(this.normal,maxVector);scale$3(maxVector,maxVector,-maxProjection),add$1(this.normal,this.normal,maxVector),normalize$1(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let edge=this.edge;do{add$1(this.centroid,this.centroid,edge.head().point),edge=edge.next}while(edge!==this.edge);scale$3(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(minArea){void 0!==minArea?this.computeNormalMinArea(minArea):this.computeNormal(),this.computeCentroid(),this.offset=dot$2(this.normal,this.centroid)}distanceToPlane(point){return dot$2(this.normal,point)-this.offset}connectHalfEdges(prev,next){let discardedFace;if(prev.opposite.face===next.opposite.face){const oppositeFace=next.opposite.face;let oppositeEdge;prev===this.edge&&(this.edge=next),3===oppositeFace.nVertices?(oppositeEdge=next.opposite.prev.opposite,oppositeFace.mark=2,discardedFace=oppositeFace):(oppositeEdge=next.opposite.next,oppositeFace.edge===oppositeEdge.prev&&(oppositeFace.edge=oppositeEdge),oppositeEdge.prev=oppositeEdge.prev.prev,oppositeEdge.prev.next=oppositeEdge),next.prev=prev.prev,next.prev.next=next,next.setOpposite(oppositeEdge),oppositeFace.computeNormalAndCentroid()}else prev.next=next,next.prev=prev;return discardedFace}mergeAdjacentFaces(adjacentEdge,discardedFaces){const oppositeEdge=adjacentEdge.opposite,oppositeFace=oppositeEdge.face;discardedFaces.push(oppositeFace),oppositeFace.mark=2;let edge,discardedFace,adjacentEdgePrev=adjacentEdge.prev,adjacentEdgeNext=adjacentEdge.next,oppositeEdgePrev=oppositeEdge.prev,oppositeEdgeNext=oppositeEdge.next;for(;adjacentEdgePrev.opposite.face===oppositeFace;)adjacentEdgePrev=adjacentEdgePrev.prev,oppositeEdgeNext=oppositeEdgeNext.next;for(;adjacentEdgeNext.opposite.face===oppositeFace;)adjacentEdgeNext=adjacentEdgeNext.next,oppositeEdgePrev=oppositeEdgePrev.prev;for(edge=oppositeEdgeNext;edge!==oppositeEdgePrev.next;edge=edge.next)edge.face=this;return this.edge=adjacentEdgeNext,discardedFace=this.connectHalfEdges(oppositeEdgePrev,adjacentEdgeNext),discardedFace&&discardedFaces.push(discardedFace),discardedFace=this.connectHalfEdges(adjacentEdgePrev,oppositeEdgeNext),discardedFace&&discardedFaces.push(discardedFace),this.computeNormalAndCentroid(),discardedFaces}collectIndices(){const indices=[];let edge=this.edge;do{indices.push(edge.head().index),edge=edge.next}while(edge!==this.edge);return indices}static createTriangle(v0,v1,v2,minArea=0){const face=new Face,e0=new HalfEdge(v0,face),e1=new HalfEdge(v1,face),e2=new HalfEdge(v2,face);return e0.next=e2.prev=e1,e1.next=e0.prev=e2,e2.next=e1.prev=e0,face.edge=e0,face.computeNormalAndCentroid(minArea),face}}class QuickHull{constructor(points){if(!Array.isArray(points))throw TypeError("input is not a valid array");if(points.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=points.length,this.faces=[],this.newFaces=[],this.claimed=new VertexList,this.unclaimed=new VertexList,this.vertices=[];for(let i=0;ithis.tolerance?this.addVertexToFace(vertex,absorbingFace):this.unclaimed.add(vertex)}else this.unclaimed.addAll(faceVertices)}resolveUnclaimedPoints(newFaces){let vertexNext=this.unclaimed.first();for(let vertex=vertexNext;vertex;vertex=vertexNext){vertexNext=vertex.next;let maxFace,maxDistance=this.tolerance;for(let i=0;imaxDistance&&(maxDistance=dist,maxFace=face),maxDistance>1e3*this.tolerance)break}}maxFace&&this.addVertexToFace(vertex,maxFace)}}computeExtremes(){const min=[],max=[],minVertices=[],maxVertices=[];let i,j;for(i=0;i<3;i+=1)minVertices[i]=maxVertices[i]=this.vertices[0];for(i=0;i<3;i+=1)min[i]=max[i]=this.vertices[0].point[i];for(i=1;imax[j]&&(max[j]=point[j],maxVertices[j]=vertex)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(min[0]),Math.abs(max[0]))+Math.max(Math.abs(min[1]),Math.abs(max[1]))+Math.max(Math.abs(min[2]),Math.abs(max[2]))),[minVertices,maxVertices]}createInitialSimplex(){const vertices=this.vertices,[min,max]=this.computeExtremes();let v2,v3,i,j,maxDistance=0,indexMax=0;for(i=0;i<3;i+=1){const distance=max[i].point[i]-min[i].point[i];distance>maxDistance&&(maxDistance=distance,indexMax=i)}const v0=min[indexMax],v1=max[indexMax];for(maxDistance=0,i=0;imaxDistance&&(maxDistance=distance,v2=vertex)}}const normal=fromPoints$4([],v0.point,v1.point,v2.point),distPO=dot$2(v0.point,normal);for(maxDistance=-1,i=0;imaxDistance&&(maxDistance=distance,v3=vertex)}}const faces=[];if(dot$2(v3.point,normal)-distPO<0)for(faces.push(Face.createTriangle(v0,v1,v2),Face.createTriangle(v3,v1,v0),Face.createTriangle(v3,v2,v1),Face.createTriangle(v3,v0,v2)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge(j)),faces[i+1].getEdge(1).setOpposite(faces[j+1].getEdge(0))}else for(faces.push(Face.createTriangle(v0,v2,v1),Face.createTriangle(v3,v0,v1),Face.createTriangle(v3,v1,v2),Face.createTriangle(v3,v2,v0)),i=0;i<3;i+=1){const j=(i+1)%3;faces[i+1].getEdge(2).setOpposite(faces[0].getEdge((3-i)%3)),faces[i+1].getEdge(0).setOpposite(faces[j+1].getEdge(1))}for(i=0;i<4;i+=1)this.faces.push(faces[i]);for(i=0;imaxDistance&&(maxDistance=distance,maxFace=faces[j])}maxFace&&this.addVertexToFace(vertex,maxFace)}}}reindexFaceAndVertices(){const activeFaces=[];for(let i=0;imaxDistance&&(maxDistance=distance,eyeVertex=vertex)}return eyeVertex}}computeHorizon(eyePoint,crossEdge,face,horizon){let edge;this.deleteFaceVertices(face),face.mark=2,edge=crossEdge?crossEdge.next:crossEdge=face.getEdge(0);do{const oppositeEdge=edge.opposite,oppositeFace=oppositeEdge.face;0===oppositeFace.mark&&(oppositeFace.distanceToPlane(eyePoint)>this.tolerance?this.computeHorizon(eyePoint,oppositeEdge,oppositeFace,horizon):horizon.push(edge)),edge=edge.next}while(edge!==crossEdge)}addAdjoiningFace(eyeVertex,horizonEdge){const face=Face.createTriangle(eyeVertex,horizonEdge.tail(),horizonEdge.head());return this.faces.push(face),face.getEdge(-1).setOpposite(horizonEdge.opposite),face.getEdge(0)}addNewFaces(eyeVertex,horizon){let firstSideEdge,previousSideEdge;this.newFaces=[];for(let i=0;i=face.nVertices)throw Error("merge recursion limit exceeded");const oppositeFace=edge.opposite.face;let merge=!1;if(2===mergeType?(this.oppositeFaceDistance(edge)>-this.tolerance||this.oppositeFaceDistance(edge.opposite)>-this.tolerance)&&(merge=!0):face.area>oppositeFace.area?this.oppositeFaceDistance(edge)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge.opposite)>-this.tolerance&&(convex=!1):this.oppositeFaceDistance(edge.opposite)>-this.tolerance?merge=!0:this.oppositeFaceDistance(edge)>-this.tolerance&&(convex=!1),merge){const discardedFaces=face.mergeAdjacentFaces(edge,[]);for(let i=0;i{const instance=new QuickHull(points);return instance.build(),instance.collectFaces(options.skipTriangulation)},toPolygons$1=geometry=>(geometry=>(isIdentity(geometry.transforms)||(geometry.polygons=geometry.polygons.map((polygon=>transform$7(geometry.transforms,polygon))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).polygons,isA$3=object=>!!(object&&"object"==typeof object&&"polygons"in object&&"transforms"in object&&Array.isArray(object.polygons)&&"length"in object.transforms),toPoints$2=geometry=>toPolygons$1(geometry).map((polygon=>toVertices$1(polygon))),transform$6=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})},validateManifold=object=>{const edgeCount=new Map;object.polygons.forEach((({vertices:vertices})=>{vertices.forEach(((v,i)=>{const edge=`${v}/${vertices[(i+1)%vertices.length]}`,count=edgeCount.has(edge)?edgeCount.get(edge):0;edgeCount.set(edge,count+1)}))}));const nonManifold=[];if(edgeCount.forEach(((count,edge)=>{const complementEdge=edge.split("/").reverse().join("/");count!==edgeCount.get(complementEdge)&&nonManifold.push(edge.replace("/"," -> "))})),nonManifold.length>0)throw new Error(`non-manifold edges ${nonManifold.length}\n${nonManifold.join("\n")}`)};var index$6=Object.freeze({__proto__:null,clone:clone$7,create:create$8,fromPoints:listOfLists=>{if(!Array.isArray(listOfLists))throw new Error("the given vertices must be an array");return create$8(listOfLists.map(create$7))},fromPointsConvex:uniquePoints=>{if(!Array.isArray(uniquePoints))throw new Error("the given points must be an array");const polygons=runner(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return create$8(polygons)},fromCompactBinary:data=>{if(1!==data[0])throw new Error("invalid compact binary data");const created=create$8();created.transforms=clone$a(data.slice(1,17));const numberOfVertices=data[21];let ci=22,vi=data.length-3*numberOfVertices;for(;vi=0&&(created.color=[data[17],data[18],data[19],data[20]]),created},invert:geometry=>{const newPolygons=toPolygons$1(geometry).map((polygon=>invert$1(polygon)));return create$8(newPolygons)},isA:isA$3,toPoints:toPoints$2,toPolygons:toPolygons$1,toString:geometry=>{const polygons=toPolygons$1(geometry);let result="geom3 ("+polygons.length+" polygons):\n";return polygons.forEach((polygon=>{result+=" "+toString$6(polygon)+"\n"})),result},toCompactBinary:geometry=>{const polygons=geometry.polygons,transforms=geometry.transforms,numberOfPolygons=polygons.length,numberOfVertices=polygons.reduce(((count,polygon)=>count+polygon.vertices.length),0);let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+numberOfPolygons+3*numberOfVertices);compacted[0]=1,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=color[0],compacted[18]=color[1],compacted[19]=color[2],compacted[20]=color[3],compacted[21]=numberOfVertices;let ci=22,vi=ci+numberOfPolygons;return polygons.forEach((polygon=>{const vertices=toVertices$1(polygon);compacted[ci]=vertices.length,ci++;for(let i=0;i{if(!isA$3(object))throw new Error("invalid geom3 structure");if(object.polygons.forEach(validate$4),validateManifold(object),!object.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${object.transforms}`)}});const clone$4=geometry=>Object.assign({},geometry),close=geometry=>{if(geometry.isClosed)return geometry;const cloned=clone$4(geometry);if(cloned.isClosed=!0,cloned.points.length>1){const points=cloned.points,p0=points[0];let pn=points[points.length-1];for(;distance(p0,pn)(void 0===points&&(points=[]),{points:points,isClosed:!1,transforms:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}),fromPoints$2=(options,points)=>{let{closed:closed}=Object.assign({},{closed:!1},options),created=create$5();if(created.points=points.map((point=>clone$8(point))),created.points.length>1){const p0=created.points[0],pn=created.points[created.points.length-1];distance(p0,pn)(geometry=>(isIdentity(geometry.transforms)||(geometry.points=geometry.points.map((point=>transform$b([0,0],point,geometry.transforms))),geometry.transforms=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),geometry))(geometry).points,concat=(...paths)=>{let isClosed=!1,newPoints=[];return paths.forEach(((path,i)=>{const tmp=toPoints$1(path).slice();if(newPoints.length>0&&tmp.length>0&&equals$6(tmp[0],newPoints[newPoints.length-1])&&tmp.shift(),tmp.length>0&&isClosed)throw new Error(`Cannot concatenate to a closed path; check the ${i}th path`);isClosed=path.isClosed,newPoints=newPoints.concat(tmp)})),fromPoints$2({closed:isClosed},newPoints)},appendPoints=(points,geometry)=>concat(geometry,create$5(points)),isA$2=object=>!!(object&&"object"==typeof object&&"points"in object&&"transforms"in object&&"isClosed"in object&&Array.isArray(object.points)&&"length"in object.transforms),transform$5=(matrix,geometry)=>{const transforms=multiply$1([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],matrix,geometry.transforms);return Object.assign({},geometry,{transforms:transforms})};var index$5=Object.freeze({__proto__:null,appendArc:(options,geometry)=>{let{endpoint:endpoint,radius:radius,xaxisRotation:xaxisRotation,clockwise:clockwise,large:large,segments:segments}=Object.assign({},{radius:[0,0],xaxisRotation:0,clockwise:!1,large:!1,segments:16},options);if(!Array.isArray(endpoint))throw new Error("endpoint must be an array of X and Y values");if(endpoint.length<2)throw new Error("endpoint must contain X and Y values");if(endpoint=clone$8(endpoint),!Array.isArray(radius))throw new Error("radius must be an array of X and Y values");if(radius.length<2)throw new Error("radius must contain X and Y values");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given path cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let xRadius=radius[0],yRadius=radius[1];const startpoint=points[points.length-1];xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5,endpoint=fromValues$2(Math.round(1e5*endpoint[0])/1e5,Math.round(1e5*endpoint[1])/1e5);const sweepFlag=!clockwise;let newPoints=[];if(0===xRadius||0===yRadius)newPoints.push(endpoint);else{xRadius=Math.abs(xRadius),yRadius=Math.abs(yRadius);const phi=xaxisRotation,cosPhi=Math.cos(phi),sinPhi=Math.sin(phi),minusHalfDistance=subtract$1([0,0],startpoint,endpoint);scale$1(minusHalfDistance,minusHalfDistance,.5);const x=Math.round(1e5*(cosPhi*minusHalfDistance[0]+sinPhi*minusHalfDistance[1]))/1e5,y=Math.round(1e5*(-sinPhi*minusHalfDistance[0]+cosPhi*minusHalfDistance[1]))/1e5,startTranslated=fromValues$2(x,y),bigLambda=startTranslated[0]*startTranslated[0]/(xRadius*xRadius)+startTranslated[1]*startTranslated[1]/(yRadius*yRadius);if(bigLambda>1){const sqrtBigLambda=Math.sqrt(bigLambda);xRadius*=sqrtBigLambda,yRadius*=sqrtBigLambda,xRadius=Math.round(1e5*xRadius)/1e5,yRadius=Math.round(1e5*yRadius)/1e5}let multiplier1=Math.sqrt((xRadius*xRadius*yRadius*yRadius-xRadius*xRadius*startTranslated[1]*startTranslated[1]-yRadius*yRadius*startTranslated[0]*startTranslated[0])/(xRadius*xRadius*startTranslated[1]*startTranslated[1]+yRadius*yRadius*startTranslated[0]*startTranslated[0]));sweepFlag===large&&(multiplier1=-multiplier1);const centerTranslated=fromValues$2(xRadius*startTranslated[1]/yRadius,-yRadius*startTranslated[0]/xRadius);scale$1(centerTranslated,centerTranslated,multiplier1);let center=fromValues$2(cosPhi*centerTranslated[0]-sinPhi*centerTranslated[1],sinPhi*centerTranslated[0]+cosPhi*centerTranslated[1]);center=add(center,center,scale$1([0,0],add([0,0],startpoint,endpoint),.5));const vector1=fromValues$2((startTranslated[0]-centerTranslated[0])/xRadius,(startTranslated[1]-centerTranslated[1])/yRadius),vector2=fromValues$2((-startTranslated[0]-centerTranslated[0])/xRadius,(-startTranslated[1]-centerTranslated[1])/yRadius),theta1=angleRadians(vector1);let deltatheta=angleRadians(vector2)-theta1;deltatheta%=TAU,!sweepFlag&&deltatheta>0?deltatheta-=TAU:sweepFlag&&deltatheta<0&&(deltatheta+=TAU);let numSteps=Math.ceil(Math.abs(deltatheta)/TAU*segments)+1;numSteps<1&&(numSteps=1);for(let step=1;step{let{controlPoints:controlPoints,segments:segments}=Object.assign({},{segments:16},options);if(!Array.isArray(controlPoints))throw new Error("controlPoints must be an array of one or more points");if(controlPoints.length<1)throw new Error("controlPoints must be an array of one or more points");if(segments<4)throw new Error("segments must be four or more");if(geometry.isClosed)throw new Error("the given geometry cannot be closed");const points=toPoints$1(geometry);if(points.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(controlPoints=controlPoints.slice(),null===controlPoints[0]){if(controlPoints.length<2)throw new Error("a null control point must be passed with one more control points");let lastBezierControlPoint=points[points.length-2];if("lastBezierControlPoint"in geometry&&(lastBezierControlPoint=geometry.lastBezierControlPoint),!Array.isArray(lastBezierControlPoint))throw new Error("the given path must contain TWO or more points if given a null control point");const controlPoint=scale$1([0,0],points[points.length-1],2);subtract$1(controlPoint,controlPoint,lastBezierControlPoint),controlPoints[0]=controlPoint}controlPoints.unshift(points[points.length-1]);const bezierOrder=controlPoints.length-1,factorials=[];let fact=1;for(let i=0;i<=bezierOrder;++i)i>0&&(fact*=i),factorials.push(fact);const binomials=[];for(let i=0;i<=bezierOrder;++i){const binomial=factorials[bezierOrder]/(factorials[i]*factorials[bezierOrder-i]);binomials.push(binomial)}const v0=[0,0],v1=[0,0],v3=[0,0,0],getPointForT=t=>{let tk=1,oneMinusTNMinusK=Math.pow(1-t,bezierOrder);const invOneMinusT=1!==t?1/(1-t):1,point=[0,0];for(let k=0;k<=bezierOrder;++k){k===bezierOrder&&(oneMinusTNMinusK=1);const bernsteinCoefficient=binomials[k]*tk*oneMinusTNMinusK,derivativePoint=scale$1(v0,controlPoints[k],bernsteinCoefficient);add(point,point,derivativePoint),tk*=t,oneMinusTNMinusK*=invOneMinusT}return point},newPoints=[],newPointsT=[],numSteps=bezierOrder+1;for(let i=0;imaxSinAngle){const t0=newPointsT[subdivideBase-1],t1=newPointsT[subdivideBase+1],newt0=t0+1*(t1-t0)/3,newt1=t0+2*(t1-t0)/3,point0=getPointForT(newt0),point1=getPointForT(newt1);newPoints.splice(subdivideBase,1,point0,point1),newPointsT.splice(subdivideBase,1,newt0,newt1),subdivideBase--,subdivideBase<1&&(subdivideBase=1)}else++subdivideBase}newPoints.shift();const result=appendPoints(newPoints,geometry);return result.lastBezierControlPoint=controlPoints[controlPoints.length-2],result},appendPoints:appendPoints,clone:clone$4,close:close,concat:concat,create:create$5,equals:(a,b)=>{if(a.isClosed!==b.isClosed)return!1;if(a.points.length!==b.points.length)return!1;const aPoints=toPoints$1(a),bPoints=toPoints$1(b),length=aPoints.length;let offset=0;do{let unequal=!1;for(let i=0;i{if(2!==data[0])throw new Error("invalid compact binary data");const created=create$5();created.transforms=clone$a(data.slice(1,17)),created.isClosed=!!data[17];for(let i=22;i=0&&(created.color=[data[18],data[19],data[20],data[21]]),created},isA:isA$2,reverse:geometry=>{const cloned=clone$4(geometry);return cloned.points=geometry.points.slice().reverse(),cloned},toPoints:toPoints$1,toString:geometry=>{const points=toPoints$1(geometry);let result="path ("+points.length+" points, "+geometry.isClosed+"):\n[\n";return points.forEach((point=>{result+=" "+toString$9(point)+",\n"})),result+="]\n",result},toCompactBinary:geometry=>{const points=geometry.points,transforms=geometry.transforms;let color=[-1,-1,-1,-1];geometry.color&&(color=geometry.color);const compacted=new Float32Array(22+2*points.length);compacted[0]=2,compacted[1]=transforms[0],compacted[2]=transforms[1],compacted[3]=transforms[2],compacted[4]=transforms[3],compacted[5]=transforms[4],compacted[6]=transforms[5],compacted[7]=transforms[6],compacted[8]=transforms[7],compacted[9]=transforms[8],compacted[10]=transforms[9],compacted[11]=transforms[10],compacted[12]=transforms[11],compacted[13]=transforms[12],compacted[14]=transforms[13],compacted[15]=transforms[14],compacted[16]=transforms[15],compacted[17]=geometry.isClosed?1:0,compacted[18]=color[0],compacted[19]=color[1],compacted[20]=color[2],compacted[21]=color[3];for(let j=0;j{if(!isA$2(object))throw new Error("invalid path2 structure");if(object.points.length>1)for(let i=0;i{if(!point.every(Number.isFinite))throw new Error(`path2 invalid point ${point}`)})),!object.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${object.transforms}`)}});const colorize=(color,...objects)=>{if(!Array.isArray(color))throw new Error("color must be an array");if(color.length<3)throw new Error("color must contain R, G and B values");3===color.length&&(color=[color[0],color[1],color[2],1]);const results=objects.map((object=>isA$5(object)?((color,object)=>{const newGeom2=clone$b(object);return newGeom2.color=color,newGeom2})(color,object):isA$3(object)?((color,object)=>{const newGeom3=clone$7(object);return newGeom3.color=color,newGeom3})(color,object):isA$2(object)?((color,object)=>{const newPath2=clone$4(object);return newPath2.color=color,newPath2})(color,object):isA$4(object)?((color,object)=>{const newPoly=clone$6(object);return newPoly.color=color,newPoly})(color,object):Array.isArray(object)?colorize(color,...object):(object.color=color,object)));return 1===results.length?results[0]:results},flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),hueToColorComponent=(p,q,t)=>(t<0&&(t+=1),t>1&&(t-=1),t<1/6?p+6*(q-p)*t:t<.5?q:t<2/3?p+(q-p)*(2/3-t)*6:p),getPointType=function(points){let firstPointType=null;return points.forEach((point=>{let pType="";if(Number.isFinite(point))pType="float_single";else{if(!Array.isArray(point))throw new Error("Bezier points must all be numbers or arrays of number.");point.forEach((val=>{if(!Number.isFinite(val))throw new Error("Bezier point values must all be numbers.")})),pType="float_"+point.length}if(null==firstPointType)firstPointType=pType;else if(firstPointType!==pType)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),firstPointType},getPermutations=function(c){const permutations=[];for(let i=0;i<=c;i++)permutations.push(factorial(c)/(factorial(i)*factorial(c-i)));return permutations},factorial=function(b){let out=1;for(let i=2;i<=b;i++)out*=i;return out},valueAt=(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierFunction(bezier,bezier.points,t);{const result=[];for(let i=0;i{let sum=0;const lengths=[0];let previous=valueAt(0,bezier);for(let index=1;index<=segments;index++){const current=valueAt(index/segments,bezier);sum+=distanceBetween(current,previous),lengths.push(sum),previous=current}return lengths},distanceBetween=(a,b)=>{if(Number.isFinite(a)&&Number.isFinite(b))return Math.abs(a-b);if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)throw new Error("The operands must have the same number of dimensions.");let sum=0;for(let i=0;i{if(!Array.isArray(points))throw new Error("Bezier points must be a valid array/");if(points.length<2)throw new Error("Bezier points must contain at least 2 values.");const pointType=getPointType(points);return{points:points,pointType:pointType,dimensions:"float_single"===pointType?0:points[0].length,permutations:getPermutations(points.length-1),tangentPermutations:getPermutations(points.length-2)}},valueAt:valueAt,tangentAt:(t,bezier)=>{if(t<0||t>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===bezier.pointType)return bezierTangent(bezier,bezier.points,t);{const result=[];for(let i=0;ilengths(segments,bezier)[segments],arcLengthToT:(options,bezier)=>{const{distance:distance,segments:segments}=Object.assign({},{distance:0,segments:100},options),arcLengths=lengths(segments,bezier);let startIndex=0,endIndex=segments;for(;startIndex<=endIndex;){const middleIndex=Math.floor(startIndex+(endIndex-startIndex)/2),diff=arcLengths[middleIndex]-distance;if(diff<0)startIndex=middleIndex+1;else{if(!(diff>0)){endIndex=middleIndex;break}endIndex=middleIndex-1}}const targetIndex=endIndex;if(arcLengths[targetIndex]===distance)return targetIndex/segments;const lengthBefore=arcLengths[targetIndex];return(targetIndex+(distance-lengthBefore)/(arcLengths[targetIndex+1]-lengthBefore))/segments}});const area$1=points=>{let area=0;for(let i=0;iarea$1(polygon.points),create$3=points=>((void 0===points||points.length<3)&&(points=[]),{points:points}),reverse$3=polygon=>{const points=polygon.points.slice().reverse();return create$3(points)},arePointsInside=(points,polygon)=>0===points.length||polygon.points.length<3?0:(measureArea$1(polygon)<0&&(polygon=reverse$3(polygon)),points.reduce(((acc,point)=>acc+isPointInside(point,polygon.points)),0)===points.length?1:0),isPointInside=(point,polygon)=>{const numPoints=polygon.length,tx=point[0],ty=point[1];let vtx0=polygon[numPoints-1],vtx1=polygon[0],yFlag0=vtx0[1]>ty,insideFlag=0,i=0;for(let j=numPoints+1;--j;){const yFlag1=vtx1[1]>ty;if(yFlag0!==yFlag1){const xFlag0=vtx0[0]>tx,xFlag1=vtx1[0]>tx;(xFlag0&&xFlag1||vtx1[0]-(vtx1[1]-ty)*(vtx0[0]-vtx1[0])/(vtx0[1]-vtx1[1])>=tx)&&(insideFlag=!insideFlag)}yFlag0=yFlag1,vtx0=vtx1,vtx1=polygon[++i]}return insideFlag},isA$1=object=>!!(object&&"object"==typeof object&&"points"in object&&Array.isArray(object.points)),crossBetweenSegments=(p1,p2,p3)=>{const X1=p2[0]-p1[0],Y1=p2[1]-p1[1],X2=p3[0]-p1[0];return X1*(p3[1]-p1[1])-Y1*X2};var index$3=Object.freeze({__proto__:null,arePointsInside:arePointsInside,clone:polygon=>Object.assign({},polygon),create:create$3,isA:isA$1,isConvex:polygon=>{const numPoints=polygon.points.length;if(numPoints>2){const points=polygon.points;let prev=0,curr=0;for(let i=0;i{const numPoints=polygon.points.length;if(numPoints<3)return!1;if(3===numPoints)return!0;const points=polygon.points,found=new Set;if(points.forEach((v=>found.add(v.toString()))),found.size!==numPoints)return!1;for(let i=0;i{const points=polygon.points,numPoints=points.length,min=0===numPoints?[0,0]:clone$8(points[0]),max=clone$8(min);for(let i=1;ipolygon.points,toString:polygon=>`poly2: [${polygon.points.map(toString$9).join(", ")}]`,transform:(matrix,polygon)=>{const points=polygon.points.map((point=>transform$b([0,0],point,matrix)));return isMirroring(matrix)&&points.reverse(),create$3(points)},validate:object=>{if(!isA$1(object))throw new Error("invalid poly2 structure");if(object.points.length<3)throw new Error(`poly2 not enough points ${object.points.length}`);if(measureArea$1(object)<=0)throw new Error("poly2 area must be greater than zero");for(let i=0;i{if(2!==point.length)throw new Error(`poly2 invalid point ${point}`);if(!point.every(Number.isFinite))throw new Error(`poly2 invalid point ${point}`)}))}});const calculatePlane=slice=>{if(slice.contours.length<1)throw new Error("slices must have at least one contour to calculate a plane");const middle=[0,0,0];let n=0;slice.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(middle,middle,vertex),n++}))})),scale$3(middle,middle,1/n);let farthestBefore,farthestVertex,farthestAfter,farthestContour=[],distance=0;slice.contours.forEach((contour=>{let prev=contour[contour.length-1];contour.forEach((vertex=>{if(!equals$7(prev,vertex)){const d=squaredDistance$1(middle,vertex);d>distance&&(farthestContour=contour,farthestBefore=prev,farthestVertex=vertex,distance=d)}prev=vertex}))}));let prev=farthestContour[farthestContour.length-1];for(let i=0;i({contours:contours}),equals$3=(a,b)=>{if(a.contours.length!==b.contours.length)return!1;const len=a.contours.length;for(let i=0;i{const contours=toOutlines(geometry).map((outline=>outline.map((point=>fromVec2([0,0,0],point)))));return create$2(contours)},fromVertices=vertices=>{if(!Array.isArray(vertices))throw new Error("the given vertices must be an array");if(vertices.length<3)throw new Error("the given vertices must contain THREE or more vertices");const cloned=vertices.map((vertex=>3===vertex.length?vertex:fromVec2([0,0,0],vertex)));return create$2([cloned])},isA=object=>!!(object&&"object"==typeof object&&"contours"in object&&Array.isArray(object.contours)),reverse$2=slice=>{const contours=slice.contours.map((contour=>contour.slice().reverse()));return create$2(contours)},toEdges=slice=>{const edges=[];return slice.contours.forEach((contour=>{contour.forEach(((vertex,i)=>{const next=contour[(i+1)%contour.length];edges.push([vertex,next])}))})),edges};class Node$2{constructor(i,x,y){this.i=i,this.x=x,this.y=y,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}const insertNode=(i,x,y,last)=>{const p=new Node$2(i,x,y);return last?(p.next=last.next,p.prev=last,last.next.prev=p,last.next=p):(p.prev=p,p.next=p),p},removeNode=p=>{p.next.prev=p.prev,p.prev.next=p.next,p.prevZ&&(p.prevZ.nextZ=p.nextZ),p.nextZ&&(p.nextZ.prevZ=p.prevZ)},pointInTriangle=(ax,ay,bx,by,cx,cy,px,py)=>(cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0,area=(p,q,r)=>(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y),linkedPolygon=(data,start,end,dim,clockwise)=>{let last;if(clockwise===signedArea$1(data,start,end,dim)>0)for(let i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);return last&&equals$2(last,last.next)&&(removeNode(last),last=last.next),last},filterPoints=(start,end)=>{if(!start)return start;end||(end=start);let again,p=start;do{if(again=!1,p.steiner||!equals$2(p,p.next)&&0!==area(p.prev,p,p.next))p=p.next;else{if(removeNode(p),p=end=p.prev,p===p.next)break;again=!0}}while(again||p!==end);return end},cureLocalIntersections=(start,triangles,dim)=>{let p=start;do{const a=p.prev,b=p.next.next;!equals$2(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim),triangles.push(p.i/dim),triangles.push(b.i/dim),removeNode(p),removeNode(p.next),p=start=b),p=p.next}while(p!==start);return filterPoints(p)},locallyInside=(a,b)=>area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0,splitPolygon=(a,b)=>{const a2=new Node$2(a.i,a.x,a.y),b2=new Node$2(b.i,b.x,b.y),an=a.next,bp=b.prev;return a.next=b,b.prev=a,a2.next=an,an.prev=a2,b2.next=a2,a2.prev=b2,bp.next=b2,b2.prev=bp,b2},isValidDiagonal=(a,b)=>a.next.i!==b.i&&a.prev.i!==b.i&&!((a,b)=>{let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return!0;p=p.next}while(p!==a);return!1})(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&((a,b)=>{let p=a,inside=!1;const px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),p=p.next}while(p!==a);return inside})(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals$2(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0),intersects=(p1,q1,p2,q2)=>{const o1=Math.sign(area(p1,q1,p2)),o2=Math.sign(area(p1,q1,q2)),o3=Math.sign(area(p2,q2,p1)),o4=Math.sign(area(p2,q2,q1));return o1!==o2&&o3!==o4||!(0!==o1||!onSegment(p1,p2,q1))||!(0!==o2||!onSegment(p1,q2,q1))||!(0!==o3||!onSegment(p2,p1,q2))||!(0!==o4||!onSegment(p2,q1,q2))},onSegment=(p,q,r)=>q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y),signedArea$1=(data,start,end,dim)=>{let sum=0;for(let i=start,j=end-dim;ip1.x===p2.x&&p1.y===p2.y,eliminateHole=(hole,outerNode)=>{const bridge=findHoleBridge(hole,outerNode);if(!bridge)return outerNode;const bridgeReverse=splitPolygon(bridge,hole),filteredBridge=filterPoints(bridge,bridge.next);return filterPoints(bridgeReverse,bridgeReverse.next),outerNode===bridge?filteredBridge:outerNode},findHoleBridge=(hole,outerNode)=>{let p=outerNode;const hx=hole.x,hy=hole.y;let m,qx=-1/0;do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){const x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){if(qx=x,x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))&&(m=p,tanMin=tan)}p=p.next}while(p!==stop);return m},sectorContainsSector=(m,p)=>area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0,getLeftmost=start=>{let p=start,leftmost=start;do{(p.x{const hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length;let outerNode=linkedPolygon(data,0,outerLen,dim,!0);const triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;let minX,minY,maxX,maxY,invSize;if(hasHoles&&(outerNode=((data,holeIndices,outerNode,dim)=>{const queue=[];for(let i=0,len=holeIndices.length;ia.x-b.x));for(let i=0;i80*dim){minX=maxX=data[0],minY=maxY=data[1];for(let i=dim;imaxX&&(maxX=x),y>maxY&&(maxY=y)}invSize=Math.max(maxX-minX,maxY-minY),invSize=0!==invSize?1/invSize:0}return earcutLinked(outerNode,triangles,dim,minX,minY,invSize),triangles},earcutLinked=(ear,triangles,dim,minX,minY,invSize,pass)=>{if(!ear)return;!pass&&invSize&&indexCurve(ear,minX,minY,invSize);let prev,next,stop=ear;for(;ear.prev!==ear.next;)if(prev=ear.prev,next=ear.next,invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear))triangles.push(prev.i/dim),triangles.push(ear.i/dim),triangles.push(next.i/dim),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?(ear=cureLocalIntersections(filterPoints(ear),triangles,dim),earcutLinked(ear,triangles,dim,minX,minY,invSize,2)):2===pass&&splitEarcut(ear,triangles,dim,minX,minY,invSize):earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);break}},isEar=ear=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;let p=ear.next.next;for(;p!==ear.prev;){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.next}return!0},isEarHashed=(ear,minX,minY,invSize)=>{const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return!1;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y,minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;for(;p&&p.z>=minZ&&n&&n.z<=maxZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}for(;p&&p.z>=minZ;){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return!1;n=n.nextZ}return!0},splitEarcut=(start,triangles,dim,minX,minY,invSize)=>{let a=start;do{let b=a.next.next;for(;b!==a.prev;){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);return a=filterPoints(a,a.next),c=filterPoints(c,c.next),earcutLinked(a,triangles,dim,minX,minY,invSize),void earcutLinked(c,triangles,dim,minX,minY,invSize)}b=b.next}a=a.next}while(a!==start)},indexCurve=(start,minX,minY,invSize)=>{let p=start;do{null===p.z&&(p.z=zOrder(p.x,p.y,minX,minY,invSize)),p.prevZ=p.prev,p.nextZ=p.next,p=p.next}while(p!==start);p.prevZ.nextZ=null,p.prevZ=null,((list,fn)=>{let i,p,q,e,numMerges,inSize=1;do{p=list,list=null;let tail=null;for(numMerges=0;p;){numMerges++,q=p;let pSize=0;for(i=0;i0||qSize>0&&q;)0!==pSize&&(0===qSize||!q||fn(p)<=fn(q))?(e=p,p=p.nextZ,pSize--):(e=q,q=q.nextZ,qSize--),tail?tail.nextZ=e:list=e,e.prevZ=tail,tail=e;p=q}tail.nextZ=null,inSize*=2}while(numMerges>1)})(p,(p=>p.z))},zOrder=(x,y,minX,minY,invSize)=>(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=32767*(x-minX)*invSize)|x<<8))|x<<4))|x<<2))|x<<1))|(y=1431655765&((y=858993459&((y=252645135&((y=16711935&((y=32767*(y-minY)*invSize)|y<<8))|y<<4))|y<<2))|y<<1))<<1,minIndex=(list,score)=>{let bestIndex,best;return list.forEach(((item,index)=>{const value=score(item);(void 0===best||valuepart.map((v=>this.to2D(v))))),geometry=create$a(projected);this.roots=(geometry=>{const outlines=toOutlines(geometry),solids=[],holes=[];outlines.forEach(((outline,i)=>{const a=area$1(outline);a<0?holes.push(i):a>0&&solids.push(i)}));const children=[],parents=[];return solids.forEach(((s,i)=>{const solid=outlines[s];children[i]=[],holes.forEach(((h,j)=>{const hole=outlines[h];arePointsInside([hole[0]],create$3(solid))&&(children[i].push(h),parents[j]||(parents[j]=[]),parents[j].push(i))}))})),holes.forEach(((h,j)=>{if(parents[j]&&parents[j].length>1){const directParent=minIndex(parents[j],(p=>children[p].length));parents[j].forEach(((p,i)=>{i!==directParent&&(children[p]=children[p].filter((c=>c!==h)))}))}})),children.map(((holes,i)=>({solid:outlines[solids[i]],holes:holes.map((h=>outlines[h]))})))})(geometry)}to2D(vector3){const vector2=fromValues$2(dot$2(vector3,this.u),dot$2(vector3,this.v));return this.basisMap.set(vector2,vector3),vector2}to3D(vector2){const original=this.basisMap.get(vector2);if(original)return original;{console.log("Warning: point not in original slice");const v1=scale$3([0,0,0],this.u,vector2[0]),v2=scale$3([0,0,0],this.v,vector2[1]),planeOrigin=scale$3([0,0,0],this.plane,this.plane[3]),v3=add$1(v1,v1,planeOrigin);return add$1(v2,v2,v3)}}}const toPolygons=slice=>{const hierarchy=new PolygonHierarchy(slice),polygons=[];return hierarchy.roots.forEach((({solid:solid,holes:holes})=>{let index=solid.length;const holesIndex=[];holes.forEach(((hole,i)=>{holesIndex.push(index),index+=hole.length}));const vertices=[solid,...holes].flat(),data=vertices.flat(),getVertex=i=>hierarchy.to3D(vertices[i]),indices=triangulate(data,holesIndex);for(let i=0;i{const contours=slice.contours.map((contour=>contour.map((vertex=>transform$c([0,0,0],vertex,matrix)))));return create$2(contours)};var index$2=Object.freeze({__proto__:null,calculatePlane:calculatePlane,clone:slice=>Object.assign({},slice),create:create$2,equals:equals$3,fromGeom2:fromGeom2,fromVertices:fromVertices,isA:isA,reverse:reverse$2,toEdges:toEdges,toVertices:slice=>{const vertices=[];return slice.contours.forEach((contour=>{contour.forEach((vertex=>{vertices.push(vertex)}))})),vertices},toPolygons:toPolygons,toString:slice=>{let result="slice ("+slice.contours.length+" contours):\n[\n";return slice.contours.forEach((contour=>{result+=" ["+contour.map(toString$b).join()+"],\n"})),result+="]\n",result},transform:transform$3,validate:object=>{if(!isA(object))throw new Error("invalid slice structure");const slicePlane=calculatePlane(object);object.contours.forEach(((contour,i)=>{if(contour.length<3)throw new Error(`slice contour ${i} must contain at least 3 vertices`);const contourPlane=plane(create$7(contour));if(!equals$5(slicePlane,contourPlane))throw new Error("slice contours must be coplanar");for(let i=0;i[0,1,0],direction$1=line=>{const vector=normal([0,0],line);return negate(vector,vector),vector},origin$1=line=>scale$1([0,0],line,line[2]),copy$1=(out,line)=>(out[0]=line[0],out[1]=line[1],out[2]=line[2],out),fromPoints$1=(out,point1,point2)=>{const vector=subtract$1([0,0],point2,point1);normal(vector,vector),normalize(vector,vector);const distance=dot$1(point1,vector);return out[0]=vector[0],out[1]=vector[1],out[2]=distance,out},fromValues=(x,y,d)=>{const out=[0,1,0];return out[0]=x,out[1]=y,out[2]=d,out},solve2Linear=(a,b,c,d,u,v)=>{const invdet=1/(a*d-b*c);let x=u*d-b*v,y=-u*c+a*v;return x*=invdet,y*=invdet,[x,y]},intersectPointOfLines=(line1,line2)=>{const point=solve2Linear(line1[0],line1[1],line2[0],line2[1],line1[2],line2[2]);return clone$8(point)};var index$1=Object.freeze({__proto__:null,clone:line=>{const out=[0,1,0];return out[0]=line[0],out[1]=line[1],out[2]=line[2],out},closestPoint:(line,point)=>{const orig=origin$1(line),dir=direction$1(line),v=subtract$1([0,0],point,orig),dist=dot$1(v,dir);return scale$1(v,dir,dist),add(v,v,orig),v},copy:copy$1,create:create$1,direction:direction$1,distanceToPoint:(line,point)=>{let distance=dot$1(point,line);return distance=Math.abs(distance-line[2]),distance},equals:(line1,line2)=>line1[0]===line2[0]&&line1[1]===line2[1]&&line1[2]===line2[2],fromPoints:fromPoints$1,fromValues:fromValues,intersectPointOfLines:intersectPointOfLines,origin:origin$1,reverse:(out,line)=>{const normal=negate([0,0],line),distance=-line[2];return copy$1(out,fromValues(normal[0],normal[1],distance))},toString:line=>`line2: (${line[0].toFixed(7)}, ${line[1].toFixed(7)}, ${line[2].toFixed(7)})`,transform:(out,line,matrix)=>{const org=origin$1(line),dir=direction$1(line);return transform$b(org,org,matrix),transform$b(dir,dir,matrix),fromPoints$1(out,org,dir)},xAtY:(line,y)=>{let x=(line[2]-line[1]*y)/line[0];return Number.isNaN(x)&&(x=origin$1(line)[0]),x}});const create=()=>[fromValues$3(0,0,0),fromValues$3(0,0,1)],closestPoint=(line,point)=>{const lPoint=line[0],lDirection=line[1],a=dot$2(subtract$3([0,0,0],point,lPoint),lDirection),b=dot$2(lDirection,lDirection),closestPoint=scale$3([0,0,0],lDirection,a/b);return add$1(closestPoint,closestPoint,lPoint),closestPoint},fromPointAndDirection=(out,point,direction)=>{const unit=normalize$1([0,0,0],direction);return copy$4(out[0],point),copy$4(out[1],unit),out};var index=Object.freeze({__proto__:null,clone:line=>{const out=create();return copy$4(out[0],line[0]),copy$4(out[1],line[1]),out},closestPoint:closestPoint,copy:(out,line)=>(copy$4(out[0],line[0]),copy$4(out[1],line[1]),out),create:create,direction:line=>line[1],distanceToPoint:(line,point)=>{const closest=closestPoint(line,point),distanceVector=subtract$3([0,0,0],point,closest);return length$2(distanceVector)},equals:(line1,line2)=>!!equals$7(line1[1],line2[1])&&!!equals$7(line1[0],line2[0]),fromPlanes:(out,plane1,plane2)=>{let direction=cross$1([0,0,0],plane1,plane2),length=length$2(direction);if(length=absY&&absX>=absZ?(r=solve2Linear(plane1[1],plane1[2],plane2[1],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(0,r[0],r[1])):absY>=absX&&absY>=absZ?(r=solve2Linear(plane1[0],plane1[2],plane2[0],plane2[2],plane1[3],plane2[3]),origin=fromValues$3(r[0],0,r[1])):(r=solve2Linear(plane1[0],plane1[1],plane2[0],plane2[1],plane1[3],plane2[3]),origin=fromValues$3(r[0],r[1],0)),fromPointAndDirection(out,origin,direction)},fromPointAndDirection:fromPointAndDirection,fromPoints:(out,point1,point2)=>{const direction=subtract$3([0,0,0],point2,point1);return fromPointAndDirection(out,point1,direction)},intersectPointOfLineAndPlane:(line,plane)=>{const pNormal=plane,pw=plane[3],lPoint=line[0],lDirection=line[1],labda=(pw-dot$2(pNormal,lPoint))/dot$2(pNormal,lDirection);return add$1([0,0,0],lPoint,scale$3([0,0,0],lDirection,labda))},origin:line=>line[0],reverse:(out,line)=>{const point=clone$9(line[0]),direction=negate$1([0,0,0],line[1]);return fromPointAndDirection(out,point,direction)},toString:line=>{const point=line[0],direction=line[1];return`line3: point: (${point[0].toFixed(7)}, ${point[1].toFixed(7)}, ${point[2].toFixed(7)}) direction: (${direction[0].toFixed(7)}, ${direction[1].toFixed(7)}, ${direction[2].toFixed(7)})`},transform:(out,line,matrix)=>{const point=line[0],direction=line[1],pointPlusDirection=add$1([0,0,0],point,direction),newPoint=transform$c([0,0,0],point,matrix),newPointPlusDirection=transform$c(pointPlusDirection,pointPlusDirection,matrix),newDirection=subtract$3(newPointPlusDirection,newPointPlusDirection,newPoint);return fromPointAndDirection(out,newPoint,newDirection)}});const cache$3=new WeakMap,measureArea=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?0:isA$5(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=toSides(geometry).reduce(((area,side)=>area+(side[0][0]*side[1][1]-side[0][1]*side[1][0])),0),area*=.5,cache$3.set(geometry,area),area)})(geometry):isA$3(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=toPolygons$1(geometry).reduce(((area,polygon)=>area+measureArea$2(polygon)),0),cache$3.set(geometry,area),area)})(geometry):isA(geometry)?(geometry=>{let area=cache$3.get(geometry);return area||(area=0,geometry.contours.forEach((contour=>{area+=measureArea$2(create$7(contour))})),cache$3.set(geometry,area),area)})(geometry):0));return 1===results.length?results[0]:results},cache$2=new WeakMap,expand2=(bbox,point)=>{0===bbox.length?(bbox[0]=fromVec2([0,0,0],point),bbox[1]=fromVec2([0,0,0],point)):(min$1(bbox[0],bbox[0],point),max$1(bbox[1],bbox[1],point))},expand3=(bbox,vertex)=>{0===bbox.length?(bbox[0]=clone$9(vertex),bbox[1]=clone$9(vertex)):(min$2(bbox[0],bbox[0],vertex),max$2(bbox[1],bbox[1],vertex))},measureCached$1=(geometry,measureFn)=>{let boundingBox=cache$2.get(geometry);return boundingBox||(boundingBox=measureFn(geometry),0===boundingBox.length&&(boundingBox[0]=[0,0,0],boundingBox[1]=[0,0,0]),cache$2.set(geometry,boundingBox),boundingBox)},measureBoundingBoxOfPath2=geometry=>{const boundingBox=[];return toPoints$1(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom2=geometry=>{const boundingBox=[];return toPoints$3(geometry).forEach((point=>{expand2(boundingBox,point)})),boundingBox},measureBoundingBoxOfGeom3=geometry=>{const boundingBox=[];return toPolygons$1(geometry).forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBoxOfSlice=geometry=>{const boundingBox=[];return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{expand3(boundingBox,vertex)}))})),boundingBox},measureBoundingBox=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?measureCached$1(geometry,measureBoundingBoxOfPath2):isA$5(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom2):isA$3(geometry)?measureCached$1(geometry,measureBoundingBoxOfGeom3):isA(geometry)?measureCached$1(geometry,measureBoundingBoxOfSlice):[[0,0,0],[0,0,0]]));return 1===results.length?results[0]:results},measureAggregateBoundingBox=(...geometries)=>{geometries=flatten(geometries);const bounds=measureBoundingBox(geometries);if(1===geometries.length)return bounds;const result=[[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],[-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE]];return bounds.reduce(((result,item)=>result=[min$2(result[0],result[0],item[0]),max$2(result[1],result[1],item[1])]),result)},calculateEpsilonFromBounds=(bounds,dimensions)=>{let total=0;for(let i=0;i{const results=(geometries=flatten(geometries)).map((geometry=>isA$3(geometry)?(geometry=>{let volume=cache$1.get(geometry);return volume||(volume=toPolygons$1(geometry).reduce(((volume,polygon)=>volume+measureSignedVolume(polygon)),0),cache$1.set(geometry,volume),volume)})(geometry):0));return 1===results.length?results[0]:results},cache=new WeakMap,measureCached=(geometry,measureFn)=>{let boundingSphere=cache.get(geometry);return boundingSphere||(boundingSphere=measureFn(geometry),0===boundingSphere.length&&(boundingSphere[0]=[0,0,0],boundingSphere[1]=0),cache.set(geometry,boundingSphere),boundingSphere)},measureBoundingSphereOfPoints=points=>{const centroid=[0,0,0];let radius=0;if(points.length>0){let numPoints=0;const temp=[0,0,0];points.forEach((point=>{add$1(centroid,centroid,fromVec2(temp,point,0)),numPoints++})),scale$3(centroid,centroid,1/numPoints),points.forEach((point=>{radius=Math.max(radius,squaredDistance(centroid,point))})),radius=Math.sqrt(radius)}return[centroid,radius]},measureBoundingSphereOfPath2=points=>measureBoundingSphereOfPoints(toPoints$1(points)),measureBoundingSphereOfGeom2=geometry=>measureBoundingSphereOfPoints(toPoints$3(geometry)),measureBoundingSphereOfGeom3=geometry=>{const centroid=[0,0,0];let radius=0;const polygons=toPolygons$1(geometry);if(polygons.length>0){let numVertices=0;polygons.forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{add$1(centroid,centroid,vertex),numVertices++}))})),scale$3(centroid,centroid,1/numVertices),polygons.forEach((polygon=>{toVertices$1(polygon).forEach((vertex=>{radius=Math.max(radius,squaredDistance$1(centroid,vertex))}))})),radius=Math.sqrt(radius)}return[centroid,radius]},measureBoundingSphereOfSlice=geometry=>{const centroid=[0,0,0];let radius=0,numVertices=0;return geometry.contours.forEach((contour=>{contour.forEach((vertex=>{add$1(centroid,centroid,vertex),numVertices++}))})),numVertices>0&&(scale$3(centroid,centroid,1/numVertices),geometry.contours.forEach((contour=>{contour.forEach((vertex=>{radius=Math.max(radius,squaredDistance$1(centroid,vertex))}))})),radius=Math.sqrt(radius)),[centroid,radius]},cacheOfCenterOfMass=new WeakMap,measureEpsilon=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)||isA$5(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),2):isA$3(geometry)||isA(geometry)?calculateEpsilonFromBounds(measureBoundingBox(geometry),3):0));return 1===results.length?results[0]:results},isNumberArray=(array,dimension)=>!!(Array.isArray(array)&&array.length>=dimension)&&array.every((n=>Number.isFinite(n))),isGT=(value,constant)=>Number.isFinite(value)&&value>constant,isGTE=(value,constant)=>Number.isFinite(value)&&value>=constant,ellipse=options=>{const defaults={center:[0,0],radius:[1,1],startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(radius,2))throw new Error("radius must be an array of X and Y values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,3))throw new Error("segments must be three or more");if(0===radius[0]||0===radius[1])return create$a();startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(radius[0],radius[1]);if(rotation{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius],ellipse({center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,segments:segments})},cuboid=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0,0],size:[2,2,2]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of width, depth and height values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");return 0===size[0]||0===size[1]||0===size[2]?create$8():create$8([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((info=>{const vertices=info[0].map((i=>[center[0]+size[0]/2*(2*!!(1&i)-1),center[1]+size[1]/2*(2*!!(2&i)-1),center[2]+size[2]/2*(2*!!(4&i)-1)]));return create$7(vertices)})))},cylinderElliptic=options=>{const defaults={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:TAU,segments:32};let{center:center,height:height,startRadius:startRadius,startAngle:startAngle,endRadius:endRadius,endAngle:endAngle,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGT(height,0))throw new Error("height must be greater then zero");if(!isNumberArray(startRadius,2))throw new Error("startRadius must be an array of X and Y values");if(!startRadius.every((n=>n>=0)))throw new Error("startRadius values must be positive");if(!isNumberArray(endRadius,2))throw new Error("endRadius must be an array of X and Y values");if(!endRadius.every((n=>n>=0)))throw new Error("endRadius values must be positive");if(endRadius.every((n=>0===n))&&startRadius.every((n=>0===n)))throw new Error("at least one radius must be positive");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minRadius=Math.min(startRadius[0],startRadius[1],endRadius[0],endRadius[1]),minAngle=Math.acos((minRadius*minRadius+minRadius*minRadius-EPS*EPS)/(2*minRadius*minRadius));if(rotation{const angle=slice*rotation+startAngle;return scale$3(v1,axisX,radius[0]*cos(angle)),scale$3(v2,axisY,radius[1]*sin(angle)),add$1(v1,v1,v2),scale$3(v3,ray,stack),add$1(v3,v3,start),add$1([0,0,0],v1,v3)},fromVertices=(...vertices)=>{const newVertices=vertices.map((vertex=>add$1([0,0,0],vertex,center)));return create$7(newVertices)},polygons=[];for(let i=0;i0&&startRadius[1]>0&&polygons.push(fromVertices(start,genVertex(0,t1,startRadius),genVertex(0,t0,startRadius))),(startRadius[0]>0||startRadius[1]>0)&&polygons.push(fromVertices(genVertex(0,t0,startRadius),genVertex(0,t1,startRadius),genVertex(1,t0,endRadius))),endRadius[0]>0&&endRadius[1]>0&&polygons.push(fromVertices(end,genVertex(1,t0,endRadius),genVertex(1,t1,endRadius))),(endRadius[0]>0||endRadius[1]>0)&&polygons.push(fromVertices(genVertex(1,t0,endRadius),genVertex(0,t1,startRadius),genVertex(1,t1,endRadius))))}return rotation{const{center:center,height:height,radius:radius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return 0===height||0===radius?create$8():cylinderElliptic({center:center,height:height,startRadius:[radius,radius],endRadius:[radius,radius],segments:segments})},ellipsoid=options=>{const{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(radius,3))throw new Error("radius must be an array of X, Y and Z values");if(!radius.every((n=>n>=0)))throw new Error("radius values must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===radius[0]||0===radius[1]||0===radius[2])return create$8();const xVector=scale$3([0,0,0],normalize$1([0,0,0],axes[0]),radius[0]),yVector=scale$3([0,0,0],normalize$1([0,0,0],axes[1]),radius[1]),zVector=scale$3([0,0,0],normalize$1([0,0,0],axes[2]),radius[2]),qSegments=Math.round(segments/4);let prevCylinderVertex;const polygons=[],p1=[0,0,0],p2=[0,0,0];for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(p1,xVector,cos(angle)),scale$3(p2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch;for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);if(slice2>0){let vertex,vertices=[];vertex=subtract$3([0,0,0],scale$3(p1,prevCylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),vertex=subtract$3([0,0,0],scale$3(p1,cylinderVertex,prevCosPitch),scale$3(p2,zVector,prevSinPitch)),vertices.push(add$1(vertex,vertex,center)),slice2{const defaults={points:[],faces:[],colors:void 0,orientation:"outward"},{points:points,faces:faces,colors:colors,orientation:orientation}=Object.assign({},defaults,options);if(!Array.isArray(points)||!Array.isArray(faces))throw new Error("points and faces must be arrays");if(points.length<3)throw new Error("three or more points are required");if(faces.length<1)throw new Error("one or more faces are required");if(colors){if(!Array.isArray(colors))throw new Error("colors must be an array");if(colors.length!==faces.length)throw new Error("faces and colors must have the same length")}points.forEach(((vertex,i)=>{if(!isNumberArray(vertex,3))throw new Error(`vertex ${i} must be an array of X, Y, Z values`)})),faces.forEach(((face,i)=>{if(face.length<3)throw new Error(`face ${i} must contain 3 or more indexes`);if(!isNumberArray(face,face.length))throw new Error(`face ${i} must be an array of numbers`)})),"outward"!==orientation&&faces.forEach((face=>face.reverse()));const polygons=faces.map(((face,findex)=>{const polygon=create$7(face.map((pindex=>points[pindex])));return colors&&colors[findex]&&(polygon.color=colors[findex]),polygon}));return create$8(polygons)},rectangle=options=>{const{center:center,size:size}=Object.assign({},{center:[0,0],size:[2,2]},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(0===size[0]||0===size[1])return create$a();const point=[size[0]/2,size[1]/2],swapped=[point[0],-point[1]],points=[subtract$1([0,0],center,point),add([0,0],center,swapped),add([0,0],center,point),subtract$1([0,0],center,swapped)];return create$a([points])},createCorners=(center,size,radius,segments,slice,positive)=>{const pitch=TAU/4*slice/segments,cosPitch=cos(pitch),sinPitch=sin(pitch),layerSegments=segments-slice;let layerRadius=radius*cosPitch,layerOffset=size[2]-(radius-radius*sinPitch);positive||(layerOffset=radius-radius*sinPitch-size[2]),layerRadius=layerRadius>EPS?layerRadius:0;const corner0=add$1([0,0,0],center,[size[0]-radius,size[1]-radius,layerOffset]),corner1=add$1([0,0,0],center,[radius-size[0],size[1]-radius,layerOffset]),corner2=add$1([0,0,0],center,[radius-size[0],radius-size[1],layerOffset]),corner3=add$1([0,0,0],center,[size[0]-radius,radius-size[1],layerOffset]),corner0Vertices=[],corner1Vertices=[],corner2Vertices=[],corner3Vertices=[];for(let i=0;i<=layerSegments;i++){const point2d=fromAngleRadians([0,0],layerSegments>0?TAU/4*i/layerSegments:0);scale$1(point2d,point2d,layerRadius);const point3d=fromVec2([0,0,0],point2d);corner0Vertices.push(add$1([0,0,0],corner0,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner1Vertices.push(add$1([0,0,0],corner1,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner2Vertices.push(add$1([0,0,0],corner2,point3d)),rotateZ$2(point3d,point3d,[0,0,0],TAU/4),corner3Vertices.push(add$1([0,0,0],corner3,point3d))}return positive?[corner0Vertices,corner1Vertices,corner2Vertices,corner3Vertices]:(corner0Vertices.reverse(),corner1Vertices.reverse(),corner2Vertices.reverse(),corner3Vertices.reverse(),[corner3Vertices,corner2Vertices,corner1Vertices,corner0Vertices])},stitchCorners=(previousCorners,currentCorners)=>{const polygons=[];for(let i=0;i{const polygons=[];for(let i=0;i{bottomCorners=(bottomCorners=[bottomCorners[3],bottomCorners[2],bottomCorners[1],bottomCorners[0]]).map((corner=>corner.slice().reverse()));const bottomVertices=[];bottomCorners.forEach((corner=>{corner.forEach((vertex=>bottomVertices.push(vertex)))}));const topVertices=[];topCorners.forEach((corner=>{corner.forEach((vertex=>topVertices.push(vertex)))}));const polygons=[];for(let i=0;i{let{center:center,radius:radius,segments:segments,axes:axes}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},options);if(!isGTE(radius,0))throw new Error("radius must be positive");return radius=[radius,radius,radius],ellipsoid({center:center,radius:radius,segments:segments,axes:axes})},getPoints=(vertices,radius,startAngle,center)=>{const a=TAU/vertices,points=[];for(let i=0;i{const{origin:origin,normal:normal}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},options),planeOfMirror=fromNormalAndPoint([0,0,0,0],normal,origin);if(Number.isNaN(planeOfMirror[0]))throw new Error("the given origin and normal do not define a proper plane");const matrix=mirrorByPlane([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],planeOfMirror),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?mirror(options,...object):object));return 1===results.length?results[0]:results},mirrorX=(...objects)=>mirror({normal:[1,0,0]},...objects),gcd=(a,b)=>a===b?a:a{const multiple=newLength/edges.length;if(1===multiple)return edges;const divisor=fromValues$3(multiple,multiple,multiple),newEdges=[];return edges.forEach((edge=>{const increment=subtract$3([0,0,0],edge[1],edge[0]);divide$1(increment,increment,divisor);let prev=edge[0];for(let i=1;i<=multiple;++i){const next=add$1([0,0,0],prev,increment);newEdges.push([prev,next]),prev=next}})),newEdges},EPSAREA=EPS*EPS/2*Math.sin(Math.PI/3),extrudeWalls=(slice0,slice1)=>{let edges0=toEdges(slice0),edges1=toEdges(slice1);if(edges0.length!==edges1.length){const newLength=(a=edges0.length,b=edges1.length,a*b/gcd(a,b));newLength!==edges0.length&&(edges0=repartitionEdges(newLength,edges0)),newLength!==edges1.length&&(edges1=repartitionEdges(newLength,edges1))}var a,b;const walls=[];return edges0.forEach(((edge0,i)=>{const edge1=edges1[i],poly0=create$7([edge0[0],edge0[1],edge1[1]]),poly0area=measureArea$2(poly0);Number.isFinite(poly0area)&&poly0area>EPSAREA&&walls.push(poly0);const poly1=create$7([edge0[0],edge1[1],edge1[0]]),poly1area=measureArea$2(poly1);Number.isFinite(poly1area)&&poly1area>EPSAREA&&walls.push(poly1)})),walls},defaultCallback=(progress,index,base)=>{let baseSlice=null;return isA$5(base)&&(baseSlice=fromGeom2(base)),isA$4(base)&&(baseSlice=fromVertices(toVertices$1(base))),0===progress||1===progress?transform$3(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[0,0,progress]),baseSlice):null},extrudeFromSlices=(options,base)=>{const defaults={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,callback:defaultCallback},{numberOfSlices:numberOfSlices,capStart:capStart,capEnd:capEnd,close:close,callback:generate}=Object.assign({},defaults,options);if(numberOfSlices<2)throw new Error("numberOfSlices must be 2 or more");const sMax=numberOfSlices-1;let startSlice=null,endSlice=null,prevSlice=null,polygons=[];for(let s=0;s{const defaults={segments:12,startAngle:0,angle:TAU,overflow:"cap"};let{segments:segments,startAngle:startAngle,angle:angle,overflow:overflow}=Object.assign({},defaults,options);if(segments<3)throw new Error("segments must be greater then 3");startAngle=Math.abs(startAngle)>TAU?startAngle%TAU:startAngle,angle=Math.abs(angle)>TAU?angle%TAU:angle;let endAngle=startAngle+angle;if(endAngle=Math.abs(endAngle)>TAU?endAngle%TAU:endAngle,endAnglesegments*anglePerSegment&&segments++}let shapeSides=toSides(geometry);if(0===shapeSides.length)return create$8();let sliceGeometry=geometry;const pointsWithNegativeX=shapeSides.filter((s=>s[0][0]<0)),pointsWithPositiveX=shapeSides.filter((s=>s[0][0]>=0));pointsWithNegativeX.length>0&&pointsWithPositiveX.length>0&&"cap"===overflow&&(pointsWithNegativeX.length>pointsWithPositiveX.length?(shapeSides=shapeSides.map((side=>{let point0=side[0],point1=side[1];return point0=[Math.min(point0[0],0),point0[1]],point1=[Math.min(point1[0],0),point1[1]],[point0,point1]})),sliceGeometry=fromSides(shapeSides),sliceGeometry=mirrorX(sliceGeometry)):pointsWithPositiveX.length>=pointsWithNegativeX.length&&(shapeSides=shapeSides.map((side=>{let point0=side[0],point1=side[1];return point0=[Math.max(point0[0],0),point0[1]],point1=[Math.max(point1[0],0),point1[1]],[point0,point1]})),sliceGeometry=fromSides(shapeSides)));const rotationPerSlice=totalRotation/segments,isCapped=Math.abs(totalRotation){let Zrotation=rotationPerSlice*index+startAngle;return totalRotation===TAU&&index===segments&&(Zrotation=startAngle),multiply$1(matrix,fromZRotation(matrix,Zrotation),fromXRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],TAU/4)),transform$3(matrix,base)}};const output=extrudeFromSlices(options,baseSlice);return geometry.color&&(output.color=geometry.color),output},rotate=(angles,...objects)=>{if(!Array.isArray(angles))throw new Error("angles must be an array");for(angles=angles.slice();angles.length<3;)angles.push(0);const yaw=angles[2],pitch=angles[1],roll=angles[0],matrix=fromTaitBryanRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],yaw,pitch,roll),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?rotate(angles,...object):object));return 1===results.length?results[0]:results},translate=(offset,...objects)=>{if(!Array.isArray(offset))throw new Error("offset must be an array");for(offset=offset.slice();offset.length<3;)offset.push(0);const matrix=fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offset),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?translate(offset,...object):object));return 1===results.length?results[0]:results},solveAngleFromSSS=(a,b,c)=>Math.acos((a*a+b*b-c*c)/(2*a*b)),solveSAS=values=>{const c=values[0],B=values[1],a=values[2],b=((a,C,b)=>C>NEPS?Math.sqrt(a*a+b*b-2*a*b*Math.cos(C)):Math.sqrt((a-b)*(a-b)+a*b*C*C*(1-C*C/12)))(c,B,a),A=solveAngleFromSSS(b,c,a),C=Math.PI-A-B;return createTriangle(A,B,C,a,b,c)},createTriangle=(A,B,C,a,b,c)=>{const p0=fromValues$2(0,0),p1=fromValues$2(c,0),p2=fromValues$2(a,0);return add(p2,rotate$1(p2,p2,[0,0],Math.PI-B),p1),create$a([[p0,p1,p2]])},simplex={height:14,32:[16],33:[10,5,21,5,7,void 0,5,2,4,1,5,0,6,1,5,2],34:[16,4,21,4,14,void 0,12,21,12,14],35:[21,11,25,4,-7,void 0,17,25,10,-7,void 0,4,12,18,12,void 0,3,6,17,6],36:[20,8,25,8,-4,void 0,12,25,12,-4,void 0,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],37:[24,21,21,3,0,void 0,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,void 0,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7],38:[26,23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2],39:[10,5,19,4,20,5,21,6,20,6,18,5,16,4,15],40:[14,11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7],41:[14,3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7],42:[16,8,21,8,9,void 0,3,18,13,12,void 0,13,18,3,12],43:[26,13,18,13,0,void 0,4,9,22,9],44:[10,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],45:[26,4,9,22,9],46:[10,5,2,4,1,5,0,6,1,5,2],47:[22,20,25,2,-7],48:[20,9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21],49:[20,6,17,8,18,11,21,11,0],50:[20,4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0],51:[20,5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],52:[20,13,21,3,7,18,7,void 0,13,21,13,0],53:[20,15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],54:[20,16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7],55:[20,17,21,7,0,void 0,3,21,17,21],56:[20,8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21],57:[20,16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3],58:[10,5,14,4,13,5,12,6,13,5,14,void 0,5,2,4,1,5,0,6,1,5,2],59:[10,5,14,4,13,5,12,6,13,5,14,void 0,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],60:[24,20,18,4,9,20,0],61:[26,4,12,22,12,void 0,4,6,22,6],62:[24,4,18,20,9,4,0],63:[18,3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,void 0,9,2,8,1,9,0,10,1,9,2],64:[27,18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,void 0,12,16,10,14,9,11,9,8,10,6,11,5,void 0,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,void 0,19,16,18,8,18,6,19,5],65:[18,9,21,1,0,void 0,9,21,17,0,void 0,4,7,14,7],66:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,void 0,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0],67:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5],68:[21,4,21,4,0,void 0,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0],69:[19,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11,void 0,4,0,17,0],70:[18,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11],71:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,void 0,13,8,18,8],72:[22,4,21,4,0,void 0,18,21,18,0,void 0,4,11,18,11],73:[8,4,21,4,0],74:[16,12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7],75:[21,4,21,4,0,void 0,18,21,4,7,void 0,9,12,18,0],76:[17,4,21,4,0,void 0,4,0,16,0],77:[24,4,21,4,0,void 0,4,21,12,0,void 0,20,21,12,0,void 0,20,21,20,0],78:[22,4,21,4,0,void 0,4,21,18,0,void 0,18,21,18,0],79:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21],80:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10],81:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,void 0,12,4,18,-2],82:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,void 0,11,11,18,0],83:[20,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],84:[16,8,21,8,0,void 0,1,21,15,21],85:[22,4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21],86:[18,1,21,9,0,void 0,17,21,9,0],87:[24,2,21,7,0,void 0,12,21,7,0,void 0,12,21,17,0,void 0,22,21,17,0],88:[20,3,21,17,0,void 0,17,21,3,0],89:[18,1,21,9,11,9,0,void 0,17,21,9,11],90:[20,17,21,3,0,void 0,3,21,17,21,void 0,3,0,17,0],91:[14,4,25,4,-7,void 0,5,25,5,-7,void 0,4,25,11,25,void 0,4,-7,11,-7],92:[14,0,21,14,-3],93:[14,9,25,9,-7,void 0,10,25,10,-7,void 0,3,25,10,25,void 0,3,-7,10,-7],94:[16,6,15,8,18,10,15,void 0,3,12,8,17,13,12,void 0,8,17,8,0],95:[16,0,-2,16,-2],96:[10,6,21,5,20,4,18,4,16,5,15,6,16,5,17],97:[19,15,14,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],98:[19,4,21,4,0,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],99:[18,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],100:[19,15,21,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],101:[18,3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],102:[12,10,21,8,21,6,20,5,17,5,0,void 0,2,14,9,14],103:[19,15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],104:[19,4,21,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],105:[8,3,21,4,20,5,21,4,22,3,21,void 0,4,14,4,0],106:[10,5,21,6,20,7,21,6,22,5,21,void 0,6,14,6,-3,5,-6,3,-7,1,-7],107:[17,4,21,4,0,void 0,14,14,4,4,void 0,8,8,15,0],108:[8,4,21,4,0],109:[30,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0,void 0,15,10,18,13,20,14,23,14,25,13,26,10,26,0],110:[19,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],111:[19,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14],112:[19,4,14,4,-7,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],113:[19,15,14,15,-7,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],114:[13,4,14,4,0,void 0,4,8,5,11,7,13,9,14,12,14],115:[17,14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3],116:[12,5,21,5,4,6,1,8,0,10,0,void 0,2,14,9,14],117:[19,4,14,4,4,5,1,7,0,10,0,12,1,15,4,void 0,15,14,15,0],118:[16,2,14,8,0,void 0,14,14,8,0],119:[22,3,14,7,0,void 0,11,14,7,0,void 0,11,14,15,0,void 0,19,14,15,0],120:[17,3,14,14,0,void 0,14,14,3,0],121:[16,2,14,8,0,void 0,14,14,8,0,6,-4,4,-6,2,-7,1,-7],122:[17,14,14,3,0,void 0,3,14,14,14,void 0,3,0,14,0],123:[14,9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,void 0,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,void 0,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7],124:[8,4,25,4,-7],125:[14,5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,void 0,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,void 0,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7],126:[24,3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,void 0,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]},defaultsVectorParams$1={xOffset:0,yOffset:0,font:simplex,height:14,extrudeOffset:0},vectorChar=(options,text)=>{const{xOffset:xOffset,yOffset:yOffset,font:font,height:height,extrudeOffset:extrudeOffset}=Object.assign({},defaultsVectorParams$1,options);if("string"!=typeof text||1!==text.length)throw new Error("text must be a single character");let code=text.charCodeAt(0);code&&font[code]||(code=63);const glyph=[].concat(font[code]),ratio=(height-extrudeOffset)/font.height,extrudeYOffset=extrudeOffset/2,width=glyph.shift()*ratio,paths=[];let polyline=[];for(let i=0,il=glyph.length;i{const{x:x,y:y}=Object.assign({x:0,y:0},options);return identity(matrix),translate$1(matrix,matrix,[x,y,0]),line.chars=line.chars.map((vchar=>(vchar.paths=vchar.paths.map((path=>transform$5(matrix,path))),vchar))),line},areAllShapesTheSameType=shapes=>{let previousType;for(const shape of shapes){let currentType=0;if(isA$5(shape)&&(currentType=1),isA$3(shape)&&(currentType=2),isA$2(shape)&&(currentType=3),previousType&¤tType!==previousType)return!1;previousType=currentType}return!0},coalesce=arr=>flattenHelper(arr,[]),flattenHelper=(arr,out)=>(Array.isArray(arr)?arr.forEach((child=>flattenHelper(child,out))):null!=arr&&void 0!==arr&&out.push(arr),out),DEFAULT_COMPARE=(a,b)=>a>b?1:a{const N=new Node$1(null,null);let l=N,r=N;for(;;){const cmp=comparator(i,t.key);if(cmp<0){if(null===t.left)break;if(comparator(i,t.left.key)<0){const y=t.left;if(t.left=y.right,y.right=t,null===(t=y).left)break}r.left=t,r=t,t=t.left}else{if(!(cmp>0))break;if(null===t.right)break;if(comparator(i,t.right.key)>0){const y=t.right;if(t.right=y.left,y.left=t,null===(t=y).right)break}l.right=t,l=t,t=t.right}}return l.right=t.left,r.left=t.right,t.left=N.right,t.right=N.left,t},insert=(i,data,t,comparator)=>{const node=new Node$1(i,data);if(null===t)return node.left=node.right=null,node;const cmp=comparator(i,(t=splay(i,t,comparator)).key);return cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>=0&&(node.right=t.right,node.left=t,t.right=null),node},split=(key,v,comparator)=>{let left=null,right=null;if(v){const cmp=comparator((v=splay(key,v,comparator)).key,key);0===cmp?(left=v.left,right=v.right):cmp<0?(right=v.right,v.right=null,left=v):(left=v.left,v.left=null,right=v)}return{left:left,right:right}},printRow=(root,prefix,isTail,out,printNode)=>{if(root){out(`${prefix}${isTail?"└── ":"├── "}${printNode(root)}\n`);const indent=prefix+(isTail?" ":"│ ");root.left&&printRow(root.left,indent,!1,out,printNode),root.right&&printRow(root.right,indent,!0,out,printNode)}};class Tree$1{constructor(comparator=DEFAULT_COMPARE){this._comparator=comparator,this._root=null,this._size=0}insert(key,data){return this._size++,this._root=insert(key,data,this._root,this._comparator),this._root}add(key,data){const node=new Node$1(key,data);null===this._root&&(node.left=node.right=null,this._size++,this._root=node);const comparator=this._comparator,t=splay(key,this._root,comparator),cmp=comparator(key,t.key);return 0===cmp?this._root=t:(cmp<0?(node.left=t.left,node.right=t,t.left=null):cmp>0&&(node.right=t.right,node.left=t,t.right=null),this._size++,this._root=node),this._root}remove(key){this._root=this._remove(key,this._root,this._comparator)}_remove(i,t,comparator){let x;return null===t?null:0===comparator(i,(t=splay(i,t,comparator)).key)?(null===t.left?x=t.right:(x=splay(i,t.left,comparator),x.right=t.right),this._size--,x):t}pop(){let node=this._root;if(node){for(;node.left;)node=node.left;return this._root=splay(node.key,this._root,this._comparator),this._root=this._remove(node.key,this._root,this._comparator),{key:node.key,data:node.data}}return null}findStatic(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return current;current=cmp<0?current.left:current.right}return null}find(key){return this._root&&(this._root=splay(key,this._root,this._comparator),0!==this._comparator(key,this._root.key))?null:this._root}contains(key){let current=this._root;const compare=this._comparator;for(;current;){const cmp=compare(key,current.key);if(0===cmp)return!0;current=cmp<0?current.left:current.right}return!1}forEach(visitor,ctx){let current=this._root;const Q=[];let done=!1;for(;!done;)null!==current?(Q.push(current),current=current.left):0!==Q.length?(current=Q.pop(),visitor.call(ctx,current),current=current.right):done=!0;return this}range(low,high,fn,ctx){const Q=[],compare=this._comparator;let cmp,node=this._root;for(;0!==Q.length||node;)if(node)Q.push(node),node=node.left;else{if(node=Q.pop(),cmp=compare(node.key,high),cmp>0)break;if(compare(node.key,low)>=0&&fn.call(ctx,node))return this;node=node.right}return this}keys(){const keys=[];return this.forEach((({key:key})=>keys.push(key))),keys}values(){const values=[];return this.forEach((({data:data})=>values.push(data))),values}min(){return this._root?this.minNode(this._root).key:null}max(){return this._root?this.maxNode(this._root).key:null}minNode(t=this._root){if(t)for(;t.left;)t=t.left;return t}maxNode(t=this._root){if(t)for(;t.right;)t=t.right;return t}at(index){let current=this._root,done=!1,i=0;const Q=[];for(;!done;)if(current)Q.push(current),current=current.left;else if(Q.length>0){if(current=Q.pop(),i===index)return current;i++,current=current.right}else done=!0;return null}next(d){let root=this._root,successor=null;if(d.right){for(successor=d.right;successor.left;)successor=successor.left;return successor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?(successor=root,root=root.left):root=root.right}return successor}prev(d){let root=this._root,predecessor=null;if(null!==d.left){for(predecessor=d.left;predecessor.right;)predecessor=predecessor.right;return predecessor}const comparator=this._comparator;for(;root;){const cmp=comparator(d.key,root.key);if(0===cmp)break;cmp<0?root=root.left:(predecessor=root,root=root.right)}return predecessor}clear(){return this._root=null,this._size=0,this}toList(){return toList(this._root)}load(keys,values=[],presort=!1){let size=keys.length;const comparator=this._comparator;if(presort&&sort(keys,values,0,size-1,comparator),null===this._root)this._root=loadRecursive(keys,values,0,size),this._size=size;else{const mergedList=mergeLists(this.toList(),createList(keys,values),comparator);size=this._size+size,this._root=sortedListToBST({head:mergedList},0,size)}return this}isEmpty(){return null===this._root}size(){return this._size}root(){return this._root}toString(printNode=(n=>String(n.key))){const out=[];return printRow(this._root,"",!0,(v=>out.push(v)),printNode),out.join("")}update(key,newKey,newData){const comparator=this._comparator;let{left:left,right:right}=split(key,this._root,comparator);comparator(key,newKey)<0?right=insert(newKey,newData,right,comparator):left=insert(newKey,newData,left,comparator),this._root=((left,right,comparator)=>null===right?left:(null===left||((right=splay(left.key,right,comparator)).left=left),right))(left,right,comparator)}split(key){return split(key,this._root,this._comparator)}*[Symbol.iterator](){let n=this.minNode();for(;n;)yield n,n=this.next(n)}}const loadRecursive=(keys,values,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),key=keys[middle],data=values[middle],node=new Node$1(key,data);return node.left=loadRecursive(keys,values,start,middle),node.right=loadRecursive(keys,values,middle+1,end),node}return null},createList=(keys,values)=>{const head=new Node$1(null,null);let p=head;for(let i=0;i{let current=root;const Q=[];let done=!1;const head=new Node$1(null,null);let p=head;for(;!done;)current?(Q.push(current),current=current.left):Q.length>0?(current=p=p.next=Q.pop(),current=current.right):done=!0;return p.next=null,head.next},sortedListToBST=(list,start,end)=>{const size=end-start;if(size>0){const middle=start+Math.floor(size/2),left=sortedListToBST(list,start,middle),root=list.head;return root.left=left,list.head=list.head.next,root.right=sortedListToBST(list,middle+1,end),root}return null},mergeLists=(l1,l2,compare)=>{const head=new Node$1(null,null);let p=head,p1=l1,p2=l2;for(;null!==p1&&null!==p2;)compare(p1.key,p2.key)<0?(p.next=p1,p1=p1.next):(p.next=p2,p2=p2.next),p=p.next;return null!==p1?p.next=p1:null!==p2&&(p.next=p2),head.next},sort=(keys,values,left,right,compare)=>{if(left>=right)return;const pivot=keys[left+right>>1];let i=left-1,j=right+1;for(;;){do{i++}while(compare(keys[i],pivot)<0);do{j--}while(compare(keys[j],pivot)>0);if(i>=j)break;let tmp=keys[i];keys[i]=keys[j],keys[j]=tmp,tmp=values[i],values[i]=values[j],values[j]=tmp}sort(keys,values,left,j,compare),sort(keys,values,j+1,right,compare)},computeFields=(event,prev,operation)=>{null===prev?(event.inOut=!1,event.otherInOut=!0):(event.isSubject===prev.isSubject?(event.inOut=!prev.inOut,event.otherInOut=prev.otherInOut):(event.inOut=!prev.otherInOut,event.otherInOut=prev.isVertical()?!prev.inOut:prev.inOut),prev&&(event.prevInResult=!inResult(prev,operation)||prev.isVertical()?prev.prevInResult:prev));const isInResult=inResult(event,operation);event.resultTransition=isInResult?determineResultTransition(event,operation):0},inResult=(event,operation)=>{switch(event.type){case 0:switch(operation){case 0:return!event.otherInOut;case 1:return event.otherInOut;case 2:return event.isSubject&&event.otherInOut||!event.isSubject&&!event.otherInOut;case 3:return!0}break;case 2:return 0===operation||1===operation;case 3:return 2===operation;case 1:return!1}return!1},determineResultTransition=(event,operation)=>{const thisIn=!event.inOut,thatIn=!event.otherInOut;let isIn;switch(operation){case 0:isIn=thisIn&&thatIn;break;case 1:isIn=thisIn||thatIn;break;case 3:isIn=thisIn^thatIn;break;case 2:isIn=event.isSubject?thisIn&&!thatIn:thatIn&&!thisIn}return isIn?1:-1};class SweepEvent{constructor(point,left,otherEvent,isSubject,edgeType){this.left=left,this.point=point,this.otherEvent=otherEvent,this.isSubject=isSubject,this.type=edgeType||0,this.inOut=!1,this.otherInOut=!1,this.prevInResult=null,this.resultTransition=0,this.otherPos=-1,this.outputContourId=-1,this.isExteriorRing=!0}isBelow(p){const p0=this.point,p1=this.otherEvent.point;return this.left?(p0[0]-p[0])*(p1[1]-p[1])-(p1[0]-p[0])*(p0[1]-p[1])>0:(p1[0]-p[0])*(p0[1]-p[1])-(p0[0]-p[0])*(p1[1]-p[1])>0}isAbove(p){return!this.isBelow(p)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return 0!==this.resultTransition}clone(){const copy=new SweepEvent(this.point,this.left,this.otherEvent,this.isSubject,this.type);return copy.contourId=this.contourId,copy.resultTransition=this.resultTransition,copy.prevInResult=this.prevInResult,copy.isExteriorRing=this.isExteriorRing,copy.inOut=this.inOut,copy.otherInOut=this.otherInOut,copy}}const signedArea=(p0,p1,p2)=>{const res=(ax=p0[0],ay=p0[1],bx=p1[0],by=p1[1],cx=p2[0],cy=p2[1],(ay-cy)*(bx-cx)-(ax-cx)*(by-cy));var ax,ay,bx,by,cx,cy;return res>0?-1:res<0?1:0},compareEvents=(e1,e2)=>{const p1=e1.point,p2=e2.point;return p1[0]>p2[0]?1:p1[0]p2[1]?1:-1:specialCases(e1,e2,p1)},specialCases=(e1,e2,p1,p2)=>e1.left!==e2.left?e1.left?1:-1:0!==signedArea(p1,e1.otherEvent.point,e2.otherEvent.point)?e1.isBelow(e2.otherEvent.point)?-1:1:!e1.isSubject&&e2.isSubject?1:-1,divideSegment=(se,p,queue)=>{const r=new SweepEvent(p,!1,se,se.isSubject),l=new SweepEvent(p,!0,se.otherEvent,se.isSubject);return r.contourId=l.contourId=se.contourId,compareEvents(l,se.otherEvent)>0&&(se.otherEvent.left=!0,l.left=!1),se.otherEvent.otherEvent=l,se.otherEvent=r,queue.push(l),queue.push(r),queue},crossProduct=(a,b)=>a[0]*b[1]-a[1]*b[0],possibleIntersection=(se1,se2,queue)=>{const inter=((a1,a2,b1,b2,noEndpointTouch)=>{const va=[a2[0]-a1[0],a2[1]-a1[1]],vb=[b2[0]-b1[0],b2[1]-b1[1]],toPoint=(p,s,d)=>[p[0]+s*d[0],p[1]+s*d[1]],e=[b1[0]-a1[0],b1[1]-a1[1]];let kross=crossProduct(va,vb),sqrKross=kross*kross;const sqrLenA=dot$1(va,va);if(sqrKross>0){const s=crossProduct(e,vb)/kross;if(s<0||s>1)return null;const t=crossProduct(e,va)/kross;return t<0||t>1?null:0===s||1===s?noEndpointTouch?null:[toPoint(a1,s,va)]:0===t||1===t?noEndpointTouch?null:[toPoint(b1,t,vb)]:[toPoint(a1,s,va)]}if(kross=crossProduct(e,va),sqrKross=kross*kross,sqrKross>0)return null;const sa=dot$1(va,e)/sqrLenA,sb=sa+dot$1(va,vb)/sqrLenA,smin=Math.min(sa,sb),smax=Math.max(sa,sb);return smin<=1&&smax>=0?1===smin?noEndpointTouch?null:[toPoint(a1,smin>0?smin:0,va)]:0===smax?noEndpointTouch?null:[toPoint(a1,smax<1?smax:1,va)]:noEndpointTouch&&0===smin&&1===smax?null:[toPoint(a1,smin>0?smin:0,va),toPoint(a1,smax<1?smax:1,va)]:null})(se1.point,se1.otherEvent.point,se2.point,se2.otherEvent.point),nIntersections=inter?inter.length:0;if(0===nIntersections)return 0;if(1===nIntersections&&(equals$6(se1.point,se2.point)||equals$6(se1.otherEvent.point,se2.otherEvent.point)))return 0;if(2===nIntersections&&se1.isSubject===se2.isSubject)return 0;if(1===nIntersections)return equals$6(se1.point,inter[0])||equals$6(se1.otherEvent.point,inter[0])||divideSegment(se1,inter[0],queue),equals$6(se2.point,inter[0])||equals$6(se2.otherEvent.point,inter[0])||divideSegment(se2,inter[0],queue),1;const events=[];let leftCoincide=!1,rightCoincide=!1;return equals$6(se1.point,se2.point)?leftCoincide=!0:1===compareEvents(se1,se2)?events.push(se2,se1):events.push(se1,se2),equals$6(se1.otherEvent.point,se2.otherEvent.point)?rightCoincide=!0:1===compareEvents(se1.otherEvent,se2.otherEvent)?events.push(se2.otherEvent,se1.otherEvent):events.push(se1.otherEvent,se2.otherEvent),leftCoincide&&rightCoincide||leftCoincide?(se2.type=1,se1.type=se2.inOut===se1.inOut?2:3,leftCoincide&&!rightCoincide&÷Segment(events[1].otherEvent,events[0].point,queue),2):rightCoincide?(divideSegment(events[0],events[1].point,queue),3):events[0]!==events[3].otherEvent?(divideSegment(events[0],events[1].point,queue),divideSegment(events[1],events[2].point,queue),3):(divideSegment(events[0],events[1].point,queue),divideSegment(events[3].otherEvent,events[2].point,queue),3)},compareSegments=(le1,le2)=>{if(le1===le2)return 0;if(0!==signedArea(le1.point,le1.otherEvent.point,le2.point)||0!==signedArea(le1.point,le1.otherEvent.point,le2.otherEvent.point))return equals$6(le1.point,le2.point)?le1.isBelow(le2.otherEvent.point)?-1:1:le1.point[0]===le2.point[0]?le1.point[1]le2.contourId?1:-1}return 1===compareEvents(le1,le2)?1:-1};class Contour{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return null==this.holeOf}}const nextPos=(pos,resultEvents,processed,origPos)=>{let newPos=pos+1;const p=resultEvents[pos].point;let p1;const length=resultEvents.length;for(newPosorigPos;)newPos--;return newPos},initializeContourFromContext=(event,contours,contourId)=>{const contour=new Contour;if(null!=event.prevInResult){const prevInResult=event.prevInResult,lowerContourId=prevInResult.outputContourId,lowerResultTransition=prevInResult.resultTransition;if(lowerContourId<0)contour.holeOf=null,contour.depth=0;else if(lowerResultTransition>0){const lowerContour=contours[lowerContourId];if(null!=lowerContour.holeOf){const parentContourId=lowerContour.holeOf;contours[parentContourId].holeIds.push(contourId),contour.holeOf=parentContourId,contour.depth=contours[lowerContourId].depth}else contours[lowerContourId].holeIds.push(contourId),contour.holeOf=lowerContourId,contour.depth=contours[lowerContourId].depth+1}else contour.holeOf=null,contour.depth=contours[lowerContourId].depth}else contour.holeOf=null,contour.depth=0;return contour},connectEdges=sortedEvents=>{const resultEvents=(sortedEvents=>{let event,i,len,tmp;const resultEvents=[];for(i=0,len=sortedEvents.length;i{processed[pos]=!0,pos=resultEvents.length)&&resultEvents[pos];);contours.push(contour)}return contours};class Queue{constructor(data,compare){if(this.data=data,this.length=this.data.length,this.compare=compare,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(item){this.data.push(item),this._up(this.length++)}pop(){if(0===this.length)return;const top=this.data[0],bottom=this.data.pop();return--this.length>0&&(this.data[0]=bottom,this._down(0)),top}peek(){return this.data[0]}_up(pos){const{data:data,compare:compare}=this,item=data[pos];for(;pos>0;){const parent=pos-1>>1,current=data[parent];if(compare(item,current)>=0)break;data[pos]=current,pos=parent}data[pos]=item}_down(pos){const{data:data,compare:compare}=this,halfLength=this.length>>1,item=data[pos];for(;pos=0)break;data[pos]=data[bestChild],pos=bestChild}data[pos]=item}}const max=Math.max,min=Math.min;let contourId=0;const processPolygon=(contourOrHole,isSubject,depth,queue,bbox,isExteriorRing)=>{const len=contourOrHole.length-1;let s1,s2,e1,e2;for(let i=0;i0?e2.left=!0:e1.left=!0;const x=s1[0],y=s1[1];bbox[0]=min(bbox[0],x),bbox[1]=min(bbox[1],y),bbox[2]=max(bbox[2],x),bbox[3]=max(bbox[3],y),queue.push(e1),queue.push(e2)}},EMPTY=[],toMartinez=geometry=>{const outlines=[];return toOutlines(geometry).forEach((outline=>{equals$6(outline[0],outline[outline.length-1])?outlines.push(outline):outlines.push([...outline,outline[0]])})),[outlines]},fromOutlines=outlines=>(outlines.forEach((outline=>{equals$6(outline[0],outline[outline.length-1])&&outline.pop()})),outlines=outlines.filter((o=>o.length>=3)),create$a(outlines)),boolean=(subjectGeom,clippingGeom,operation)=>{const subject=toMartinez(subjectGeom),clipping=toMartinez(clippingGeom);let trivial=((subject,clipping,operation)=>{let result=null;if(subject.length*clipping.length==0){if(0===operation)return EMPTY;2===operation?result=subject:1!==operation&&3!==operation||(result=0===subject.length?clipping:subject)}return result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,operation);if(trivial)return trivial;const sbbox=[1/0,1/0,-1/0,-1/0],cbbox=[1/0,1/0,-1/0,-1/0],eventQueue=((subject,clipping,sbbox,cbbox,operation)=>{const eventQueue=new Queue([],compareEvents);let polygonSet,isExteriorRing,i,ii,j,jj;for(i=0,ii=subject.length;i{let result=null;return(sbbox[0]>cbbox[2]||cbbox[0]>sbbox[2]||sbbox[1]>cbbox[3]||cbbox[1]>sbbox[3])&&(0===operation?result=EMPTY:2===operation?result=subject:1!==operation&&3!==operation||(result=subject.concat(clipping))),result===EMPTY?create$a():result?fromOutlines(result.flat()):null})(subject,clipping,sbbox,cbbox,operation),trivial)return trivial;const sortedEvents=((eventQueue,subject,clipping,sbbox,cbbox,operation)=>{const sweepLine=new Tree$1(compareSegments),sortedEvents=[],rightBound=Math.min(sbbox[2],cbbox[2]);let prev,next,begin;for(;0!==eventQueue.length;){let event=eventQueue.pop();if(sortedEvents.push(event),0===operation&&event.point[0]>rightBound||2===operation&&event.point[0]>sbbox[2])break;if(event.left){next=prev=sweepLine.insert(event),begin=sweepLine.minNode(),prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next);const prevEvent=prev?prev.key:null;let prevprevEvent;if(computeFields(event,prevEvent,operation),next&&2===possibleIntersection(event,next.key,eventQueue)&&(computeFields(event,prevEvent,operation),computeFields(next.key,event,operation)),prev&&2===possibleIntersection(prev.key,event,eventQueue)){let prevprev=prev;prevprev=prevprev!==begin?sweepLine.prev(prevprev):null,prevprevEvent=prevprev?prevprev.key:null,computeFields(prevEvent,prevprevEvent,operation),computeFields(event,prevEvent,operation)}}else event=event.otherEvent,next=prev=sweepLine.find(event),prev&&next&&(prev=prev!==begin?sweepLine.prev(prev):null,next=sweepLine.next(next),sweepLine.remove(event),next&&prev&&possibleIntersection(prev.key,next.key,eventQueue))}return sortedEvents})(eventQueue,0,0,sbbox,cbbox,operation),contours=connectEdges(sortedEvents),polygons=[];for(let i=0;i=0;k--)hole.push(holePoints[k]);rings.push(hole)}polygons.push(rings)}}return polygons?fromOutlines(polygons.flat()):create$a()},interpolateBetween2DPointsForY=(point1,point2,y)=>{let t,f1=y-point1[1],f2=point2[1]-point1[1];return f2<0&&(f1=-f1,f2=-f2),t=f1<=0?0:f1>=f2?1:f2<1e-10?.5:f1/f2,point1[0]+t*(point2[0]-point1[0])};class OrthonormalFormula{constructor(plane){this.plane=plane;const rightVector=orthogonal([0,0,0],plane);this.v=normalize$1(rightVector,cross$1(rightVector,plane,rightVector)),this.u=cross$1([0,0,0],this.v,plane),this.planeOrigin=scale$3([0,0,0],plane,plane[3]),this.basisMap=new Map}getProjectionMatrix(){return fromValues$4(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)}getInverseProjectionMatrix(){return fromValues$4(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,this.planeOrigin[0],this.planeOrigin[1],this.planeOrigin[2],1)}to2D(vertex){const point=fromValues$2(dot$2(vertex,this.u),dot$2(vertex,this.v));return this.basisMap.set(point,vertex),point}to3D(point){const original=this.basisMap.get(point);if(original)return original;const v1=scale$3([0,0,0],this.u,point[0]),v2=scale$3([0,0,0],this.v,point[1]),v3=add$1(v1,v1,this.planeOrigin);return add$1(v2,v2,v3)}}const insertSorted=(array,element,compareFunc)=>{let leftBound=0,rightBound=array.length;for(;rightBound>leftBound;){const testIndex=Math.floor((leftBound+rightBound)/2);compareFunc(element,array[testIndex])>0?leftBound=testIndex+1:rightBound=testIndex}array.splice(leftBound,0,element)},fnNumberSort=(a,b)=>a-b,retessellate=geometry=>{if(geometry.isRetesselated)return geometry;const polygons=toPolygons$1(geometry).map(((polygon,index)=>({vertices:polygon.vertices,plane:plane(polygon),index:index}))),classified=classifyPolygons(polygons),destPolygons=[];classified.forEach((group=>{if(Array.isArray(group)){const reTessellateCoplanarPolygons=(sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const destPolygons=[],numPolygons=sourcePolygons.length,plane$1=plane(sourcePolygons[0]),orthonormalFormula=new OrthonormalFormula(plane$1),polygonVertices2d=[],polygonTopVertexIndexes=[],topy2polygonIndexes=new Map,yCoordinateToPolygonIndexes=new Map,yCoordinateBins=new Map;for(let polygonIndex=0;polygonIndex0){let miny,maxy;for(let i=0;imaxy)&&(maxy=y);let polygonIndexes=yCoordinateToPolygonIndexes.get(y);polygonIndexes||(polygonIndexes={},yCoordinateToPolygonIndexes.set(y,polygonIndexes)),polygonIndexes[polygonIndex]=!0}if(miny>=maxy)vertices2d=[],numVertices=0,minIndex=-1;else{let polygonIndexes=topy2polygonIndexes.get(miny);polygonIndexes||(polygonIndexes=[],topy2polygonIndexes.set(miny,polygonIndexes)),polygonIndexes.push(polygonIndex)}}vertices2d.reverse(),minIndex=numVertices-minIndex-1,polygonVertices2d.push(vertices2d),polygonTopVertexIndexes.push(minIndex)}const yCoordinates=[];yCoordinateToPolygonIndexes.forEach(((polylist,y)=>yCoordinates.push(y))),yCoordinates.sort(fnNumberSort);let activePolygons=[],prevOutPolygonRow=[];for(let yIndex=0;yIndex=numVertices&&(nextLeftVertexIndex=0),vertices2d[nextLeftVertexIndex][1]!==yCoordinate)break;newLeftVertexIndex=nextLeftVertexIndex}let nextRightVertexIndex=newRightVertexIndex-1;if(nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),vertices2d[nextRightVertexIndex][1]===yCoordinate&&(newRightVertexIndex=nextRightVertexIndex),newLeftVertexIndex!==activePolygon.leftVertexIndex&&newLeftVertexIndex===newRightVertexIndex)activePolygons.splice(activePolygonIndex,1),--activePolygonIndex;else{activePolygon.leftVertexIndex=newLeftVertexIndex,activePolygon.rightVertexIndex=newRightVertexIndex,activePolygon.topLeft=vertices2d[newLeftVertexIndex],activePolygon.topRight=vertices2d[newRightVertexIndex];let nextLeftVertexIndex=newLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0),activePolygon.bottomLeft=vertices2d[nextLeftVertexIndex];let nextRightVertexIndex=newRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1),activePolygon.bottomRight=vertices2d[nextRightVertexIndex]}}}let nextYcoordinate;if(yIndex>=yCoordinates.length-1)activePolygons=[],nextYcoordinate=null;else{nextYcoordinate=Number(yCoordinates[yIndex+1]);const middleYcoordinate=.5*(yCoordinate+nextYcoordinate),startingPolygonIndexes=topy2polygonIndexes.get(yCoordinate);for(const polygonIndexKey in startingPolygonIndexes){const polygonIndex=startingPolygonIndexes[polygonIndexKey],vertices2d=polygonVertices2d[polygonIndex],numVertices=vertices2d.length,topVertexIndex=polygonTopVertexIndexes[polygonIndex];let topLeftVertexIndex=topVertexIndex;for(;;){let i=topLeftVertexIndex+1;if(i>=numVertices&&(i=0),vertices2d[i][1]!==yCoordinate)break;if(i===topVertexIndex)break;topLeftVertexIndex=i}let topRightVertexIndex=topVertexIndex;for(;;){let i=topRightVertexIndex-1;if(i<0&&(i=numVertices-1),vertices2d[i][1]!==yCoordinate)break;if(i===topLeftVertexIndex)break;topRightVertexIndex=i}let nextLeftVertexIndex=topLeftVertexIndex+1;nextLeftVertexIndex>=numVertices&&(nextLeftVertexIndex=0);let nextRightVertexIndex=topRightVertexIndex-1;nextRightVertexIndex<0&&(nextRightVertexIndex=numVertices-1);const newActivePolygon={polygonIndex:polygonIndex,leftVertexIndex:topLeftVertexIndex,rightVertexIndex:topRightVertexIndex,topLeft:vertices2d[topLeftVertexIndex],topRight:vertices2d[topRightVertexIndex],bottomLeft:vertices2d[nextLeftVertexIndex],bottomRight:vertices2d[nextRightVertexIndex]};insertSorted(activePolygons,newActivePolygon,((el1,el2)=>{const x1=interpolateBetween2DPointsForY(el1.topLeft,el1.bottomLeft,middleYcoordinate),x2=interpolateBetween2DPointsForY(el2.topLeft,el2.bottomLeft,middleYcoordinate);return x1>x2?1:x10){const prevOutPolygon=newOutPolygonRow[newOutPolygonRow.length-1],d1=distance(outPolygon.topLeft,prevOutPolygon.topRight),d2=distance(outPolygon.bottomLeft,prevOutPolygon.bottomRight);d10){const prevContinuedIndexes=new Set,matchedIndexes=new Set;for(let i=0;i=0)&&(rightLineContinues||d2>=0)&&(thisPolygon.outPolygon=prevPolygon.outPolygon,thisPolygon.leftLineContinues=leftLineContinues,thisPolygon.rightLineContinues=rightLineContinues,prevContinuedIndexes.add(ii));break}}}for(let ii=0;iiEPS&&prevPolygon.outPolygon.leftPoints.push(prevPolygon.bottomLeft),prevPolygon.outPolygon.leftPoints.reverse();const vertices3d=prevPolygon.outPolygon.rightPoints.concat(prevPolygon.outPolygon.leftPoints).map((point2d=>orthonormalFormula.to3D(point2d))),polygon=fromVerticesAndPlane(vertices3d,plane$1);polygon.vertices.length&&destPolygons.push(polygon)}}for(let i=0;iEPS&&thisPolygon.outPolygon.rightPoints.push(thisPolygon.topRight))}prevOutPolygonRow=newOutPolygonRow}return destPolygons})(group);destPolygons.push(...reTessellateCoplanarPolygons)}else destPolygons.push(group)}));const result=create$8(destPolygons);return result.isRetesselated=!0,result},classifyPolygons=polygons=>{let clusters=[polygons];const nonCoplanar=[];for(let component=3;component>=0;component--){const maybeCoplanar=[],tolerance=3===component?15e-9:NEPS;clusters.forEach((cluster=>{cluster.sort(byPlaneComponent(component,tolerance));let startIndex=0;for(let i=1;itolerance&&(i-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex,i)),startIndex=i);cluster.length-startIndex==1?nonCoplanar.push(cluster[startIndex]):maybeCoplanar.push(cluster.slice(startIndex))})),clusters=maybeCoplanar}const result=[];return clusters.forEach((cluster=>{cluster[0]&&(result[cluster[0].index]=cluster)})),nonCoplanar.forEach((polygon=>{result[polygon.index]=polygon})),result},byPlaneComponent=(component,tolerance)=>(a,b)=>a.plane[component]-b.plane[component]>tolerance?1:b.plane[component]-a.plane[component]>tolerance?-1:0;class Node{constructor(parent){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=parent}invert(){const queue=[this];let node;for(let i=0;i{treeNode.isRemoved()||treeNode.splitByPlane(plane,coplanarFrontNodes,backNodes,frontNodes,backNodes)})),node.front&&frontNodes.length>0&&stack.push({node:node.front,polygonTreeNodes:frontNodes});const numBackNodes=backNodes.length;if(node.back&&numBackNodes>0)stack.push({node:node.back,polygonTreeNodes:backNodes});else for(let i=0;i0&&tree.rootnode.clipPolygons(node.polygontreenodes,alsoRemoveCoplanarFront),node.front&&stack.push(node.front),node.back&&stack.push(node.back),node=stack.pop()}while(void 0!==node)}addPolygonTreeNodes(newPolygonTreeNodes){let current={node:this,polygonTreeNodes:newPolygonTreeNodes};const stack=[];do{const node=current.node,polygonTreeNodes=current.polygonTreeNodes,len=polygonTreeNodes.length;if(0===len){current=stack.pop();continue}if(!node.plane){let index=0;index=Math.floor(len/2);const bestPoly=polygonTreeNodes[index].getPolygon();node.plane=plane(bestPoly)}const frontNodes=[],backNodes=[];for(let i=0;i0&&(node.front||(node.front=new Node(node)),len===frontNodes.length&&0===backNodes.length?node.front.polygontreenodes=frontNodes:stack.push({node:node.front,polygonTreeNodes:frontNodes})),backNodes.length>0&&(node.back||(node.back=new Node(node)),len===backNodes.length&&0===frontNodes.length?node.back.polygontreenodes=backNodes:stack.push({node:node.back,polygonTreeNodes:backNodes})),current=stack.pop()}while(void 0!==current)}}const splitLineSegmentByPlane=(plane,p1,p2)=>{const direction=subtract$3([0,0,0],p2,p1);let lambda=(plane[3]-dot$2(plane,p1))/dot$2(plane,direction);return Number.isNaN(lambda)&&(lambda=0),lambda>1&&(lambda=1),lambda<0&&(lambda=0),scale$3(direction,direction,lambda),add$1(direction,p1,direction),direction};class PolygonTreeNode{constructor(parent,polygon){this.parent=parent,this.children=[],this.polygon=polygon,this.removed=!1}addPolygons(polygons){if(!this.isRootNode())throw new Error("Assertion failed");const _this=this;polygons.forEach((polygon=>{_this.addChild(polygon)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const parentschildren=this.parent.children,i=parentschildren.indexOf(this);if(i<0)throw new Error("Assertion failed");parentschildren.splice(i,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(result){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){if(this.children.length){const queue=[this.children];let i,j,l,node,nodes;for(i=0;i0?queue.push(node.children):node._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}else this._splitByPlane(plane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes)}_splitByPlane(splane,coplanarFrontNodes,coplanarBackNodes,frontNodes,backNodes){const polygon=this.polygon;if(polygon){const bound=measureBoundingSphere$1(polygon),sphereRadius=bound[3]+EPS,d=dot$2(splane,bound)-splane[3];if(d>sphereRadius)frontNodes.push(this);else if(d<-sphereRadius)backNodes.push(this);else{const splitResult=((splane,polygon)=>{const result={type:null,front:null,back:null},vertices=polygon.vertices,numVertices=vertices.length,pplane=plane(polygon);if(equals$5(pplane,splane))result.type=0;else{let hasFront=!1,hasBack=!1;const vertexIsBack=[],MINEPS=-EPS;for(let i=0;iEPS&&(hasFront=!0),t=numVertices&&(nextVertexIndex=0);const nextIsBack=vertexIsBack[nextVertexIndex];if(isback===nextIsBack)isback?backVertices.push(vertex):frontVertices.push(vertex);else{const nextPoint=vertices[nextVertexIndex],intersectionPoint=splitLineSegmentByPlane(splane,vertex,nextPoint);isback?(backVertices.push(vertex),backVertices.push(intersectionPoint),frontVertices.push(intersectionPoint)):(frontVertices.push(vertex),frontVertices.push(intersectionPoint),backVertices.push(intersectionPoint))}isback=nextIsBack}const EPS_SQUARED=EPS*EPS;if(backVertices.length>=3){let prevVertex=backVertices[backVertices.length-1];for(let vertexIndex=0;vertexIndex=3){let prevVertex=frontVertices[frontVertices.length-1];for(let vertexIndex=0;vertexIndex=3&&(result.front=fromVerticesAndPlane(frontVertices,pplane)),backVertices.length>=3&&(result.back=fromVerticesAndPlane(backVertices,pplane))}else result.type=3;else result.type=2;else{const t=dot$2(splane,pplane);result.type=t>=0?0:1}}return result})(splane,polygon);switch(splitResult.type){case 0:coplanarFrontNodes.push(this);break;case 1:coplanarBackNodes.push(this);break;case 2:frontNodes.push(this);break;case 3:backNodes.push(this);break;case 4:if(splitResult.front){const frontNode=this.addChild(splitResult.front);frontNodes.push(frontNode)}if(splitResult.back){const backNode=this.addChild(splitResult.back);backNodes.push(backNode)}}}}}addChild(polygon){const newChild=new PolygonTreeNode(this,polygon);return this.children.push(newChild),newChild}invertSub(){let children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let children=[this];const queue=[children];for(let i=0;i0&&queue.push(node.children),node.children=[]}}}toString(){let result="",children=[this];const queue=[children];let i,j,l,node;for(i=0;i0&&queue.push(node.children)}return result}}class Tree{constructor(polygons){this.polygonTree=new PolygonTreeNode,this.rootnode=new Node(null),polygons&&this.addPolygons(polygons)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(tree,alsoRemoveCoplanarFront=!1){this.rootnode.clipTo(tree,alsoRemoveCoplanarFront)}allPolygons(){const result=[];return this.polygonTree.getPolygons(result),result}addPolygons(polygons){const polygonTreeNodes=new Array(polygons.length);for(let i=0;i{if(0===geometry1.polygons.length||0===geometry2.polygons.length)return!1;const bounds1=measureBoundingBox(geometry1),min1=bounds1[0],max1=bounds1[1],bounds2=measureBoundingBox(geometry2),min2=bounds2[0],max2=bounds2[1];return!(min2[0]-max1[0]>EPS||min1[0]-max2[0]>EPS||min2[1]-max1[1]>EPS||min1[1]-max2[1]>EPS||min2[2]-max1[2]>EPS||min1[2]-max2[2]>EPS)},intersectGeom3=geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return create$8();const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),b.clipTo(a),b.invert(),a.clipTo(b),b.clipTo(a),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=retessellate(newGeometry),newGeometry},scission=(...objects)=>{const results=objects.map((object=>isA$3(object)?(geometry=>{const eps=measureEpsilon(geometry),polygons=toPolygons$1(geometry),pl=polygons.length,indexesPerVertex=new Map,temp=[0,0,0];polygons.forEach(((polygon,index)=>{polygon.vertices.forEach((vertex=>{((map,vertex,index)=>{const key=`${vertex}`,mapping=map.get(key);void 0===mapping?map.set(key,[index]):mapping.push(index)})(indexesPerVertex,snap$2(temp,vertex,eps),index)}))}));const indexesPerPolygon=polygons.map((polygon=>{let indexes=[];return polygon.vertices.forEach((vertex=>{indexes=indexes.concat(((map,vertex)=>{const key=`${vertex}`;return map.get(key)})(indexesPerVertex,snap$2(temp,vertex,eps)))})),{e:1,d:(array=indexes,array.sort(((a,b)=>a-b)).filter(((item,pos,ary)=>!pos||item!==ary[pos-1])))};var array}));indexesPerVertex.clear();let merges=0;const ippl=indexesPerPolygon.length;for(let i=0;i0){const indexes=new Array(pl);indexes[i]=!0;do{merges=0,indexes.forEach(((e,j)=>{const mapj=indexesPerPolygon[j];if(mapj.e>0){mapj.e=-1;for(let d=0;d0);mapi.indexes=indexes}}const newgeometries=[];for(let i=0;inewpolygons.push(polygons[p]))),newgeometries.push(create$8(newpolygons))}return newgeometries})(object):Array.isArray(object)?scission(...object):object));return 1===results.length?results[0]:results},subtractGeom3=geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=((geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return clone$7(geometry1);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.invert(),a.clipTo(b),b.clipTo(a,!0),a.addPolygons(b.allPolygons()),a.invert();const newPolygons=a.allPolygons();return create$8(newPolygons)})(newGeometry,geometry)})),newGeometry=retessellate(newGeometry),newGeometry},unionGeom2=geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,1)})),newGeometry},unionGeom3Sub=(geometry1,geometry2)=>{if(!mayOverlap(geometry1,geometry2))return unionForNonIntersecting(geometry1,geometry2);const a=new Tree(toPolygons$1(geometry1)),b=new Tree(toPolygons$1(geometry2));a.clipTo(b,!1),b.clipTo(a),b.invert(),b.clipTo(a),b.invert();const newPolygons=a.allPolygons().concat(b.allPolygons());return create$8(newPolygons)},unionForNonIntersecting=(geometry1,geometry2)=>{let newpolygons=toPolygons$1(geometry1);return newpolygons=newpolygons.concat(toPolygons$1(geometry2)),create$8(newpolygons)},union=(...geometries)=>{if(0===(geometries=coalesce(geometries)).length)return;if(!areAllShapesTheSameType(geometries))throw new Error("union arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return unionGeom2(geometries);if(isA$3(geometry))return(geometries=>{let i;for(i=1;i{let{offset:offset,twistAngle:twistAngle,twistSteps:twistSteps,repair:repair}=Object.assign({},{offset:[0,0,1],twistAngle:0,twistSteps:12,repair:!0},options);if(twistSteps<1)throw new Error("twistSteps must be 1 or more");0===twistAngle&&(twistSteps=1);const offsetV=clone$9(offset);let baseSlice=fromGeom2(geometry);offsetV[2]<0&&(baseSlice=reverse$2(baseSlice));const matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];options={numberOfSlices:twistSteps+1,capStart:!0,capEnd:!0,repair:repair,callback:(progress,index,base)=>{const Zrotation=index/twistSteps*twistAngle,Zoffset=scale$3([0,0,0],offsetV,index/twistSteps);return multiply$1(matrix,fromZRotation(matrix,Zrotation),fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],Zoffset)),transform$3(matrix,base)}};const output=extrudeFromSlices(options,baseSlice);return geometry.color&&(output.color=geometry.color),output},extrudeLinear=(options,...objects)=>{const{height:height,twistAngle:twistAngle,twistSteps:twistSteps,repair:repair}=Object.assign({},{height:1,twistAngle:0,twistSteps:1,repair:!0},options);options={offset:[0,0,height],twistAngle:twistAngle,twistSteps:twistSteps,repair:repair};const results=objects.map((object=>isA$2(object)?((options,geometry)=>{if(!geometry.isClosed)throw new Error("extruded path must be closed");const points=toPoints$1(geometry),geometry2=create$a([points]);return geometry.color&&(geometry2.color=geometry.color),extrudeLinearGeom2(options,geometry2)})(options,object):isA$5(object)?extrudeLinearGeom2(options,object):Array.isArray(object)?extrudeLinear(options,...object):object));return 1===results.length?results[0]:results},aboutEqualNormals=(a,b)=>Math.abs(a[0]-b[0])<=NEPS&&Math.abs(a[1]-b[1])<=NEPS&&Math.abs(a[2]-b[2])<=NEPS,project=(options,...objects)=>{const{axis:axis,origin:origin}=Object.assign({},{axis:[0,0,1],origin:[0,0,0]},options);options={axis:axis,origin:origin};const results=objects.map((object=>isA$3(object)?((options,geometry)=>{const projPlane=fromNormalAndPoint([0,0,0,0],options.axis,options.origin);if(Number.isNaN(projPlane[0])||Number.isNaN(projPlane[1])||Number.isNaN(projPlane[2])||Number.isNaN(projPlane[3]))throw new Error("project: invalid axis or origin");const epsilon=measureEpsilon(geometry),epsilonArea=epsilon*epsilon*Math.sqrt(3)/4;if(0===epsilon)return create$a();const polygons=toPolygons$1(geometry);let projPolys=[];for(let i=0;iprojectionOfPoint(projPlane,v))),newPoly=create$7(newVertices),newPlane=plane(newPoly);aboutEqualNormals(projPlane,newPlane)&&(measureArea$2(newPoly)transform$7(rotation,p)))}projPolys=projPolys.sort(((a,b)=>measureArea$2(b)-measureArea$2(a)));const projGeoms=projPolys.map((p=>{const cloned=p.vertices.map(clone$8);return create$a([cloned])})),output=unionGeom2(projGeoms);return geometry.color&&(output.color=geometry.color),output})(options,object):Array.isArray(object)?project(options,...object):object));return 1===results.length?results[0]:results},hullPoints2=uniquePoints=>{let min=fromValues$2(1/0,1/0);uniquePoints.forEach((point=>{(point[1]{const angle=fakeAtan2(point[1]-min[1],point[0]-min[0]),distSq=squaredDistance(point,min);points.push({point:point,angle:angle,distSq:distSq})})),points.sort(((pt1,pt2)=>pt1.angle!==pt2.angle?pt1.angle-pt2.angle:pt1.distSq-pt2.distSq));const stack=[];return points.forEach((point=>{let cnt=stack.length;for(;cnt>1&&ccw(stack[cnt-2],stack[cnt-1],point.point)<=Number.EPSILON;)stack.pop(),cnt=stack.length;stack.push(point.point)})),stack},ccw=(v1,v2,v3)=>(v2[0]-v1[0])*(v3[1]-v1[1])-(v2[1]-v1[1])*(v3[0]-v1[0]),fakeAtan2=(y,x)=>0===y&&0===x?-1/0:-x/y,toUniquePoints=geometries=>{const found=new Set,uniquePoints=[],addPoint=point=>{const key=point.toString();found.has(key)||(uniquePoints.push(point),found.add(key))};return geometries.forEach((geometry=>{isA$5(geometry)?toPoints$3(geometry).forEach(addPoint):isA$3(geometry)?toPoints$2(geometry).forEach((points=>points.forEach(addPoint))):isA$2(geometry)&&toPoints$1(geometry).forEach(addPoint)})),uniquePoints},hullPoints3=uniquePoints=>{const polygons=runner(uniquePoints,{skipTriangulation:!0}).map((face=>{const vertices=face.map((index=>uniquePoints[index]));return create$7(vertices)}));return polygons},hull=(...geometries)=>{if(0===(geometries=coalesce(geometries)).length)return;if(!areAllShapesTheSameType(geometries))throw new Error("only hulls of the same type are supported");const geometry=geometries[0];return isA$2(geometry)?(geometries=>{const unique=toUniquePoints(geometries),hullPoints=hullPoints2(unique);return fromPoints$2({closed:!0},hullPoints)})(geometries):isA$5(geometry)?(geometries=>{const unique=toUniquePoints(geometries),hullPoints=hullPoints2(unique);return hullPoints.length<3?create$a():create$a([hullPoints])})(geometries):isA$3(geometry)?(geometries=>{const unique=toUniquePoints(geometries);return 0===unique.length?create$8():create$8(hullPoints3(unique))})(geometries):geometry},snapPolygons=(epsilon,polygons)=>{let newPolygons=polygons.map((polygon=>{const snapVertices=polygon.vertices.map((vertex=>snap$2([0,0,0],vertex,epsilon))),newVertices=[];for(let i=0;i((epsilon,polygon)=>{const area=Math.abs(measureArea$2(polygon));return Number.isFinite(area)&&area>epsilon})(epsilonArea,polygon))),newPolygons},createEdges=polygon=>{const vertices=toVertices$1(polygon),edges=[];for(let i=0;i{const key=`${edge.v1}:${edge.v2}`;edges.set(key,edge)},deleteEdge=(edges,edge)=>{const key=`${edge.v1}:${edge.v2}`;edges.delete(key)},findOppositeEdge=(edges,edge)=>{const key=`${edge.v2}:${edge.v1}`;return edges.get(key)},calculateAnglesBetween=(current,opposite,normal)=>{let v0=current.prev.v1,v1=current.prev.v2,v2=opposite.next.v2;const angle1=calculateAngle(v0,v1,v2,normal);return v0=opposite.prev.v1,v1=opposite.prev.v2,v2=current.next.v2,[angle1,calculateAngle(v0,v1,v2,normal)]},v1=[0,0,0],v2=[0,0,0],calculateAngle=(prevVertex,midVertex,nextVertex,normal)=>{const d0=subtract$3(v1,midVertex,prevVertex),d1=subtract$3(v2,nextVertex,midVertex);return cross$1(d0,d0,d1),dot$2(d0,normal)},mergeCoplanarPolygons=sourcePolygons=>{if(sourcePolygons.length<2)return sourcePolygons;const normal=sourcePolygons[0].plane,polygons=sourcePolygons.slice(),edgeList=new Map;for(;polygons.length>0;){const polygon=polygons.shift(),edges=createEdges(polygon);for(let i=0;i=0&&angles[1]>=0){const edge1=opposite.next,edge2=current.next;current.prev.next=opposite.next,current.next.prev=opposite.prev,opposite.prev.next=current.next,opposite.next.prev=current.prev,current.v1=null,current.v2=null,current.next=null,current.prev=null,deleteEdge(edgeList,opposite),opposite.v1=null,opposite.v2=null,opposite.next=null,opposite.prev=null;const mergeEdges=(list,e1,e2)=>{const newEdge={v1:e2.v1,v2:e1.v2,next:e1.next,prev:e2.prev};e2.prev.next=newEdge,e1.next.prev=newEdge,deleteEdge(list,e1),e1.v1=null,e1.v2=null,e1.next=null,e1.prev=null,deleteEdge(list,e2),e2.v1=null,e2.v2=null,e2.next=null,e2.prev=null};0===angles[0]&&mergeEdges(edgeList,edge1,edge1.prev),0===angles[1]&&mergeEdges(edgeList,edge2,edge2.prev)}}else current.next&&insertEdge(edgeList,current)}}const destPolygons=[];return edgeList.forEach((edge=>{const polygon=(edge=>{let polygon;const vertices=[];for(;edge.next;){const next=edge.next;vertices.push(edge.v1),edge.v1=null,edge.v2=null,edge.next=null,edge.prev=null,edge=next}return vertices.length>0&&(polygon=create$7(vertices)),polygon})(edge);polygon&&destPolygons.push(polygon)})),edgeList.clear(),destPolygons},mergePolygons=(epsilon,polygons)=>{const polygonsPerPlane=[];polygons.forEach((polygon=>{const mapping=polygonsPerPlane.find((element=>{return plane1=element[0],plane2=plane(polygon),Math.abs(plane1[3]-plane2[3])<15e-8&&aboutEqualNormals(plane1,plane2);var plane1,plane2}));mapping?mapping[1].push(polygon):polygonsPerPlane.push([plane(polygon),[polygon]])}));let destPolygons=[];return polygonsPerPlane.forEach((mapping=>{const sourcePolygons=mapping[1],retesselatedPolygons=mergeCoplanarPolygons(sourcePolygons);destPolygons=destPolygons.concat(retesselatedPolygons)})),destPolygons},getTag=vertex=>`${vertex}`,addSide=(sideMap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),newSideTag=`${startTag}/${endTag}`,reverseSideTag=`${endTag}/${startTag}`;if(sideMap.has(reverseSideTag))return deleteSide(sideMap,vertextag2sidestart,vertextag2sideend,vertex1,vertex0,null),null;const newSideObj={vertex0:vertex0,vertex1:vertex1,polygonIndex:polygonIndex};return sideMap.has(newSideTag)?sideMap.get(newSideTag).push(newSideObj):sideMap.set(newSideTag,[newSideObj]),vertextag2sidestart.has(startTag)?vertextag2sidestart.get(startTag).push(newSideTag):vertextag2sidestart.set(startTag,[newSideTag]),vertextag2sideend.has(endTag)?vertextag2sideend.get(endTag).push(newSideTag):vertextag2sideend.set(endTag,[newSideTag]),newSideTag},deleteSide=(sidemap,vertextag2sidestart,vertextag2sideend,vertex0,vertex1,polygonIndex)=>{const startTag=getTag(vertex0),endTag=getTag(vertex1),sideTag=`${startTag}/${endTag}`;let idx=-1;const sideObjs=sidemap.get(sideTag);for(let i=0;i{const triangles=[];return polygons.forEach((polygon=>{((epsilon,polygon,triangles)=>{const nv=polygon.vertices.length;if(nv>3){if(nv>4){const midpoint=[0,0,0];polygon.vertices.forEach((vertex=>add$1(midpoint,midpoint,vertex))),snap$2(midpoint,divide$1(midpoint,midpoint,[nv,nv,nv]),epsilon);for(let i=0;i{const{snap:snap,simplify:simplify,triangulate:triangulate}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},options),epsilon=measureEpsilon(geometry);let polygons=toPolygons$1(geometry);snap&&(polygons=snapPolygons(epsilon,polygons)),simplify&&(polygons=mergePolygons(0,polygons)),triangulate&&(polygons=(polygons=>{const sideMap=new Map;for(let polygonIndex=0;polygonIndex=3){let vertex=polygon.vertices[0],vertexTag=getTag(vertex);for(let vertexIndex=0;vertexIndex0){const vertextag2sidestart=new Map,vertextag2sideend=new Map,sidesToCheck=new Map;for(const[sidetag,sideObjs]of sideMap)sidesToCheck.set(sidetag,!0),sideObjs.forEach((sideObj=>{const starttag=getTag(sideObj.vertex0),endtag=getTag(sideObj.vertex1);vertextag2sidestart.has(starttag)?vertextag2sidestart.get(starttag).push(sidetag):vertextag2sidestart.set(starttag,[sidetag]),vertextag2sideend.has(endtag)?vertextag2sideend.get(endtag).push(sidetag):vertextag2sideend.set(endtag,[sidetag])}));const newPolygons=polygons.slice(0);for(;0!==sideMap.size;){for(const sideTag of sideMap.keys())sidesToCheck.set(sideTag,!0);let doneSomething=!1;for(;;){const sideTags=Array.from(sidesToCheck.keys());if(0===sideTags.length)break;const sideTagToCheck=sideTags[0];let doneWithSide=!0;if(sideMap.has(sideTagToCheck)){const sideObj=sideMap.get(sideTagToCheck)[0];for(let directionIndex=0;directionIndex<2;directionIndex++){const startVertex=0===directionIndex?sideObj.vertex0:sideObj.vertex1,endVertex=0===directionIndex?sideObj.vertex1:sideObj.vertex0,startVertexTag=getTag(startVertex),endVertexTag=getTag(endVertex);let matchingSides=[];0===directionIndex?vertextag2sideend.has(startVertexTag)&&(matchingSides=vertextag2sideend.get(startVertexTag)):vertextag2sidestart.has(startVertexTag)&&(matchingSides=vertextag2sidestart.get(startVertexTag));for(let matchingSideIndex=0;matchingSideIndex0&&t<1){const closestVertex=scale$3([0,0,0],direction,t);if(add$1(closestVertex,closestVertex,startPos),squaredDistance$1(closestVertex,endPos){const results=geometries.map((geometry=>isA$2(geometry)||isA$5(geometry)?((options,geometry)=>geometry)(0,geometry):isA$3(geometry)?generalizeGeom3(options,geometry):Array.isArray(geometry)?generalize(options,...geometry):geometry));return 1===results.length?results[0]:results},snap=(...geometries)=>{const results=geometries.map((geometry=>isA$2(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry),newPoints=toPoints$1(geometry).map((point=>snap$1([0,0],point,epsilon)));return create$5(newPoints)})(geometry):isA$5(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry);let newOutlines=toOutlines(geometry).map((outline=>{let prev=snap$1([0,0],outline[outline.length-1],epsilon);const newOutline=[];return outline.forEach((point=>{const snapped=snap$1([0,0],point,epsilon);equals$6(prev,snapped)||newOutline.push(snapped),prev=snapped})),newOutline}));return newOutlines=newOutlines.filter((outline=>measureArea$1(create$3(outline)))),create$a(newOutlines)})(geometry):isA$3(geometry)?(geometry=>{const epsilon=measureEpsilon(geometry),polygons=toPolygons$1(geometry),newPolygons=snapPolygons(epsilon,polygons);return create$8(newPolygons)})(geometry):Array.isArray(geometry)?snap(...geometry):geometry));return 1===results.length?results[0]:results},offsetFromPoints=(options,points)=>{let{delta:delta,corners:corners,closed:closed,segments:segments}=Object.assign({},{delta:1,corners:"edge",closed:!1,segments:16},options);if(Math.abs(delta)0&&delta>=0||rotation<0&&delta<0;delta=Math.abs(delta);let previousSegment=null,newPoints=[];const newCorners=[],of=[0,0],n=points.length;for(let i=0;ipointIndex.set(point,index)));const line0=[0,1,0],line1=[0,1,0];newCorners.forEach((corner=>{fromPoints$1(line0,corner.s0[0],corner.s0[1]),fromPoints$1(line1,corner.s1[0],corner.s1[1]);const ip=intersectPointOfLines(line0,line1);if(Number.isFinite(ip[0])&&Number.isFinite(ip[1])){const p0=corner.s0[1],i=pointIndex.get(p0);newPoints[i]=ip,newPoints[(i+1)%newPoints.length]=void 0}else{const p0=corner.s1[0],i=pointIndex.get(p0);newPoints[i]=void 0}})),newPoints=newPoints.filter((p=>void 0!==p))}if("round"===corners){let cornerSegments=Math.floor(segments/4);const v0=[0,0];newCorners.forEach((corner=>{let rotation=angleRadians(subtract$1(v0,corner.s1[0],corner.c));if(rotation-=angleRadians(subtract$1(v0,corner.s0[1],corner.c)),orientation&&rotation<0&&(rotation+=Math.PI,rotation<0&&(rotation+=Math.PI)),!orientation&&rotation>0&&(rotation-=Math.PI,rotation>0&&(rotation-=Math.PI)),0!==rotation){cornerSegments=Math.floor(segments*(Math.abs(rotation)/TAU));const step=rotation/cornerSegments,start=angleRadians(subtract$1(v0,corner.s0[1],corner.c)),cornerPoints=[];for(let i=1;i0){const p0=corner.s0[1];let i=newPoints.findIndex((point=>equals$6(p0,point)));i=(i+1)%newPoints.length,newPoints.splice(i,0,...cornerPoints)}}else{const p0=corner.s1[0],i=newPoints.findIndex((point=>equals$6(p0,point)));newPoints.splice(i,1)}}))}return newPoints},mapPlaneToVertex=(map,vertex,plane)=>{const key=vertex.toString();if(map.has(key))map.get(key)[1].push(plane);else{const entry=[vertex,[plane]];map.set(key,entry)}},mapPlaneToEdge=(map,edge,plane)=>{const key0=edge[0].toString(),key1=edge[1].toString(),key=key0{map.findIndex((item=>item===angle))<0&&map.push(angle)},offsetShell=(options,geometry)=>{const{delta:delta,segments:segments}=Object.assign({},{delta:1,segments:12},options);let result=create$8();const vertices2planes=new Map,edges2planes=new Map,v1=[0,0,0],v2=[0,0,0];return toPolygons$1(geometry).forEach((polygon=>{const extrudeVector=scale$3([0,0,0],plane(polygon),2*delta),extrudedFace=((offsetVector,polygon1)=>{dot$2(plane(polygon1),offsetVector)>0&&(polygon1=invert$1(polygon1));const newPolygons=[polygon1],polygon2=transform$7(fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],offsetVector),polygon1),numVertices=polygon1.vertices.length;for(let i=0;i{const edge=item[0],planes=item[1],startVertex=edge[0],endVertex=edge[1],zBase=subtract$3([0,0,0],endVertex,startVertex);normalize$1(zBase,zBase);const xBase=planes[0],yBase=cross$1([0,0,0],xBase,zBase);let angles=[];for(let i=0;i=0&&distance$1(p1,prevP1)=0){startFaceVertices.push(p1),endFaceVertices.push(p2);const polygon=create$7([prevP2,p2,p1,prevP1]);polygons.push(polygon)}prevP1=p1,prevP2=p2}}endFaceVertices.reverse(),polygons.push(create$7(startFaceVertices)),polygons.push(create$7(endFaceVertices));const cylinder=create$8(polygons);result=unionGeom3Sub(result,cylinder)})),vertices2planes.forEach((item=>{const vertex=item[0],planes=item[1],xaxis=planes[0];let bestzaxis=null,bestzaxisOrthogonality=0;for(let i=1;i.05&&crossLength>bestzaxisOrthogonality&&(bestzaxisOrthogonality=crossLength,bestzaxis=normal)}bestzaxis||(bestzaxis=orthogonal(v1,xaxis));const yaxis=cross$1(v1,xaxis,bestzaxis);normalize$1(yaxis,yaxis);const zaxis=cross$1(v2,yaxis,xaxis),corner=sphere({center:[vertex[0],vertex[1],vertex[2]],radius:delta,segments:segments,axes:[xaxis,yaxis,zaxis]});result=unionGeom3Sub(result,corner)})),retessellate(result)},offsetPath2=(options,geometry)=>{const{delta:delta,corners:corners,segments:segments}=Object.assign({},{delta:1,corners:"edge",segments:16},options);if(delta<=0)throw new Error("the given delta must be positive for paths");if("edge"!==corners&&"chamfer"!==corners&&"round"!==corners)throw new Error('corners must be "edge", "chamfer", or "round"');const closed=geometry.isClosed,points=toPoints$1(geometry),paths={points:points,external:offsetFromPoints({delta:delta,corners:corners,segments:segments,closed:closed},points),internal:offsetFromPoints({delta:-delta,corners:corners,segments:segments,closed:closed},points)},output=geometry.isClosed?(paths=>{let{external:external,internal:internal}=paths;return external.length<2?create$a():(area$1(external)<0?external=external.reverse():internal=internal.reverse(),create$a([external,internal]))})(paths):((paths,segments,corners,delta)=>{const{points:points,external:external,internal:internal}=paths;if(0===points.length)return create$a();if(1===points.length)return circle({center:points[0],radius:delta});const capSegments=Math.floor(segments/2),e2iCap=[],i2eCap=[];if("round"===corners&&capSegments>0){const step=Math.PI/capSegments,eCorner=points[points.length-1],e2iStart=angleRadians(subtract$1([0,0],external[external.length-1],eCorner)),iCorner=points[0],i2eStart=angleRadians(subtract$1([0,0],internal[0],iCorner));for(let i=1;i{const results=objects.map((object=>isA$2(object)?offsetPath2(options,object):isA$5(object)?((options,geometry)=>{const{delta:delta,corners:corners,segments:segments,expandHoles:expandHoles}=Object.assign({},{delta:1,corners:"edge",segments:16,expandHoles:!1},options);if("edge"!==corners&&"chamfer"!==corners&&"round"!==corners)throw new Error('corners must be "edge", "chamfer", or "round"');if(!Number.isFinite(delta))throw new Error("delta must be a finite number");if("round"===corners&&!Number.isFinite(segments))throw new Error("segments must be a finite number");if("round"===corners&&!(segments>0))throw new Error("segments must be greater than zero");const outlines=toOutlines(geometry),newOutlines=outlines.map((outline=>{let outside=!0;if(expandHoles){const level=outlines.reduce(((acc,polygon)=>acc+arePointsInside(outline,create$3(polygon))),0);outside=level%2==0}return offsetFromPoints(options={delta:outside?delta:-delta,corners:corners,closed:!0,segments:segments},outline)})),output=create$a(newOutlines);return geometry.color&&(output.color=geometry.color),output})(options,object):isA$3(object)?((options,geometry)=>{const{delta:delta,corners:corners,segments:segments}=Object.assign({},{delta:1,corners:"round",segments:12},options);if("round"!==corners)throw new Error('corners must be "round" for 3D geometries');const expanded=offsetShell(options={delta:delta,corners:corners,segments:segments},geometry),output=union(geometry,expanded);return geometry.color&&(output.color=geometry.color),output})(options,object):Array.isArray(object)?offset(options,...object):object));return 1===results.length?results[0]:results},padArrayToLength=(anArray,padding,targetLength)=>{for(anArray=anArray.slice();anArray.length{const bounds=measureAggregateBoundingBox(geometries),translation=[0,0,0];for(let i=0;i<3;i++)"center"===modes[i]?translation[i]=relativeTo[i]-(bounds[0][i]+bounds[1][i])/2:"max"===modes[i]?translation[i]=relativeTo[i]-bounds[1][i]:"min"===modes[i]&&(translation[i]=relativeTo[i]-bounds[0][i]);return translate(translation,geometries)},centerGeometry=(options,object)=>{const{axes:axes,relativeTo:relativeTo}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},options),bounds=measureAggregateBoundingBox(object),offset=[0,0,0];return axes[0]&&(offset[0]=relativeTo[0]-(bounds[0][0]+(bounds[1][0]-bounds[0][0])/2)),axes[1]&&(offset[1]=relativeTo[1]-(bounds[0][1]+(bounds[1][1]-bounds[0][1])/2)),axes[2]&&(offset[2]=relativeTo[2]-(bounds[0][2]+(bounds[1][2]-bounds[0][2])/2)),translate(offset,object)},center=(options,...objects)=>{const{axes:axes,relativeTo:relativeTo}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},options);if(3!==relativeTo.length)throw new Error("relativeTo must be an array of length 3");options={axes:axes,relativeTo:relativeTo};const results=objects.map((object=>isA$2(object)||isA$5(object)||isA$3(object)||Array.isArray(object)?centerGeometry(options,object):object));return 1===results.length?results[0]:results},scale=(factors,...objects)=>{if(!Array.isArray(factors))throw new Error("factors must be an array");for(factors=factors.slice();factors.length<3;)factors.push(1);if(factors[0]<=0||factors[1]<=0||factors[2]<=0)throw new Error("factors must be positive");const matrix=fromScaling([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],factors),results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?scale(factors,...object):object));return 1===results.length?results[0]:results},transform=(matrix,...objects)=>{const results=objects.map((object=>isA$2(object)?transform$5(matrix,object):isA$5(object)?transform$a(matrix,object):isA$3(object)?transform$6(matrix,object):Array.isArray(object)?transform(matrix,...object):object));return 1===results.length?results[0]:results};exports.EPS=EPS,exports.NEPS=NEPS,exports.TAU=TAU,exports.align=(options,...geometries)=>{options=(options=>{if(!Array.isArray(options.modes)||options.modes.length>3)throw new Error("align(): modes must be an array of length <= 3");if(options.modes=padArrayToLength(options.modes,"none",3),3!==options.modes.filter((mode=>["center","max","min","none"].includes(mode))).length)throw new Error('align(): all modes must be one of "center", "max" or "min"');if(!Array.isArray(options.relativeTo)||options.relativeTo.length>3)throw new Error("align(): relativeTo must be an array of length <= 3");if(options.relativeTo=padArrayToLength(options.relativeTo,0,3),3!==options.relativeTo.filter((alignVal=>Number.isFinite(alignVal)||null==alignVal)).length)throw new Error("align(): all relativeTo values must be a number, or null.");if("boolean"!=typeof options.grouped)throw new Error("align(): grouped must be a boolean value.");return options})(options=Object.assign({},{modes:["center","center","min"],relativeTo:[0,0,0],grouped:!1},options));let{modes:modes,relativeTo:relativeTo,grouped:grouped}=options;if(relativeTo.filter((val=>null==val)).length){const bounds=measureAggregateBoundingBox(geometries);relativeTo=((relativeTo,modes,bounds)=>{for(let i=0;i<3;i++)null==relativeTo[i]&&("center"===modes[i]?relativeTo[i]=(bounds[0][i]+bounds[1][i])/2:"max"===modes[i]?relativeTo[i]=bounds[1][i]:"min"===modes[i]&&(relativeTo[i]=bounds[0][i]));return relativeTo})(relativeTo,modes,bounds)}return grouped?(geometries=coalesce(geometries),geometries=alignGeometries(geometries,modes,relativeTo)):geometries=geometries.map((geometry=>alignGeometries(geometry,modes,relativeTo))),1===geometries.length?geometries[0]:geometries},exports.arc=options=>{const defaults={center:[0,0],radius:1,startAngle:0,endAngle:TAU,makeTangent:!1,segments:32};let{center:center,radius:radius,startAngle:startAngle,endAngle:endAngle,makeTangent:makeTangent,segments:segments}=Object.assign({},defaults,options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGT(radius,0))throw new Error("radius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGTE(endAngle,0))throw new Error("endAngle must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");startAngle%=TAU,endAngle%=TAU;let rotation=TAU;startAngleendAngle&&(rotation=endAngle+(TAU-startAngle));const minAngle=Math.acos((radius*radius+radius*radius-EPS*EPS)/(2*radius*radius)),centerV=clone$8(center);let point;const pointArray=[];if(rotation.25&&(edgeStepSize=.25);const totalSteps=makeTangent?numSteps+2:numSteps;for(let i=0;i<=totalSteps;i++){let step=i;makeTangent&&(step=(i-1)*(numSteps-2*edgeStepSize)/numSteps+edgeStepSize,step<0&&(step=0),step>numSteps&&(step=numSteps)),point=fromAngleRadians([0,0],startAngle+step*(rotation/numSteps)),scale$1(point,point,radius),add(point,point,centerV),pointArray.push(point)}}return fromPoints$2({closed:!1},pointArray)},exports.area=area$1,exports.bezier=index$4,exports.center=center,exports.centerX=(...objects)=>center({axes:[!0,!1,!1]},...objects),exports.centerY=(...objects)=>center({axes:[!1,!0,!1]},...objects),exports.centerZ=(...objects)=>center({axes:[!1,!1,!0]},...objects),exports.circle=circle,exports.colorNameToRgb=s=>cssColors[s.toLowerCase()],exports.colorize=colorize,exports.cos=cos,exports.cssColors=cssColors,exports.cube=options=>{let{center:center,size:size}=Object.assign({},{center:[0,0,0],size:2},options);if(!isGTE(size,0))throw new Error("size must be positive");return size=[size,size,size],cuboid({center:center,size:size})},exports.cuboid=cuboid,exports.cylinder=cylinder,exports.cylinderElliptic=cylinderElliptic,exports.degToRad=degrees=>.017453292519943295*degrees,exports.ellipse=ellipse,exports.ellipsoid=ellipsoid,exports.extrudeFromSlices=extrudeFromSlices,exports.extrudeHelical=(options,geometry)=>{const defaults={angle:TAU,startAngle:0,pitch:10,endOffset:0,segmentsPerRotation:32},{angle:angle,endOffset:endOffset,segmentsPerRotation:segmentsPerRotation,startAngle:startAngle}=Object.assign({},defaults,options);let pitch;if(pitch=!options.pitch&&options.height?options.height/(angle/TAU):options.pitch?options.pitch:defaults.pitch,segmentsPerRotation<3)throw new Error("The number of segments per rotation needs to be at least 3.");let baseSlice=fromGeom2(geometry);measureBoundingBox(geometry)[1][0]<=0&&(baseSlice=reverse$2(baseSlice));const calculatedSegments=Math.round(segmentsPerRotation/TAU*Math.abs(angle)),segments=calculatedSegments>=2?calculatedSegments:2,step1=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];let matrix;return extrudeFromSlices({numberOfSlices:segments+1,callback:(progress,index,base)=>{const zRotation=startAngle+angle/segments*index;return multiply$1(step1,fromTranslation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],[endOffset/segments*index,0,(zRotation-startAngle)/TAU*pitch*Math.sign(angle)]),fromXRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],-TAU/4*Math.sign(angle))),matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],multiply$1(matrix,fromZRotation([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],zRotation),step1),transform$3(matrix,baseSlice)}},baseSlice)},exports.extrudeLinear=extrudeLinear,exports.extrudeRotate=extrudeRotate,exports.flatten=flatten,exports.generalize=generalize,exports.geodesicSphere=options=>{let{radius:radius,frequency:frequency}=Object.assign({},{radius:1,frequency:6},options);if(!isGTE(radius,0))throw new Error("radius must be positive");if(!isGTE(frequency,6))throw new Error("frequency must be six or more");if(0===radius)return create$8();frequency=Math.floor(frequency/6);const ci=[[.850651,0,-.525731],[.850651,-0,.525731],[-.850651,-0,.525731],[-.850651,0,-.525731],[0,-.525731,.850651],[0,.525731,.850651],[0,.525731,-.850651],[0,-.525731,-.850651],[-.525731,-.850651,-0],[.525731,-.850651,-0],[.525731,.850651,0],[-.525731,.850651,0]],ti=[[0,9,1],[1,10,0],[6,7,0],[10,6,0],[7,9,0],[5,1,4],[4,1,9],[5,10,1],[2,8,3],[3,11,2],[2,5,4],[4,8,2],[2,11,5],[3,7,6],[6,11,3],[8,7,3],[9,8,4],[11,10,5],[10,11,6],[8,9,7]],geodesicSubDivide=(p,frequency,offset)=>{const p1=p[0],p2=p[1],p3=p[2];let n=offset;const c=[],f=[];for(let i=0;i{const _f=1-f,c=[];for(let i=0;i<3;i++)c[i]=a[i]*_f+b[i]*f;return c};let vertices=[],faces=[],offset=0;for(let i=0;i{if((notation=notation.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const r=parseInt(notation.substring(0,2),16)/255,g=parseInt(notation.substring(2,4),16)/255,b=parseInt(notation.substring(4,6),16)/255;return notation.length>=8?[r,g,b,parseInt(notation.substring(6,8),16)/255]:[r,g,b]},exports.hslToRgb=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain H, S and L values");const h=values[0],s=values[1],l=values[2];let r=l,g=l,b=l;if(0!==s){const q=l<.5?l*(1+s):l+s-l*s,p=2*l-q;r=hueToColorComponent(p,q,h+1/3),g=hueToColorComponent(p,q,h),b=hueToColorComponent(p,q,h-1/3)}return values.length>3?[r,g,b,values[3]]:[r,g,b]},exports.hsvToRgb=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain H, S and V values");const h=values[0],s=values[1],v=values[2];let r=0,g=0,b=0;const i=Math.floor(6*h),f=6*h-i,p=v*(1-s),q=v*(1-f*s),t=v*(1-(1-f)*s);switch(i%6){case 0:r=v,g=t,b=p;break;case 1:r=q,g=v,b=p;break;case 2:r=p,g=v,b=t;break;case 3:r=p,g=q,b=v;break;case 4:r=t,g=p,b=v;break;case 5:r=v,g=p,b=q}return values.length>3?[r,g,b,values[3]]:[r,g,b]},exports.hueToColorComponent=hueToColorComponent,exports.hull=hull,exports.hullChain=(...geometries)=>{if(0===(geometries=coalesce(geometries)).length)return;if(1===geometries.length)return geometries[0];if(!areAllShapesTheSameType(geometries))throw new Error("only hulls of the same type are supported");const hulls=[];for(let i=1;i{if(0===(geometries=coalesce(geometries)).length)return;if(!areAllShapesTheSameType(geometries))throw new Error("intersect arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return(geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,0)})),newGeometry})(geometries);if(isA$3(geometry))return intersectGeom3(geometries);throw new Error("intersect unsupported geometry type")},exports.line=points=>{if(!Array.isArray(points))throw new Error("points must be an array");return fromPoints$2({},points)},exports.line2=index$1,exports.line3=index,exports.mat4=index$c,exports.measureAggregateArea=(...geometries)=>{geometries=flatten(geometries);const areas=measureArea(geometries);return 1===geometries.length?areas:areas.reduce(((result,area)=>result+area),0)},exports.measureAggregateBoundingBox=measureAggregateBoundingBox,exports.measureAggregateEpsilon=(...geometries)=>{geometries=flatten(geometries);const bounds=measureAggregateBoundingBox(geometries);let dimensions=0;return dimensions=geometries.reduce(((dimensions,geometry)=>isA$2(geometry)||isA$5(geometry)?Math.max(dimensions,2):isA$3(geometry)?Math.max(dimensions,3):0),dimensions),calculateEpsilonFromBounds(bounds,dimensions)},exports.measureAggregateVolume=(...geometries)=>{geometries=flatten(geometries);const volumes=measureVolume(geometries);return 1===geometries.length?volumes:volumes.reduce(((result,volume)=>result+volume),0)},exports.measureArea=measureArea,exports.measureBoundingBox=measureBoundingBox,exports.measureBoundingSphere=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$2(geometry)?measureCached(geometry,measureBoundingSphereOfPath2):isA$5(geometry)?measureCached(geometry,measureBoundingSphereOfGeom2):isA$3(geometry)?measureCached(geometry,measureBoundingSphereOfGeom3):isA(geometry)?measureCached(geometry,measureBoundingSphereOfSlice):[[0,0,0],0]));return 1===results.length?results[0]:results},exports.measureCenter=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>{const bounds=measureBoundingBox(geometry);return[bounds[0][0]+(bounds[1][0]-bounds[0][0])/2,bounds[0][1]+(bounds[1][1]-bounds[0][1])/2,bounds[0][2]+(bounds[1][2]-bounds[0][2])/2]}));return 1===results.length?results[0]:results},exports.measureCenterOfMass=(...geometries)=>{const results=(geometries=flatten(geometries)).map((geometry=>isA$5(geometry)?(geometry=>{let centerOfMass=cacheOfCenterOfMass.get(geometry);if(void 0!==centerOfMass)return centerOfMass;const sides=toSides(geometry);let area=0,x=0,y=0;if(sides.length>0){for(let i=0;i{let centerOfMass=cacheOfCenterOfMass.get(geometry);if(void 0!==centerOfMass)return centerOfMass;centerOfMass=[0,0,0];const polygons=toPolygons$1(geometry);if(0===polygons.length)return centerOfMass;let totalVolume=0;const vector=[0,0,0];return polygons.forEach((polygon=>{const vertices=polygon.vertices;for(let i=0;i{const results=(geometries=flatten(geometries)).map((geometry=>{const boundingBox=measureBoundingBox(geometry);return[boundingBox[1][0]-boundingBox[0][0],boundingBox[1][1]-boundingBox[0][1],boundingBox[1][2]-boundingBox[0][2]]}));return 1===results.length?results[0]:results},exports.measureEpsilon=measureEpsilon,exports.measureVolume=measureVolume,exports.mirror=mirror,exports.mirrorX=mirrorX,exports.mirrorY=(...objects)=>mirror({normal:[0,1,0]},...objects),exports.mirrorZ=(...objects)=>mirror({normal:[0,0,1]},...objects),exports.offset=offset,exports.offsetFromPoints=offsetFromPoints,exports.path2=index$5,exports.plane=index$9,exports.poly2=index$3,exports.poly3=index$7,exports.polygon=options=>{const{points:points,paths:paths,orientation:orientation}=Object.assign({},{points:[],paths:[],orientation:"counterclockwise"},options);if(!Array.isArray(points)||!Array.isArray(paths))throw new Error("points and paths must be arrays");let listOfPolys=points;Array.isArray(points[0])&&(Array.isArray(points[0][0])||(listOfPolys=[points])),listOfPolys.forEach(((list,i)=>{if(!Array.isArray(list))throw new Error("list of points "+i+" must be an array");if(list.length<3)throw new Error("list of points "+i+" must contain three or more points");list.forEach(((point,j)=>{if(!Array.isArray(point))throw new Error("list of points "+i+", point "+j+" must be an array");if(point.length<2)throw new Error("list of points "+i+", point "+j+" must contain by X and Y values")}))}));let listOfPaths=paths;if(0===paths.length){let count=0;listOfPaths=listOfPolys.map((list=>list.map((point=>count++))))}const allPoints=[];listOfPolys.forEach((list=>list.forEach((point=>allPoints.push(point)))));const outlines=[];listOfPaths.forEach((path=>{const setOfPoints=path.map((index=>allPoints[index]));outlines.push(setOfPoints)}));let geometry=create$a(outlines);return"clockwise"===orientation&&(geometry=reverse$5(geometry)),geometry},exports.polyhedron=polyhedron,exports.project=project,exports.radToDeg=radians=>57.29577951308232*radians,exports.radiusToSegments=(radius,minimumLength,minimumAngle)=>{const ss=minimumLength>0?radius*TAU/minimumLength:0,as=minimumAngle>0?TAU/minimumAngle:0;return Math.ceil(Math.max(ss,as,4))},exports.rectangle=rectangle,exports.retessellate=retessellate,exports.rgbToHex=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=255*values[0],g=255*values[1],b=255*values[2];let s=`#${Number(16777216+65536*r+256*g+b).toString(16).substring(1,7)}`;return values.length>3&&(s+=Number(255*values[3]).toString(16)),s},exports.rgbToHsl=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=values[0],g=values[1],b=values[2],max=Math.max(r,g,b),min=Math.min(r,g,b);let h,s;const l=(max+min)/2;if(max===min)h=s=0;else{const d=max-min;switch(s=l>.5?d/(2-max-min):d/(max+min),max){case r:h=(g-b)/d+(g3?[h,s,l,values[3]]:[h,s,l]},exports.rgbToHsv=(...values)=>{if((values=flatten(values)).length<3)throw new Error("values must contain R, G and B values");const r=values[0],g=values[1],b=values[2],max=Math.max(r,g,b),min=Math.min(r,g,b);let h;const v=max,d=max-min,s=0===max?0:d/max;if(max===min)h=0;else{switch(max){case r:h=(g-b)/d+(g3?[h,s,v,values[3]]:[h,s,v]},exports.rotate=rotate,exports.rotateX=(angle,...objects)=>rotate([angle,0,0],...objects),exports.rotateY=(angle,...objects)=>rotate([0,angle,0],...objects),exports.rotateZ=(angle,...objects)=>rotate([0,0,angle],...objects),exports.roundedCuboid=options=>{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0,0],size:[2,2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isNumberArray(size,3))throw new Error("size must be an array of X, Y and Z values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1]||0===size[2])return create$8();if(0===roundRadius)return cuboid({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS||roundRadius>size[2]-EPS)throw new Error("roundRadius must be smaller than the radius of all dimensions");segments=Math.floor(segments/4);let prevCornersPos=null,prevCornersNeg=null,polygons=[];for(let slice=0;slice<=segments;slice++){const cornersPos=createCorners(center,size,roundRadius,segments,slice,!0),cornersNeg=createCorners(center,size,roundRadius,segments,slice,!1);if(0===slice&&(polygons=polygons.concat(stitchSides(cornersNeg,cornersPos))),prevCornersPos&&(polygons=polygons.concat(stitchCorners(prevCornersPos,cornersPos),stitchWalls(prevCornersPos,cornersPos))),prevCornersNeg&&(polygons=polygons.concat(stitchCorners(prevCornersNeg,cornersNeg),stitchWalls(prevCornersNeg,cornersNeg))),slice===segments){let vertices=cornersPos.map((corner=>corner[0]));polygons.push(create$7(vertices)),vertices=cornersNeg.map((corner=>corner[0])),polygons.push(create$7(vertices))}prevCornersPos=cornersPos,prevCornersNeg=cornersNeg}return create$8(polygons)},exports.roundedCylinder=options=>{const{center:center,height:height,radius:radius,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0,0],height:2,radius:1,roundRadius:.2,segments:32},options);if(!isNumberArray(center,3))throw new Error("center must be an array of X, Y and Z values");if(!isGTE(height,0))throw new Error("height must be positive");if(!isGTE(radius,0))throw new Error("radius must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(roundRadius>radius)throw new Error("roundRadius must be smaller than the radius");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===height||0===radius)return create$8();if(0===roundRadius)return cylinder({center:center,height:height,radius:radius});const start=[0,0,-height/2],end=[0,0,height/2],direction=subtract$3([0,0,0],end,start);if(2*roundRadius>length$2(direction)-EPS)throw new Error("height must be larger than twice roundRadius");let defaultNormal;defaultNormal=Math.abs(direction[0])>Math.abs(direction[1])?fromValues$3(0,1,0):fromValues$3(1,0,0);const zVector=scale$3([0,0,0],normalize$1([0,0,0],direction),roundRadius),xVector=scale$3([0,0,0],normalize$1([0,0,0],cross$1([0,0,0],zVector,defaultNormal)),radius),yVector=scale$3([0,0,0],normalize$1([0,0,0],cross$1([0,0,0],xVector,zVector)),radius);add$1(start,start,zVector),subtract$3(end,end,zVector);const qSegments=Math.floor(.25*segments),fromVertices=vertices=>{const newVertices=vertices.map((vertex=>add$1(vertex,vertex,center)));return create$7(newVertices)},polygons=[],v1=[0,0,0],v2=[0,0,0];let prevCylinderVertex;for(let slice1=0;slice1<=segments;slice1++){const angle=TAU*slice1/segments,cylinderVertex=add$1([0,0,0],scale$3(v1,xVector,cos(angle)),scale$3(v2,yVector,sin(angle)));if(slice1>0){let prevCosPitch,prevSinPitch,vertex,vertices=[];vertices.push(add$1([0,0,0],start,cylinderVertex)),vertices.push(add$1([0,0,0],start,prevCylinderVertex)),vertices.push(add$1([0,0,0],end,prevCylinderVertex)),vertices.push(add$1([0,0,0],end,cylinderVertex)),polygons.push(fromVertices(vertices));for(let slice2=0;slice2<=qSegments;slice2++){const pitch=TAU/4*slice2/qSegments,cosPitch=cos(pitch),sinPitch=sin(pitch);slice2>0&&(vertices=[],vertex=add$1([0,0,0],start,subtract$3(v1,scale$3(v1,prevCylinderVertex,prevCosPitch),scale$3(v2,zVector,prevSinPitch))),vertices.push(vertex),vertex=add$1([0,0,0],start,subtract$3(v1,scale$3(v1,cylinderVertex,prevCosPitch),scale$3(v2,zVector,prevSinPitch))),vertices.push(vertex),slice2{let{center:center,size:size,roundRadius:roundRadius,segments:segments}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isNumberArray(size,2))throw new Error("size must be an array of X and Y values");if(!size.every((n=>n>=0)))throw new Error("size values must be positive");if(!isGTE(roundRadius,0))throw new Error("roundRadius must be positive");if(!isGTE(segments,4))throw new Error("segments must be four or more");if(0===size[0]||0===size[1])return create$a();if(0===roundRadius)return rectangle({center:center,size:size});if(size=size.map((v=>v/2)),roundRadius>size[0]-EPS||roundRadius>size[1]-EPS)throw new Error("roundRadius must be smaller than the radius of all dimensions");const cornerSegments=Math.floor(segments/4),corner0=add([0,0],center,[size[0]-roundRadius,size[1]-roundRadius]),corner1=add([0,0],center,[roundRadius-size[0],size[1]-roundRadius]),corner2=add([0,0],center,[roundRadius-size[0],roundRadius-size[1]]),corner3=add([0,0],center,[size[0]-roundRadius,roundRadius-size[1]]),corner0Points=[],corner1Points=[],corner2Points=[],corner3Points=[];for(let i=0;i<=cornerSegments;i++){const point=fromAngleRadians([0,0],TAU/4*i/cornerSegments);scale$1(point,point,roundRadius),corner0Points.push(add([0,0],corner0,point)),rotate$1(point,point,[0,0],TAU/4),corner1Points.push(add([0,0],corner1,point)),rotate$1(point,point,[0,0],TAU/4),corner2Points.push(add([0,0],corner2,point)),rotate$1(point,point,[0,0],TAU/4),corner3Points.push(add([0,0],corner3,point))}const points=corner0Points.concat(corner1Points,corner2Points,corner3Points);return create$a([points])},exports.scale=scale,exports.scaleX=(factor,...objects)=>scale([factor,1,1],...objects),exports.scaleY=(factor,...objects)=>scale([1,factor,1],...objects),exports.scaleZ=(factor,...objects)=>scale([1,1,factor],...objects),exports.scission=scission,exports.sin=sin,exports.slice=index$2,exports.snap=snap,exports.sphere=sphere,exports.square=options=>{let{center:center,size:size}=Object.assign({},{center:[0,0],size:2},options);if(!isGTE(size,0))throw new Error("size must be positive");return size=[size,size],rectangle({center:center,size:size})},exports.star=options=>{let{center:center,vertices:vertices,outerRadius:outerRadius,innerRadius:innerRadius,density:density,startAngle:startAngle}=Object.assign({},{center:[0,0],vertices:5,outerRadius:1,innerRadius:0,density:2,startAngle:0},options);if(!isNumberArray(center,2))throw new Error("center must be an array of X and Y values");if(!isGTE(vertices,2))throw new Error("vertices must be two or more");if(!isGT(outerRadius,0))throw new Error("outerRadius must be greater than zero");if(!isGTE(innerRadius,0))throw new Error("innerRadius must be greater than zero");if(!isGTE(startAngle,0))throw new Error("startAngle must be greater than zero");if(vertices=Math.floor(vertices),density=Math.floor(density),startAngle%=TAU,0===innerRadius){if(!isGTE(density,2))throw new Error("density must be two or more");innerRadius=outerRadius*((vertices,density)=>vertices>0&&density>1&&density{if(0===(geometries=coalesce(geometries)).length)return;if(!areAllShapesTheSameType(geometries))throw new Error("subtract arguments must be the same geometry type");const geometry=geometries[0];if(isA$5(geometry))return(geometries=>{let newGeometry=geometries.shift();return geometries.forEach((geometry=>{newGeometry=boolean(newGeometry,geometry,2)})),newGeometry})(geometries);if(isA$3(geometry))return subtractGeom3(geometries);throw new Error("subtract unsupported geometry type")},exports.torus=options=>{const defaults={innerRadius:1,innerSegments:32,outerRadius:4,outerSegments:32,innerRotation:0,startAngle:0,outerRotation:TAU},{innerRadius:innerRadius,innerSegments:innerSegments,outerRadius:outerRadius,outerSegments:outerSegments,innerRotation:innerRotation,startAngle:startAngle,outerRotation:outerRotation}=Object.assign({},defaults,options);if(!isGT(innerRadius,0))throw new Error("innerRadius must be greater than zero");if(!isGTE(innerSegments,3))throw new Error("innerSegments must be three or more");if(!isGT(outerRadius,0))throw new Error("outerRadius must be greater than zero");if(!isGTE(outerSegments,3))throw new Error("outerSegments must be three or more");if(!isGTE(startAngle,0))throw new Error("startAngle must be positive");if(!isGT(outerRotation,0))throw new Error("outerRotation must be greater than zero");if(innerRadius>=outerRadius)throw new Error("inner circle is too large to rotate about the outer circle");let innerCircle=circle({radius:innerRadius,segments:innerSegments});return 0!==innerRotation&&(innerCircle=rotate([0,0,innerRotation],innerCircle)),innerCircle=translate([outerRadius,0],innerCircle),extrudeRotate({startAngle:startAngle,angle:outerRotation,segments:outerSegments},innerCircle)},exports.transform=transform,exports.translate=translate,exports.translateX=(offset,...objects)=>translate([offset,0,0],...objects),exports.translateY=(offset,...objects)=>translate([0,offset,0],...objects),exports.translateZ=(offset,...objects)=>translate([0,0,offset],...objects),exports.triangle=options=>{let{type:type,values:values}=Object.assign({},{type:"SSS",values:[1,1,1]},options);if("string"!=typeof type)throw new Error("triangle type must be a string");if(type=type.toUpperCase(),"A"!==type[0]&&"S"!==type[0]||"A"!==type[1]&&"S"!==type[1]||"A"!==type[2]&&"S"!==type[2])throw new Error("triangle type must contain three letters; A or S");if(!isNumberArray(values,3))throw new Error("triangle values must contain three values");if(!values.every((n=>n>0)))throw new Error("triangle values must be greater than zero");switch(type){case"AAA":return(angles=>{if(Math.abs(angles[0]+angles[1]+angles[2]-Math.PI)>NEPS)throw new Error("AAA triangles require angles that sum to PI");const A=angles[0],B=angles[1],C=Math.PI-A-B,a=1/Math.sin(C)*Math.sin(A),b=1/Math.sin(C)*Math.sin(B);return createTriangle(A,B,C,a,b,1)})(values);case"AAS":return(values=>{const A=values[0],B=values[1],C=Math.PI+NEPS-A-B;if(C{const A=values[0],B=values[2],C=Math.PI+NEPS-A-B;if(C{const c=values[0],a=values[1],C=values[2],A=Math.asin(a*Math.sin(C)/c),B=Math.PI-A-C,b=c/Math.sin(C)*Math.sin(B);return createTriangle(A,B,C,a,b,c)})(values);case"SSS":return(lengths=>{const a=lengths[1],b=lengths[2],c=lengths[0];if(a+b<=c||b+c<=a||c+a<=b)throw new Error("SSS triangle is incorrect, as the longest side is longer than the sum of the other sides");const A=solveAngleFromSSS(b,c,a),B=solveAngleFromSSS(c,a,b),C=Math.PI-A-B;return createTriangle(A,B,C,a,b,c)})(values);default:throw new Error("invalid triangle type, try again")}},exports.union=union,exports.vec2=index$b,exports.vec3=index$d,exports.vec4=index$8,exports.vectorChar=vectorChar,exports.vectorText=(options,text)=>{const{xOffset:xOffset,yOffset:yOffset,font:font,height:height,align:align,extrudeOffset:extrudeOffset,lineSpacing:lineSpacing,letterSpacing:letterSpacing}=Object.assign({},defaultsVectorParams,options);if("string"!=typeof text)throw new Error("text must be a string");const extraLetterSpacing=height*letterSpacing;let maxWidth=0,line={width:0,height:0,chars:[]},lines=[];const pushLine=()=>{maxWidth=Math.max(maxWidth,line.width),line.chars.length&&lines.push(line),line={width:0,height:0,chars:[]}};let vchar,x=xOffset,y=yOffset;const il=text.length;for(let i=0;i{const diff=maxWidth-line.width;return"right"===align?translateLine({x:diff},line):"center"===align?translateLine({x:diff/2},line):line})),lines},Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadModeling={}); diff --git a/packages/modeling/package.json b/packages/modeling/package.json index 736f064ee..c9c0ac0fd 100644 --- a/packages/modeling/package.json +++ b/packages/modeling/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/modeling", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "Constructive Solid Geometry (CSG) Library for JSCAD", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", diff --git a/packages/utils/array-utils/CHANGELOG.md b/packages/utils/array-utils/CHANGELOG.md index b4bcfb319..7a5801658 100644 --- a/packages/utils/array-utils/CHANGELOG.md +++ b/packages/utils/array-utils/CHANGELOG.md @@ -3,6 +3,13 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/array-utils@2.1.4...@jscad/array-utils@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **array-utils:** corrected typescript definitions, added test:tsd script ([#1316](https://github.com/jscad/OpenJSCAD.org/issues/1316)) ([9582d18](https://github.com/jscad/OpenJSCAD.org/commit/9582d18e76d89793b38fd1c98fe52ba27ac1af21)) +* **modeling:** use modern typescript imports ([0a0d2e8](https://github.com/jscad/OpenJSCAD.org/commit/0a0d2e8e4ac5db50cf9a6f05a33dba9bdd68c98a)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/array-utils@2.1.4...@jscad/array-utils@3.0.0-alpha.0) (2023-10-09) ### Bug Fixes diff --git a/packages/utils/array-utils/dist/jscad-array-utils.es.js b/packages/utils/array-utils/dist/jscad-array-utils.es.js index 408bd789e..de4e6aba8 100644 --- a/packages/utils/array-utils/dist/jscad-array-utils.es.js +++ b/packages/utils/array-utils/dist/jscad-array-utils.es.js @@ -1,7 +1,7 @@ /** * JSCAD Utility functions for arrays * @module @jscad/array-utils - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),fnNumberSort=(a,b)=>a-b,head=array=>{if(Array.isArray(array)&&0!==array.length)return array[0]},insertSorted=(array,element,compareFunction)=>{let leftbound=0,rightbound=array.length;for(;rightbound>leftbound;){const testindex=Math.floor((leftbound+rightbound)/2);compareFunction(element,array[testindex])>0?leftbound=testindex+1:rightbound=testindex}return array.splice(leftbound,0,element),array},nth=(array,index)=>{if(Array.isArray(array)&&!(array.length{for(anArray=anArray.slice();anArray.lengthArray.isArray(array)?array:null==array?[]:[array];export{flatten,fnNumberSort,head,insertSorted,nth,padToLength,toArray}; diff --git a/packages/utils/array-utils/dist/jscad-array-utils.min.js b/packages/utils/array-utils/dist/jscad-array-utils.min.js index 5455cfecf..34eb18315 100644 --- a/packages/utils/array-utils/dist/jscad-array-utils.min.js +++ b/packages/utils/array-utils/dist/jscad-array-utils.min.js @@ -1,7 +1,7 @@ /** * JSCAD Utility functions for arrays * @module @jscad/array-utils - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ var global,factory;global=this,factory=function(exports){const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]);exports.flatten=flatten,exports.fnNumberSort=(a,b)=>a-b,exports.head=array=>{if(Array.isArray(array)&&0!==array.length)return array[0]},exports.insertSorted=(array,element,compareFunction)=>{let leftbound=0,rightbound=array.length;for(;rightbound>leftbound;){const testindex=Math.floor((leftbound+rightbound)/2);compareFunction(element,array[testindex])>0?leftbound=testindex+1:rightbound=testindex}return array.splice(leftbound,0,element),array},exports.nth=(array,index)=>{if(Array.isArray(array)&&!(array.length{for(anArray=anArray.slice();anArray.lengthArray.isArray(array)?array:null==array?[]:[array],Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadArrayUtils={}); diff --git a/packages/utils/array-utils/package.json b/packages/utils/array-utils/package.json index 6cb1f7aa7..854f0dfb1 100644 --- a/packages/utils/array-utils/package.json +++ b/packages/utils/array-utils/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/array-utils", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "JSCAD Utility functions for arrays", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", diff --git a/packages/utils/regl-renderer/CHANGELOG.md b/packages/utils/regl-renderer/CHANGELOG.md index a243f474a..7e825e3e1 100644 --- a/packages/utils/regl-renderer/CHANGELOG.md +++ b/packages/utils/regl-renderer/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.0.1-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/regl-renderer@2.6.3...@jscad/regl-renderer@3.0.1-alpha.0) (2025-01-03) + +### Bug Fixes + +* **regl-renderer:** define the entity type and corrected TS definitions ([156929b](https://github.com/jscad/OpenJSCAD.org/commit/156929bbbeae028e91b5b4bc1d1fda682931af06)) + +### Features + +* **regl-renderer:** added rollup configuration to create ES6 bundle, adjusted imports and exports ([#1259](https://github.com/jscad/OpenJSCAD.org/issues/1259)) ([47a66bc](https://github.com/jscad/OpenJSCAD.org/commit/47a66bc07a137a748ce8571ea5d043ebaab9418d)) + # [3.0.0-alpha.0](https://github.com/jscad/OpenJSCAD.org/compare/@jscad/regl-renderer@2.6.3...@jscad/regl-renderer@3.0.0-alpha.0) (2023-10-09) ### Features diff --git a/packages/utils/regl-renderer/dist/jscad-regl-renderer.es.js b/packages/utils/regl-renderer/dist/jscad-regl-renderer.es.js index 9a3cd4cb1..20ca50762 100644 --- a/packages/utils/regl-renderer/dist/jscad-regl-renderer.es.js +++ b/packages/utils/regl-renderer/dist/jscad-regl-renderer.es.js @@ -1,13 +1,13 @@ /** * Renderer for JSCAD Geometries * @module @jscad/regl-renderer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ "undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var create_1$1=function(){var out=new Float32Array(3);return out[0]=0,out[1]=0,out[2]=0,out};var clone_1$1=function(a){var out=new Float32Array(3);return out[0]=a[0],out[1]=a[1],out[2]=a[2],out};var fromValues_1=function(x,y,z){var out=new Float32Array(3);return out[0]=x,out[1]=y,out[2]=z,out};var normalize_1=function(out,a){var x=a[0],y=a[1],z=a[2],len=x*x+y*y+z*z;len>0&&(len=1/Math.sqrt(len),out[0]=a[0]*len,out[1]=a[1]*len,out[2]=a[2]*len);return out};var dot_1=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]};var angle_1=function(a,b){var tempA=fromValues(a[0],a[1],a[2]),tempB=fromValues(b[0],b[1],b[2]);normalize(tempA,tempA),normalize(tempB,tempB);var cosine=dot(tempA,tempB);return cosine>1?0:Math.acos(cosine)},fromValues=fromValues_1,normalize=normalize_1,dot=dot_1;var copy_1$1=function(out,a){return out[0]=a[0],out[1]=a[1],out[2]=a[2],out};var set_1=function(out,x,y,z){return out[0]=x,out[1]=y,out[2]=z,out};var equals_1=function(a,b){var a0=a[0],a1=a[1],a2=a[2],b0=b[0],b1=b[1],b2=b[2];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))},EPSILON=1e-6;var exactEquals_1=function(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]};var add_1=function(out,a,b){return out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out};var subtract_1=function(out,a,b){return out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out};var subExports={};({get exports(){return subExports},set exports(v){subExports=v}}).exports=subtract_1;var multiply_1$1=function(out,a,b){return out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out};var mulExports={};({get exports(){return mulExports},set exports(v){mulExports=v}}).exports=multiply_1$1;var divide_1=function(out,a,b){return out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out};var divExports={};({get exports(){return divExports},set exports(v){divExports=v}}).exports=divide_1;var min_1=function(out,a,b){return out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out};var max_1=function(out,a,b){return out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out};var floor_1=function(out,a){return out[0]=Math.floor(a[0]),out[1]=Math.floor(a[1]),out[2]=Math.floor(a[2]),out};var ceil_1=function(out,a){return out[0]=Math.ceil(a[0]),out[1]=Math.ceil(a[1]),out[2]=Math.ceil(a[2]),out};var round_1=function(out,a){return out[0]=Math.round(a[0]),out[1]=Math.round(a[1]),out[2]=Math.round(a[2]),out};var scale_1$1=function(out,a,b){return out[0]=a[0]*b,out[1]=a[1]*b,out[2]=a[2]*b,out};var scaleAndAdd_1=function(out,a,b,scale){return out[0]=a[0]+b[0]*scale,out[1]=a[1]+b[1]*scale,out[2]=a[2]+b[2]*scale,out};var distance_1=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)};var distExports={};({get exports(){return distExports},set exports(v){distExports=v}}).exports=distance_1;var squaredDistance_1=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z};var sqrDistExports={};({get exports(){return sqrDistExports},set exports(v){sqrDistExports=v}}).exports=squaredDistance_1;var length_1=function(a){var x=a[0],y=a[1],z=a[2];return Math.sqrt(x*x+y*y+z*z)};var lenExports={};({get exports(){return lenExports},set exports(v){lenExports=v}}).exports=length_1;var squaredLength_1=function(a){var x=a[0],y=a[1],z=a[2];return x*x+y*y+z*z};var sqrLenExports={};({get exports(){return sqrLenExports},set exports(v){sqrLenExports=v}}).exports=squaredLength_1;var negate_1=function(out,a){return out[0]=-a[0],out[1]=-a[1],out[2]=-a[2],out};var inverse_1=function(out,a){return out[0]=1/a[0],out[1]=1/a[1],out[2]=1/a[2],out};var cross_1=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out};var lerp_1=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out[2]=az+t*(b[2]-az),out};var random_1=function(out,scale){scale=scale||1;var r=2*Math.random()*Math.PI,z=2*Math.random()-1,zScale=Math.sqrt(1-z*z)*scale;return out[0]=Math.cos(r)*zScale,out[1]=Math.sin(r)*zScale,out[2]=z*scale,out};var transformMat4_1=function(out,a,m){var x=a[0],y=a[1],z=a[2],w=m[3]*x+m[7]*y+m[11]*z+m[15];return w=w||1,out[0]=(m[0]*x+m[4]*y+m[8]*z+m[12])/w,out[1]=(m[1]*x+m[5]*y+m[9]*z+m[13])/w,out[2]=(m[2]*x+m[6]*y+m[10]*z+m[14])/w,out};var transformMat3_1=function(out,a,m){var x=a[0],y=a[1],z=a[2];return out[0]=x*m[0]+y*m[3]+z*m[6],out[1]=x*m[1]+y*m[4]+z*m[7],out[2]=x*m[2]+y*m[5]+z*m[8],out};var transformQuat_1=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;return out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy,out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz,out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx,out};var rotateX_1$1=function(out,a,b,c){var by=b[1],bz=b[2],py=a[1]-by,pz=a[2]-bz,sc=Math.sin(c),cc=Math.cos(c);return out[0]=a[0],out[1]=by+py*cc-pz*sc,out[2]=bz+py*sc+pz*cc,out};var rotateY_1$1=function(out,a,b,c){var bx=b[0],bz=b[2],px=a[0]-bx,pz=a[2]-bz,sc=Math.sin(c),cc=Math.cos(c);return out[0]=bx+pz*sc+px*cc,out[1]=a[1],out[2]=bz+pz*cc-px*sc,out};var rotateZ_1$1=function(out,a,b,c){var bx=b[0],by=b[1],px=a[0]-bx,py=a[1]-by,sc=Math.sin(c),cc=Math.cos(c);return out[0]=bx+px*cc-py*sc,out[1]=by+px*sc+py*cc,out[2]=a[2],out};var forEach_1=function(a,stride,offset,count,fn,arg){var i,l;stride||(stride=3);offset||(offset=0);l=count?Math.min(count*stride+offset,a.length):a.length;for(i=offset;i{const{width:width,height:height}=input,aspect=width/height,viewport=[0,0,width,height],multiplier=camera.zoom,left=-width*multiplier,right=width*multiplier,bottom=-height*multiplier,top=height*multiplier;return{projection:glMat4.ortho([],left,right,bottom,top,camera.near,camera.far),aspect:aspect,viewport:viewport}};var orthographicCamera=Object.freeze({__proto__:null,cameraState:cameraState$1,cameraProps:{},setProjection:setProjection$1});const cameraState={view:glMat4.identity(new Float32Array(16)),projection:glMat4.identity(new Float32Array(16)),matrix:glMat4.identity(new Float32Array(16)),near:1,far:18e3,up:[0,0,1],eye:new Float32Array(3),position:[450,550,700],target:[0,0,0],fov:Math.PI/4,aspect:1,viewport:[0,0,0,0],projectionType:"perspective"},cameraProps={},defaults$1=Object.assign({},cameraState,cameraProps),setProjection=(output,camera,input)=>{const aspect=input.width/input.height,projection=glMat4.perspective(glMat4.identity([]),camera.fov,aspect,camera.near,camera.far),viewport=[0,0,input.width,input.height],out=output||{};return out.projection=projection,out.aspect=aspect,out.viewport=viewport,out};var perspectiveCamera=Object.freeze({__proto__:null,cameraState:cameraState,cameraProps:cameraProps,defaults:defaults$1,setProjection:setProjection,update:(output,camera)=>{camera||(camera=output);const{position:position,target:target,up:up}=camera,offset=glVec3.subtract([],position,target),newPosition=glVec3.add(glVec3.create(),target,offset),newView=glMat4.lookAt(glMat4.create(),newPosition,target,up),out=output||{};return out.position=newPosition,out.view=newView,out}});var camera=Object.freeze({__proto__:null,fromOrthographicToPerspective:orthographicCamera=>{const{near:near,far:far,fov:fov}=orthographicCamera,{viewport:viewport}=orthographicCamera,projection=setProjection(orthographicCamera,{width:viewport[2],height:viewport[3]}),{projectionType:projectionType}=cameraState;return Object.assign({},orthographicCamera,projection,{projectionType:projectionType},{near:near,far:far,fov:fov})},fromPerspectiveToOrthographic:perspectiveCamera=>{const{fov:fov,aspect:aspect}=perspectiveCamera,distance=.3*glVec3.length(glVec3.subtract([],perspectiveCamera.position,perspectiveCamera.target)),width=Math.tan(fov)*distance*aspect,height=Math.tan(fov)*distance,{near:near,far:far,viewport:viewport}=perspectiveCamera,projectionType=cameraState$1.projectionType,projection=setProjection$1({zoom:1,near:near,far:far},{width:width,height:height});return Object.assign({},orthographicCamera,perspectiveCamera,projection,{projectionType:projectionType,viewport:viewport})},toPerspectiveView:({camera:camera})=>{const offsetToTarget=glVec3.distance(camera.position,camera.target),position=[offsetToTarget,offsetToTarget,offsetToTarget];return{view:glMat4.lookAt(glMat4.create(),position,camera.target,camera.up),position:position}},toPresetView:(viewName,{camera:camera})=>{const offsetToTarget=glVec3.distance(camera.position,camera.target),position=glVec3.add(glVec3.create(),{top:[0,-1e-6,1],bottom:[0,0,-1],front:[0,1,0],back:[0,-1,0],left:[-1,0,0],right:[1,0,0],undefined:[0,0,0]}[viewName].map((x=>x*offsetToTarget)),camera.target);return{view:glMat4.lookAt(glMat4.create(),position,camera.target,camera.up),position:position}}}),index$2=Object.freeze({__proto__:null,camera:camera,orthographic:orthographicCamera,perspective:perspectiveCamera});const makeDrawGrid=(regl,params={})=>{const positions=[],defaults={visuals:{color:[0,0,1,1],fadeOut:!1},ticks:1,size:[16,16],centered:!1,lineWidth:2},visuals=Object.assign({},defaults.visuals,params.visuals||{}),{fadeOut:fadeOut,color:color}=visuals,{size:size,ticks:ticks,centered:centered,lineWidth:lineWidth}=Object.assign({},defaults,params),width=size[0],length=size[1];if(centered){const halfWidth=.5*width,halfLength=.5*length,widthStart=-halfWidth+halfWidth%ticks,widthEnd=-widthStart,lengthStart=-halfLength+halfLength%ticks,lengthEnd=-lengthStart,skipEvery=0;for(let i=widthStart,j=0;i<=widthEnd;i+=ticks,j+=1)j%skipEvery!=0&&(positions.push(lengthStart,i,0),positions.push(lengthEnd,i,0),positions.push(lengthStart,i,0));for(let i=lengthStart,j=0;i<=lengthEnd;i+=ticks,j+=1)j%skipEvery!=0&&(positions.push(i,widthStart,0),positions.push(i,widthEnd,0),positions.push(i,widthStart,0))}else{for(let i=.5*-width;i<=.5*width;i+=ticks)positions.push(.5*-length,i,0),positions.push(.5*length,i,0),positions.push(.5*-length,i,0);for(let i=.5*-length;i<=.5*length;i+=ticks)positions.push(i,.5*-width,0),positions.push(i,.5*width,0),positions.push(i,.5*-width,0)}return regl({vert:"precision mediump float;\n\n uniform float camNear, camFar;\n uniform mat4 model, view, projection;\n\n attribute vec3 position;\n varying vec3 fragNormal, fragPosition;\n varying vec4 worldPosition;\n\n void main() {\n fragPosition = position;\n worldPosition = model * vec4(position, 1);\n vec4 glPosition = projection * view * worldPosition;\n gl_Position = glPosition;\n }",frag:"precision mediump float;\n uniform vec4 color;\n varying vec3 fragNormal, fragPosition;\n varying vec4 worldPosition;\n\n uniform vec4 fogColor;\n uniform bool fadeOut;\n void main() {\n float dist = .5;\n if(fadeOut){\n dist = distance( vec2(0.,0.), vec2(worldPosition.x, worldPosition.y));\n dist *= 0.0025;\n dist = sqrt(dist);\n }\n\n gl_FragColor = mix(color, fogColor, dist);\n }\n ",attributes:{position:regl.buffer(positions)},count:positions.length/3,uniforms:{model:(context,props)=>props&&props.model?props.model:glMat4.identity([]),color:(context,props)=>props&&props.color?props.color:color,fogColor:(context,props)=>props&&props.color?[props.color[0],props.color[1],props.color[2],0]:[color[0],color[1],color[2],0],fadeOut:(context,props)=>props&&void 0!==props.fadeOut?props.fadeOut:fadeOut},lineWidth:(context,props)=>Math.min(props&&props.lineWidth?props.lineWidth:lineWidth,regl.limits.lineWidthDims[1]),primitive:"lines",cull:{enable:!0,face:"front"},polygonOffset:{enable:!0,offset:{factor:1,units:10*Math.random()}},blend:{enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}})},meshColor=[0,.6,1,1];var renderDefaults=Object.freeze({__proto__:null,background:[1,1,1,1],meshColor:meshColor,lightColor:[1,1,1,1],lightDirection:[.2,.2,1],lightPosition:[100,200,100],ambientLightAmount:.3,diffuseLightAmount:.89,specularLightAmount:.16,materialShininess:8});var index$1=Object.freeze({__proto__:null,drawGrid:(regl,params)=>{const{size:size,ticks:ticks}=Object.assign({},{size:[50,50],ticks:[10,1]},params),drawMainGrid=makeDrawGrid(regl,{size:size,ticks:ticks[0]}),drawSubGrid=makeDrawGrid(regl,{size:size,ticks:ticks[1]});return props=>{drawMainGrid(props),drawSubGrid({color:props.subColor,fadeOut:props.fadeOut})}},drawAxis:(regl,params)=>{let{size:size,xColor:xColor,yColor:yColor,zColor:zColor,lineWidth:lineWidth,alwaysVisible:alwaysVisible}=Object.assign({},{xColor:[1,0,0,1],yColor:[0,1,0,1],zColor:[0,0,1,1],size:10,lineWidth:3,alwaysVisible:!0},params);lineWidth>regl.limits.lineWidthDims[1]&&(lineWidth=regl.limits.lineWidthDims[1]);const points=[0,0,0,size,0,0],commandParams={frag:"precision mediump float;\n uniform vec4 color;\n void main() {\n gl_FragColor = color;\n }",vert:"\n precision mediump float;\n attribute vec3 position;\n uniform mat4 model, view, projection;\n void main() {\n gl_Position = projection * view * model * vec4(position, 1);\n }",uniforms:{model:(context,props)=>props&&props.model?props.model:glMat4.identity([]),color:(context,props)=>props.color,angle:(contet,props)=>props.angle},attributes:{position:points},count:points.length/3,primitive:"line loop",lineWidth:lineWidth,depth:{enable:!alwaysVisible}},xAxisModel=glMat4.identity([]),yAxisModel=glMat4.rotateZ(glMat4.create(),glMat4.identity([]),Math.PI/2),zAxisModel=glMat4.rotateY(glMat4.create(),glMat4.identity([]),-Math.PI/2),single=regl(commandParams);return props=>{const defaults={model:glMat4.identity([])};return props=Object.assign({},defaults,props),single([{color:xColor,model:glMat4.multiply(glMat4.create(),props.model,xAxisModel)},{color:yColor,model:glMat4.multiply(glMat4.create(),props.model,yAxisModel)},{color:zColor,model:glMat4.multiply(glMat4.create(),props.model,zAxisModel)}])}},drawMesh:(regl,params={extras:{}})=>{const defaults={useVertexColors:!0,dynamicCulling:!0,geometry:void 0,color:meshColor,visuals:{}},{geometry:geometry,dynamicCulling:dynamicCulling,useVertexColors:useVertexColors,color:color,visuals:visuals}=Object.assign({},defaults,params),ambientOcclusion=regl.buffer([]),hasIndices=!!(geometry.indices&&geometry.indices.length>0),hasNormals=!!(geometry.normals&&geometry.normals.length>0),transparent="transparent"in visuals&&visuals.transparent,hasVertexColors=!!(useVertexColors&&geometry.colors&&geometry.colors.length>0),transforms=geometry.transforms||glMat4.create(),flip=glMat4.determinant(transforms)<0,cullFace=dynamicCulling&&flip?"front":"back",vert=hasVertexColors?"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection, unormal;\n\nattribute vec3 position, normal;\nattribute vec4 color;\n\nattribute float ao;\nvarying float ambientAo;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\nvarying vec4 vColor;\n\nvoid main() {\n surfacePosition = (unormal * vec4(position, 1.0)).xyz;\n surfaceNormal = normalize((unormal * vec4(normal, 1.0)).xyz); //vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n //gl_Position = projection * view * worldSpacePosition;\n\n vColor = color;\n\n //ambientAo = (1. - ao) * (0.5 * max(normal.x, 0.) + 0.5);\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n //gl_Position = zBufferAdjust(glPosition, camNear, camFar);\n}\n":"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\n\nvoid main() {\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n",frag=hasVertexColors?"\nprecision mediump float;\nvarying vec3 surfaceNormal, surfacePosition;\n\nuniform float ambientLightAmount;\nuniform float diffuseLightAmount;\nuniform float specularLightAmount;\n\nuniform vec3 lightDirection;\nuniform vec4 lightColor;\nuniform vec3 opacity;\nuniform float uMaterialShininess;\n\nvarying vec4 vColor;\nuniform vec4 ucolor;\nuniform float vColorToggler;\n\nuniform vec2 printableArea;\nvec4 errorColor = vec4(0.15, 0.15, 0.15, 0.3);//vec4(0.15, 0.15, 0.15, 0.3);\nvarying vec4 _worldSpacePosition;\nvarying float ambientAo;\n\nvoid main () {\n vec4 depth = gl_FragCoord;\n vec4 endColor = vColor * vColorToggler + ucolor * (1.0 - vColorToggler);\n\n vec3 ambient = ambientLightAmount * endColor.rgb ; //ambientAo * \n\n float diffuseWeight = dot(surfaceNormal, lightDirection);\n vec3 diffuse = diffuseLightAmount * endColor.rgb * clamp(diffuseWeight , 0.0, 1.0 );\n\n //specular\n \n vec4 specularColor = vec4(lightColor);\n vec3 eyeDirection = normalize(surfacePosition.xyz);\n vec3 reflectionDirection = reflect(-lightDirection, -surfaceNormal);\n float specularLightWeight = pow(max(dot(reflectionDirection, eyeDirection), 0.0), uMaterialShininess);\n vec3 specular = specularColor.rgb * specularLightWeight * specularLightAmount;\n\n gl_FragColor = vec4((ambient + diffuse + specular), endColor.a);\n}\n":"\nprecision mediump float;\nvarying vec3 surfaceNormal;\nuniform float ambientLightAmount;\nuniform float diffuseLightAmount;\nuniform vec4 ucolor;\nuniform vec3 lightDirection;\nuniform vec3 opacity;\n\nvarying vec4 _worldSpacePosition;\n\nuniform vec2 printableArea;\n\nvec4 errorColor = vec4(0.15, 0.15, 0.15, 0.3);\n\nvoid main () {\n vec4 depth = gl_FragCoord;\n\n float v = 0.8; // shadow value\n vec4 endColor = ucolor;\n\n vec3 ambient = ambientLightAmount * endColor.rgb;\n float cosTheta = dot(surfaceNormal, lightDirection);\n vec3 diffuse = diffuseLightAmount * endColor.rgb * clamp(cosTheta , 0.0, 1.0 );\n\n float cosTheta2 = dot(surfaceNormal, vec3(-lightDirection.x, -lightDirection.y, lightDirection.z));\n vec3 diffuse2 = diffuseLightAmount * endColor.rgb * clamp(cosTheta2 , 0.0, 1.0 );\n\n gl_FragColor = vec4((ambient + diffuse + diffuse2 * v), endColor.a);\n}",modelMatrixInv=glMat4.invert(glMat4.create(),transforms);let commandParams={primitive:"triangles",vert:vert,frag:frag,uniforms:{model:(context,props)=>transforms,ucolor:(context,props)=>props&&props.color?props.color:color,vColorToggler:(context,props)=>props&&props.useVertexColors&&!0===props.useVertexColors?1:0,unormal:(context,props)=>{const modelViewMatrix=glMat4.invert(glMat4.create(),props.camera.view);return glMat4.multiply(modelViewMatrix,modelMatrixInv,modelViewMatrix),glMat4.transpose(modelViewMatrix,modelViewMatrix),modelViewMatrix}},attributes:{position:regl.buffer({usage:"static",type:"float",data:geometry.positions}),ao:ambientOcclusion},cull:{enable:!0,face:cullFace}};return transparent&&(commandParams.blend={enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}),geometry.cells?commandParams.elements=geometry.cells:hasIndices?commandParams.elements=regl.elements({usage:"static",type:"uint16",data:geometry.indices}):geometry.triangles?commandParams.elements=geometry.triangles:commandParams.count=geometry.positions.length/3,hasNormals&&(commandParams.attributes.normal=regl.buffer({usage:"static",type:"float",data:geometry.normals})),hasVertexColors&&(commandParams.attributes.color=regl.buffer({usage:"static",type:"float",data:geometry.colors})),commandParams=Object.assign({},commandParams,params.extras),regl(commandParams)},drawLines:(regl,params={})=>{const defaults={color:meshColor,geometry:void 0};let{geometry:geometry,color:color,transparent:transparent}=Object.assign({},defaults,params);"color"in geometry&&(color=geometry.color);const hasIndices=!!(geometry.indices&&geometry.indices.length>0),hasNormals=!!(geometry.normals&&geometry.normals.length>0),hasVertexColors=!!(geometry.colors&&geometry.colors.length>0),commandParams={primitive:"lines",vert:hasVertexColors?"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\nattribute vec4 color;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\nvarying vec4 vColor;\n\nvoid main() {\n vColor = color;\n\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n":"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\n\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\n\n\nvoid main() {\n\n\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n",frag:hasVertexColors?"\nprecision mediump float;\nvarying vec4 vColor;\n\nvoid main () {\n gl_FragColor = vColor;\n}\n":"\nprecision mediump float;\nuniform vec4 ucolor;\n\nvoid main () {\n gl_FragColor = ucolor;\n}\n",uniforms:{model:(context,props)=>props.model||geometry.transforms||glMat4.create(),ucolor:(context,props)=>props&&props.color?props.color:color},attributes:{position:regl.buffer({usage:"static",type:"float",data:geometry.positions})}};return transparent&&(commandParams.blend={enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}),hasVertexColors&&(commandParams.attributes.color=regl.buffer({usage:"static",type:"float",data:geometry.colors})),hasIndices&&(commandParams.elements=regl.elements({usage:"static",type:"uint16",data:geometry.indices})),hasNormals&&(commandParams.attributes.normal=regl.buffer({usage:"static",type:"float",data:geometry.normals})),regl(commandParams)}}),projectMat4=function(out,vec,m){var x=vec[0],y=vec[1],z=vec[2],a00=m[0],a01=m[1],a02=m[2],a03=m[3],a10=m[4],a11=m[5],a12=m[6],a13=m[7],a20=m[8],a21=m[9],a22=m[10],a23=m[11],a30=m[12],a31=m[13],a32=m[14],a33=m[15],lw=1/(x*a03+y*a13+z*a23+a33);return out[0]=(x*a00+y*a10+z*a20+a30)*lw,out[1]=(x*a01+y*a11+z*a21+a31)*lw,out[2]=(x*a02+y*a12+z*a22+a32)*lw,out};var transform=projectMat4,cameraUnproject=function(out,vec,viewport,invProjectionView){var viewX=viewport[0],viewY=viewport[1],viewWidth=viewport[2],viewHeight=viewport[3],x=vec[0],y=vec[1],z=vec[2];return x-=viewX,y=viewHeight-y-1,y-=viewY,out[0]=2*x/viewWidth-1,out[1]=2*y/viewHeight-1,out[2]=2*z-1,transform(out,out,invProjectionView)} /** * JSCAD Utility functions for arrays * @module @jscad/array-utils - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */;const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),computeBounds=(...geometries)=>{let bbox;(geometries=flatten(geometries)).forEach((geometry=>{let gbbox=(positions=>{if(0===positions.length)return[[0,0,0],[0,0,0]];const nested=Array.isArray(positions)&&Array.isArray(positions[0]),dimensions=nested?positions[0].length:3,min=new Array(dimensions),max=new Array(dimensions);for(let i=0;i{for(let i=0;imax[i]?_position:max[i],min[i]=_positionmax[i]?_position:max[i],min[i]=_positionglVec3.transformMat4(bounds,bounds,geometry.transforms))),bbox?(glVec3.min(bbox[0],bbox[0],gbbox[0]),glVec3.max(bbox[1],bbox[1],gbbox[1])):bbox=gbbox}));const min=glVec3.min(glVec3.create(),bbox[1],bbox[0]),max=glVec3.max(glVec3.create(),bbox[1],bbox[0]),size=glVec3.subtract(glVec3.create(),max,min);let center=glVec3.scale(glVec3.create(),size,.5);center=glVec3.add(center,min,center);return{dia:glVec3.distance(center,max),center:[...center],min:[...min],max:[...max],size:[...size]}},{max:max,min:min,sqrt:sqrt,PI:PI,sin:sin,cos:cos,atan2:atan2}=Math,controlsProps={limits:{minDistance:.01,maxDistance:1e4},drag:.27,EPS:1e-6,zoomToFit:{auto:!0,targets:"all",tightness:1.5},userControl:{zoom:!0,zoomSpeed:1,rotate:!0,rotateSpeed:1,pan:!0,panSpeed:1},autoRotate:{enabled:!1,speed:1},autoAdjustPlanes:!0},controlsState={thetaDelta:0,phiDelta:0,scale:1},defaults=Object.assign({},controlsState,controlsProps);var orbitControls=Object.freeze({__proto__:null,controlsProps:controlsProps,controlsState:controlsState,defaults:defaults,update:({controls:controls,camera:camera},output)=>{const{EPS:EPS,drag:drag}=controls,{position:position,target:target}=camera,up=controls.up?controls.up:camera.up;let curThetaDelta=controls.thetaDelta;const curPhiDelta=controls.phiDelta,curScale=controls.scale,offset=glVec3.subtract([],position,target);let theta,phi;1===up[2]?(theta=atan2(offset[0],offset[1]),phi=atan2(sqrt(offset[0]*offset[0]+offset[1]*offset[1]),offset[2])):(theta=atan2(offset[0],offset[2]),phi=atan2(sqrt(offset[0]*offset[0]+offset[2]*offset[2]),offset[1])),controls.autoRotate.enabled&&controls.userControl.rotate&&(curThetaDelta+=2*Math.PI/60/60*controls.autoRotate.speed),theta+=curThetaDelta,phi+=curPhiDelta,phi=max(EPS,min(PI-EPS,phi));const radius=max(controls.limits.minDistance,min(controls.limits.maxDistance,glVec3.length(offset)*curScale));1===up[2]?(offset[0]=radius*sin(phi)*sin(theta),offset[2]=radius*cos(phi),offset[1]=radius*sin(phi)*cos(theta)):(offset[0]=radius*sin(phi)*sin(theta),offset[1]=radius*cos(phi),offset[2]=radius*sin(phi)*cos(theta));const newPosition=glVec3.add(glVec3.create(),target,offset),newView=glMat4.lookAt(glMat4.create(),newPosition,target,up),dragEffect=1-max(min(drag,1),.01);return{controls:{thetaDelta:curThetaDelta*dragEffect,phiDelta:curPhiDelta*dragEffect,scale:1,changed:glVec3.distance(position,newPosition)>.001},camera:{position:newPosition,view:newView}}},rotate:({controls:controls,camera:camera,speed:speed=1},angle)=>{let{thetaDelta:thetaDelta,phiDelta:phiDelta}=controls;return controls.userControl.rotate&&(thetaDelta+=angle[0]*speed,phiDelta+=angle[1]*speed),{controls:{thetaDelta:thetaDelta,phiDelta:phiDelta},camera:camera}},zoom:({controls:controls,camera:camera,speed:speed=1},zoomDelta=0)=>{let{scale:scale}=controls;if(controls.userControl.zoom&&camera&&void 0!==zoomDelta&&0!==zoomDelta&&!isNaN(zoomDelta)){const newScale=(zoomDelta=zoomDelta/zoomDelta*(0===Math.sign(zoomDelta)?1:Math.sign(zoomDelta))*speed)+controls.scale,newDistance=glVec3.distance(camera.position,camera.target)*newScale;if(newDistance>controls.limits.minDistance&&newDistance{const{projection:projection,view:view,viewport:viewport}=camera,combinedProjView=glMat4.multiply([],projection,view),invProjView=glMat4.invert([],combinedProjView),panStart=[viewport[2],viewport[3],0],panEnd=[viewport[2]-delta[0],viewport[3]+delta[1],0],unPanStart=cameraUnproject.unproject([],panStart,viewport,invProjView),unPanEnd=cameraUnproject.unproject([],panEnd,viewport,invProjView),eyeDistance=glVec3.distance(camera.position,camera.eye),offset=glVec3.subtract([],unPanStart,unPanEnd).map((x=>x*speed*eyeDistance*controls.scale));return{controls:controls,camera:{position:glVec3.add(glVec3.create(),camera.position,offset),target:glVec3.add(glVec3.create(),camera.target,offset)}}},zoomToFit:({controls:controls,camera:camera,entities:entities})=>{const{zoomToFit:zoomToFit}=controls;if("all"!==zoomToFit.targets)return{controls:controls,camera:camera};if(0===entities.length)return{controls:controls,camera:camera};const geometries=entities.map((entity=>entity.geometry)),bounds=computeBounds(geometries),{fov:fov,target:target,position:position}=camera,{tightness:tightness}=Object.assign({},zoomToFit,controlsProps.zoomToFit),scaleForIdealDistance=bounds.dia*tightness/Math.tan(fov/2)/glVec3.distance(target,position);return{camera:{target:bounds.center},controls:{scale:scaleForIdealDistance}}},reset:({controls:controls,camera:camera},desiredState)=>({camera:{position:desiredState.camera.position,target:desiredState.camera.target,projection:glMat4.perspective([],camera.fov,camera.aspect,camera.near,camera.far),view:desiredState.camera.view},controls:{thetaDelta:desiredState.controls.thetaDelta,phiDelta:desiredState.controls.phiDelta,scale:desiredState.controls.scale}})}),index=Object.freeze({__proto__:null,orbit:orbitControls});const maxIndex$2=Math.floor(32767.5),polygonColor=(polygon,color)=>{let faceColor=color;return polygon.color&&(faceColor=polygon.color),faceColor&&faceColor.length<4&&faceColor.push(1),faceColor},calculateNormal=polygon=>{if(polygon.plane)return glVec3.clone(polygon.plane);const vertices=polygon.vertices,ba=glVec3.create();glVec3.subtract(ba,vertices[1],vertices[0]);const ca=glVec3.create();glVec3.subtract(ca,vertices[2],vertices[0]);const normal=glVec3.create();return glVec3.cross(normal,ba,ca),glVec3.normalize(normal,normal),normal},maxIndex=Math.floor(32767.5)-2,entitiesFromSolids=(options,...solids)=>{const defaults={color:meshColor,smoothNormals:!0},{color:color,smoothNormals:smoothNormals}=Object.assign({},defaults,options);var array;solids=(solids=flatten((array=solids,Array.isArray(array)?array:null==array?[]:[array]))).filter((solid=>solid&&solid instanceof Object));const entities=[];return solids.forEach((solid=>{let geometries=[];"outlines"in solid?geometries=((options,solid)=>{let{color:color}=options;const outlines=solid.outlines;if(0===outlines.length)return[];"color"in solid&&(color=solid.color);const isTransparent=color[3]<1,geometries=[];for(let i=0;inormal)),indices=positions.map(((x,i)=>i)),transforms=solid.transforms?glMat4.clone(solid.transforms):glMat4.create();geometries.push({type:"2d",positions:positions,normals:normals,indices:indices,transforms:transforms,color:color,isTransparent:isTransparent})}}return geometries})({color:color},solid):"points"in solid?geometries=((options,solid)=>{let{color:color}=options;const points=solid.points;if(0===points.length)return[];"color"in solid&&(color=solid.color);const isTransparent=color[3]<1,numgeometries=Math.floor(points.length/maxIndex)+1,geometries=[];for(let g=0;gnormal)),indices=positions.map(((x,i)=>i)),transforms=solid.transforms?glMat4.clone(solid.transforms):glMat4.create();geometries.push({type:"2d",positions:positions,normals:normals,indices:indices,transforms:transforms,color:color,isTransparent:isTransparent})}return geometries})({color:color},solid):"polygons"in solid&&(geometries=((options,solid)=>{let{color:color,smoothLighting:smoothLighting}=options;"color"in solid&&(color=solid.color);const polygons=solid.polygons,transforms=solid.transforms?glMat4.clone(solid.transforms):glMat4.create(),geometries=[];let setstart=0;for(;setstart65535));i++)setend++;const positions=[],normals=[],indices=[],colors=[],isTransparent=color[3]<1;for(let i=setstart;igeometries.map((geometry=>({geometry:geometry,visuals:{drawCmd:"2d"===geometry.type?"drawLines":"drawMesh",show:!0,transparent:geometry.isTransparent,useVertexColors:!0}}))))(geometries))})),entities};var reglExports={};({get exports(){return reglExports},set exports(v){reglExports=v}}).exports=function(){var isTypedArray=function(x){return x instanceof Uint8Array||x instanceof Uint16Array||x instanceof Uint32Array||x instanceof Int8Array||x instanceof Int16Array||x instanceof Int32Array||x instanceof Float32Array||x instanceof Float64Array||x instanceof Uint8ClampedArray},extend=function(base,opts){for(var keys=Object.keys(opts),i=0;i=0&&(0|value)===value||raise("invalid parameter type, ("+value+")"+encolon(message)+". must be a nonnegative integer")}function checkOneOf(value,list,message){list.indexOf(value)<0&&raise("invalid value"+encolon(message)+". must be one of: "+list)}var constructorKeys=["gl","canvas","container","attributes","pixelRatio","extensions","optionalExtensions","profile","onDone"];function checkConstructor(obj){Object.keys(obj).forEach((function(key){constructorKeys.indexOf(key)<0&&raise('invalid regl constructor argument "'+key+'". must be one of '+constructorKeys)}))}function leftPad(str,n){for(str+="";str.length0&&result.push(new ShaderError("unknown",0,errMsg))}})),result}function annotateFiles(files,errors){errors.forEach((function(error){var file=files[error.file];if(file){var line=file.index[error.line];if(line)return line.errors.push(error),void(file.hasErrors=!0)}files.unknown.hasErrors=!0,files.unknown.lines[0].errors.push(error)}))}function checkShaderError(gl,shader,source,type,command){if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){var errLog=gl.getShaderInfoLog(shader),typeName=type===gl.FRAGMENT_SHADER?"fragment":"vertex";checkCommandType(source,"string",typeName+" shader source must be a string",command);var files=parseSource(source,command),errors=parseErrorLog(errLog);annotateFiles(files,errors),Object.keys(files).forEach((function(fileNumber){var file=files[fileNumber];if(file.hasErrors){var strings=[""],styles=[""];push("file number "+fileNumber+": "+file.name+"\n","color:red;text-decoration:underline;font-weight:bold"),file.lines.forEach((function(line){if(line.errors.length>0){push(leftPad(line.number,4)+"| ","background-color:yellow; font-weight:bold"),push(line.line+endl,"color:red; background-color:yellow; font-weight:bold");var offset=0;line.errors.forEach((function(error){var message=error.message,token=/^\s*'(.*)'\s*:\s*(.*)$/.exec(message);if(token){var tokenPat=token[1];message=token[2],"assign"===tokenPat&&(tokenPat="="),offset=Math.max(line.line.indexOf(tokenPat,offset),0)}else offset=0;push(leftPad("| ",6)),push(leftPad("^^^",offset+3)+endl,"font-weight:bold"),push(leftPad("| ",6)),push(message+endl,"font-weight:bold")})),push(leftPad("| ",6)+endl)}else push(leftPad(line.number,4)+"| "),push(line.line+endl,"color:red")})),"undefined"==typeof document||window.chrome?console.log(strings.join("")):(styles[0]=strings.join("%c"),console.log.apply(console,styles))}function push(str,style){strings.push(str),styles.push(style||"")}})),check.raise("Error compiling "+typeName+" shader, "+files[0].name)}}function checkLinkError(gl,program,fragShader,vertShader,command){if(!gl.getProgramParameter(program,gl.LINK_STATUS)){var errLog=gl.getProgramInfoLog(program),fragParse=parseSource(fragShader,command),header='Error linking program with vertex shader, "'+parseSource(vertShader,command)[0].name+'", and fragment shader "'+fragParse[0].name+'"';"undefined"!=typeof document?console.log("%c"+header+endl+"%c"+errLog,"color:red;text-decoration:underline;font-weight:bold","color:red"):console.log(header+endl+errLog),check.raise(header)}}function saveCommandRef(object){object._commandRef=guessCommand()}function saveDrawCommandInfo(opts,uniforms,attributes,stringStore){function id(str){return str?stringStore.id(str):0}function addProps(dict,set){Object.keys(set).forEach((function(u){dict[stringStore.id(u)]=!0}))}saveCommandRef(opts),opts._fragId=id(opts.static.frag),opts._vertId=id(opts.static.vert);var uniformSet=opts._uniformSet={};addProps(uniformSet,uniforms.static),addProps(uniformSet,uniforms.dynamic);var attributeSet=opts._attributeSet={};addProps(attributeSet,attributes.static),addProps(attributeSet,attributes.dynamic),opts._hasCount="count"in opts.static||"count"in opts.dynamic||"elements"in opts.static||"elements"in opts.dynamic}function commandRaise(message,command){var callSite=guessCallSite();raise(message+" in command "+(command||guessCommand())+("unknown"===callSite?"":" called from "+callSite))}function checkCommand(pred,message,command){pred||commandRaise(message,command||guessCommand())}function checkParameterCommand(param,possibilities,message,command){param in possibilities||commandRaise("unknown parameter ("+param+")"+encolon(message)+". possible values: "+Object.keys(possibilities).join(),command||guessCommand())}function checkCommandType(value,type,message,command){standardTypeEh(value,type)||commandRaise("invalid parameter type"+encolon(message)+". expected "+type+", got "+typeof value,command||guessCommand())}function checkOptional(block){block()}function checkFramebufferFormat(attachment,texFormats,rbFormats){attachment.texture?checkOneOf(attachment.texture._texture.internalformat,texFormats,"unsupported texture format for attachment"):checkOneOf(attachment.renderbuffer._renderbuffer.format,rbFormats,"unsupported renderbuffer format for attachment")}var GL_CLAMP_TO_EDGE=33071,GL_NEAREST=9728,GL_NEAREST_MIPMAP_NEAREST=9984,GL_LINEAR_MIPMAP_NEAREST=9985,GL_NEAREST_MIPMAP_LINEAR=9986,GL_LINEAR_MIPMAP_LINEAR=9987,GL_UNSIGNED_BYTE=5121,GL_SHORT=5122,GL_UNSIGNED_SHORT=5123,GL_INT=5124,GL_UNSIGNED_INT=5125,GL_FLOAT=5126,GL_UNSIGNED_SHORT_4_4_4_4=32819,GL_UNSIGNED_SHORT_5_5_5_1=32820,GL_UNSIGNED_SHORT_5_6_5=33635,GL_UNSIGNED_INT_24_8_WEBGL=34042,GL_HALF_FLOAT_OES=36193,TYPE_SIZE={};function pixelSize(type,channels){return type===GL_UNSIGNED_SHORT_5_5_5_1||type===GL_UNSIGNED_SHORT_4_4_4_4||type===GL_UNSIGNED_SHORT_5_6_5?2:type===GL_UNSIGNED_INT_24_8_WEBGL?4:TYPE_SIZE[type]*channels}function isPow2(v){return!(v&v-1||!v)}function checkTexture2D(info,mipData,limits){var i,w=mipData.width,h=mipData.height,c=mipData.channels;check(w>0&&w<=limits.maxTextureSize&&h>0&&h<=limits.maxTextureSize,"invalid texture shape"),info.wrapS===GL_CLAMP_TO_EDGE&&info.wrapT===GL_CLAMP_TO_EDGE||check(isPow2(w)&&isPow2(h),"incompatible wrap mode for texture, both width and height must be power of 2"),1===mipData.mipmask?1!==w&&1!==h&&check(info.minFilter!==GL_NEAREST_MIPMAP_NEAREST&&info.minFilter!==GL_NEAREST_MIPMAP_LINEAR&&info.minFilter!==GL_LINEAR_MIPMAP_NEAREST&&info.minFilter!==GL_LINEAR_MIPMAP_LINEAR,"min filter requires mipmap"):(check(isPow2(w)&&isPow2(h),"texture must be a square power of 2 to support mipmapping"),check(mipData.mipmask===(w<<1)-1,"missing or incomplete mipmap data")),mipData.type===GL_FLOAT&&(limits.extensions.indexOf("oes_texture_float_linear")<0&&check(info.minFilter===GL_NEAREST&&info.magFilter===GL_NEAREST,"filter not supported, must enable oes_texture_float_linear"),check(!info.genMipmaps,"mipmap generation not supported with float textures"));var mipimages=mipData.images;for(i=0;i<16;++i)if(mipimages[i]){var mw=w>>i,mh=h>>i;check(mipData.mipmask&1<0&&w<=limits.maxTextureSize&&h>0&&h<=limits.maxTextureSize,"invalid texture shape"),check(w===h,"cube map must be square"),check(info.wrapS===GL_CLAMP_TO_EDGE&&info.wrapT===GL_CLAMP_TO_EDGE,"wrap mode not supported by cube map");for(var i=0;i>j,mh=h>>j;check(face.mipmask&1<1&&firstChar===lastChar&&('"'===firstChar||"'"===firstChar))return['"'+escapeStr(str.substr(1,str.length-2))+'"'];var parts=/\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(str);if(parts)return splitParts(str.substr(0,parts.index)).concat(splitParts(parts[1])).concat(splitParts(str.substr(parts.index+parts[0].length)));var subparts=str.split(".");if(1===subparts.length)return['"'+escapeStr(str)+'"'];for(var result=[],i=0;i0,"invalid pixel ratio"))):check$1.raise("invalid arguments to regl"),element&&("canvas"===element.nodeName.toLowerCase()?canvas=element:container=element),!gl){if(!canvas){check$1("undefined"!=typeof document,"must manually specify webgl context outside of DOM environments");var result=createCanvas(container||document.body,onDone,pixelRatio);if(!result)return null;canvas=result.canvas,onDestroy=result.onDestroy}void 0===contextAttributes.premultipliedAlpha&&(contextAttributes.premultipliedAlpha=!0),gl=createContext(canvas,contextAttributes)}return gl?{gl:gl,canvas:canvas,container:container,extensions:extensions,optionalExtensions:optionalExtensions,pixelRatio:pixelRatio,profile:profile,onDone:onDone,onDestroy:onDestroy}:(onDestroy(),onDone("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"),null)}function createExtensionCache(gl,config){var extensions={};function tryLoadExtension(name_){check$1.type(name_,"string","extension name must be string");var ext,name=name_.toLowerCase();try{ext=extensions[name]=gl.getExtension(name)}catch(e){}return!!ext}for(var i=0;i65535)<<4,r|=shift=((v>>>=r)>255)<<3,r|=shift=((v>>>=shift)>15)<<2,(r|=shift=((v>>>=shift)>3)<<1)|(v>>>=shift)>>1}function createPool(){var bufferPool=loop(8,(function(){return[]}));function alloc(n){var sz=nextPow16(n),bin=bufferPool[log2(sz)>>2];return bin.length>0?bin.pop():new ArrayBuffer(sz)}function free(buf){bufferPool[log2(buf.byteLength)>>2].push(buf)}function allocType(type,n){var result=null;switch(type){case GL_BYTE$1:result=new Int8Array(alloc(n),0,n);break;case GL_UNSIGNED_BYTE$2:result=new Uint8Array(alloc(n),0,n);break;case GL_SHORT$1:result=new Int16Array(alloc(2*n),0,n);break;case GL_UNSIGNED_SHORT$1:result=new Uint16Array(alloc(2*n),0,n);break;case GL_INT$1:result=new Int32Array(alloc(4*n),0,n);break;case GL_UNSIGNED_INT$1:result=new Uint32Array(alloc(4*n),0,n);break;case GL_FLOAT$2:result=new Float32Array(alloc(4*n),0,n);break;default:return null}return result.length!==n?result.subarray(0,n):result}function freeType(array){free(array.buffer)}return{alloc:alloc,free:free,allocType:allocType,freeType:freeType}}var pool=createPool();pool.zero=createPool();var GL_SUBPIXEL_BITS=3408,GL_RED_BITS=3410,GL_GREEN_BITS=3411,GL_BLUE_BITS=3412,GL_ALPHA_BITS=3413,GL_DEPTH_BITS=3414,GL_STENCIL_BITS=3415,GL_ALIASED_POINT_SIZE_RANGE=33901,GL_ALIASED_LINE_WIDTH_RANGE=33902,GL_MAX_TEXTURE_SIZE=3379,GL_MAX_VIEWPORT_DIMS=3386,GL_MAX_VERTEX_ATTRIBS=34921,GL_MAX_VERTEX_UNIFORM_VECTORS=36347,GL_MAX_VARYING_VECTORS=36348,GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS=35661,GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS=35660,GL_MAX_TEXTURE_IMAGE_UNITS=34930,GL_MAX_FRAGMENT_UNIFORM_VECTORS=36349,GL_MAX_CUBE_MAP_TEXTURE_SIZE=34076,GL_MAX_RENDERBUFFER_SIZE=34024,GL_VENDOR=7936,GL_RENDERER=7937,GL_VERSION=7938,GL_SHADING_LANGUAGE_VERSION=35724,GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT=34047,GL_MAX_COLOR_ATTACHMENTS_WEBGL=36063,GL_MAX_DRAW_BUFFERS_WEBGL=34852,GL_TEXTURE_2D=3553,GL_TEXTURE_CUBE_MAP=34067,GL_TEXTURE_CUBE_MAP_POSITIVE_X=34069,GL_TEXTURE0=33984,GL_RGBA=6408,GL_FLOAT$1=5126,GL_UNSIGNED_BYTE$1=5121,GL_FRAMEBUFFER=36160,GL_FRAMEBUFFER_COMPLETE=36053,GL_COLOR_ATTACHMENT0=36064,GL_COLOR_BUFFER_BIT$1=16384,wrapLimits=function(gl,extensions){var maxAnisotropic=1;extensions.ext_texture_filter_anisotropic&&(maxAnisotropic=gl.getParameter(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT));var maxDrawbuffers=1,maxColorAttachments=1;extensions.webgl_draw_buffers&&(maxDrawbuffers=gl.getParameter(GL_MAX_DRAW_BUFFERS_WEBGL),maxColorAttachments=gl.getParameter(GL_MAX_COLOR_ATTACHMENTS_WEBGL));var readFloat=!!extensions.oes_texture_float;if(readFloat){var readFloatTexture=gl.createTexture();gl.bindTexture(GL_TEXTURE_2D,readFloatTexture),gl.texImage2D(GL_TEXTURE_2D,0,GL_RGBA,1,1,0,GL_RGBA,GL_FLOAT$1,null);var fbo=gl.createFramebuffer();if(gl.bindFramebuffer(GL_FRAMEBUFFER,fbo),gl.framebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,readFloatTexture,0),gl.bindTexture(GL_TEXTURE_2D,null),gl.checkFramebufferStatus(GL_FRAMEBUFFER)!==GL_FRAMEBUFFER_COMPLETE)readFloat=!1;else{gl.viewport(0,0,1,1),gl.clearColor(1,0,0,1),gl.clear(GL_COLOR_BUFFER_BIT$1);var pixels=pool.allocType(GL_FLOAT$1,4);gl.readPixels(0,0,1,1,GL_RGBA,GL_FLOAT$1,pixels),gl.getError()?readFloat=!1:(gl.deleteFramebuffer(fbo),gl.deleteTexture(readFloatTexture),readFloat=1===pixels[0]),pool.freeType(pixels)}}var npotTextureCube=!0;if("undefined"==typeof navigator||!(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)||/Edge/.test(navigator.userAgent))){var cubeTexture=gl.createTexture(),data=pool.allocType(GL_UNSIGNED_BYTE$1,36);gl.activeTexture(GL_TEXTURE0),gl.bindTexture(GL_TEXTURE_CUBE_MAP,cubeTexture),gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X,0,GL_RGBA,3,3,0,GL_RGBA,GL_UNSIGNED_BYTE$1,data),pool.freeType(data),gl.bindTexture(GL_TEXTURE_CUBE_MAP,null),gl.deleteTexture(cubeTexture),npotTextureCube=!gl.getError()}return{colorBits:[gl.getParameter(GL_RED_BITS),gl.getParameter(GL_GREEN_BITS),gl.getParameter(GL_BLUE_BITS),gl.getParameter(GL_ALPHA_BITS)],depthBits:gl.getParameter(GL_DEPTH_BITS),stencilBits:gl.getParameter(GL_STENCIL_BITS),subpixelBits:gl.getParameter(GL_SUBPIXEL_BITS),extensions:Object.keys(extensions).filter((function(ext){return!!extensions[ext]})),maxAnisotropic:maxAnisotropic,maxDrawbuffers:maxDrawbuffers,maxColorAttachments:maxColorAttachments,pointSizeDims:gl.getParameter(GL_ALIASED_POINT_SIZE_RANGE),lineWidthDims:gl.getParameter(GL_ALIASED_LINE_WIDTH_RANGE),maxViewportDims:gl.getParameter(GL_MAX_VIEWPORT_DIMS),maxCombinedTextureUnits:gl.getParameter(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxCubeMapSize:gl.getParameter(GL_MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderbufferSize:gl.getParameter(GL_MAX_RENDERBUFFER_SIZE),maxTextureUnits:gl.getParameter(GL_MAX_TEXTURE_IMAGE_UNITS),maxTextureSize:gl.getParameter(GL_MAX_TEXTURE_SIZE),maxAttributes:gl.getParameter(GL_MAX_VERTEX_ATTRIBS),maxVertexUniforms:gl.getParameter(GL_MAX_VERTEX_UNIFORM_VECTORS),maxVertexTextureUnits:gl.getParameter(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxVaryingVectors:gl.getParameter(GL_MAX_VARYING_VECTORS),maxFragmentUniforms:gl.getParameter(GL_MAX_FRAGMENT_UNIFORM_VECTORS),glsl:gl.getParameter(GL_SHADING_LANGUAGE_VERSION),renderer:gl.getParameter(GL_RENDERER),vendor:gl.getParameter(GL_VENDOR),version:gl.getParameter(GL_VERSION),readFloat:readFloat,npotTextureCube:npotTextureCube}};function isNDArrayLike(obj){return!!obj&&"object"==typeof obj&&Array.isArray(obj.shape)&&Array.isArray(obj.stride)&&"number"==typeof obj.offset&&obj.shape.length===obj.stride.length&&(Array.isArray(obj.data)||isTypedArray(obj.data))}var values=function(obj){return Object.keys(obj).map((function(key){return obj[key]}))},flattenUtils={shape:arrayShape$1,flatten:flattenArray};function flatten1D(array,nx,out){for(var i=0;i0)if(Array.isArray(data[0])){shape=arrayShape(data);for(var dim=1,i=1;i0)if("number"==typeof data[0]){var converted=pool.allocType(buffer.dtype,data.length);copyArray(converted,data),setSubData(converted,offset),pool.freeType(converted)}else if(Array.isArray(data[0])||isTypedArray(data[0])){shape=arrayShape(data);var flatData=arrayFlatten(data,shape,buffer.dtype);setSubData(flatData,offset),pool.freeType(flatData)}else check$1.raise("invalid buffer data")}else if(isNDArrayLike(data)){shape=data.shape;var stride=data.stride,shapeX=0,shapeY=0,strideX=0,strideY=0;1===shape.length?(shapeX=shape[0],shapeY=1,strideX=stride[0],strideY=0):2===shape.length?(shapeX=shape[0],shapeY=shape[1],strideX=stride[0],strideY=stride[1]):check$1.raise("invalid shape");var dtype=Array.isArray(data.data)?buffer.dtype:typedArrayCode(data.data),transposeData=pool.allocType(dtype,shapeX*shapeY);transpose(transposeData,data.data,shapeX,shapeY,strideX,strideY,data.offset),setSubData(transposeData,offset),pool.freeType(transposeData)}else check$1.raise("invalid data for buffer subdata");return reglBuffer}return bufferSet[buffer.id]=buffer,deferInit||reglBuffer(options),reglBuffer._reglType="buffer",reglBuffer._buffer=buffer,reglBuffer.subdata=subdata,config.profile&&(reglBuffer.stats=buffer.stats),reglBuffer.destroy=function(){destroy(buffer)},reglBuffer}function restoreBuffers(){values(bufferSet).forEach((function(buffer){buffer.buffer=gl.createBuffer(),gl.bindBuffer(buffer.type,buffer.buffer),gl.bufferData(buffer.type,buffer.persistentData||buffer.byteLength,buffer.usage)}))}return config.profile&&(stats.getTotalBufferSize=function(){var total=0;return Object.keys(bufferSet).forEach((function(key){total+=bufferSet[key].stats.size})),total}),{create:createBuffer,createStream:createStream,destroyStream:destroyStream,clear:function(){values(bufferSet).forEach(destroy),streamPool.forEach(destroy)},getBuffer:function(wrapper){return wrapper&&wrapper._buffer instanceof REGLBuffer?wrapper._buffer:null},restore:restoreBuffers,_initBuffer:initBufferFromData}}DTYPES_SIZES[5120]=1,DTYPES_SIZES[5122]=2,DTYPES_SIZES[5124]=4,DTYPES_SIZES[5121]=1,DTYPES_SIZES[5123]=2,DTYPES_SIZES[5125]=4,DTYPES_SIZES[5126]=4;var primTypes={points:0,point:0,lines:1,line:1,triangles:4,triangle:4,"line loop":2,"line strip":3,"triangle strip":5,"triangle fan":6},GL_POINTS=0,GL_LINES=1,GL_TRIANGLES=4,GL_BYTE$2=5120,GL_UNSIGNED_BYTE$4=5121,GL_SHORT$2=5122,GL_UNSIGNED_SHORT$2=5123,GL_INT$2=5124,GL_UNSIGNED_INT$2=5125,GL_ELEMENT_ARRAY_BUFFER=34963,GL_STREAM_DRAW$1=35040,GL_STATIC_DRAW$1=35044;function wrapElementsState(gl,extensions,bufferState,stats){var elementSet={},elementCount=0,elementTypes={uint8:GL_UNSIGNED_BYTE$4,uint16:GL_UNSIGNED_SHORT$2};function REGLElementBuffer(buffer){this.id=elementCount++,elementSet[this.id]=this,this.buffer=buffer,this.primType=GL_TRIANGLES,this.vertCount=0,this.type=0}extensions.oes_element_index_uint&&(elementTypes.uint32=GL_UNSIGNED_INT$2),REGLElementBuffer.prototype.bind=function(){this.buffer.bind()};var bufferPool=[];function createElementStream(data){var result=bufferPool.pop();return result||(result=new REGLElementBuffer(bufferState.create(null,GL_ELEMENT_ARRAY_BUFFER,!0,!1)._buffer)),initElements(result,data,GL_STREAM_DRAW$1,-1,-1,0,0),result}function destroyElementStream(elements){bufferPool.push(elements)}function initElements(elements,data,usage,prim,count,byteLength,type){var dtype;if(elements.buffer.bind(),data){var predictedType=type;type||isTypedArray(data)&&(!isNDArrayLike(data)||isTypedArray(data.data))||(predictedType=extensions.oes_element_index_uint?GL_UNSIGNED_INT$2:GL_UNSIGNED_SHORT$2),bufferState._initBuffer(elements.buffer,data,usage,predictedType,3)}else gl.bufferData(GL_ELEMENT_ARRAY_BUFFER,byteLength,usage),elements.buffer.dtype=dtype||GL_UNSIGNED_BYTE$4,elements.buffer.usage=usage,elements.buffer.dimension=3,elements.buffer.byteLength=byteLength;if(dtype=type,!type){switch(elements.buffer.dtype){case GL_UNSIGNED_BYTE$4:case GL_BYTE$2:dtype=GL_UNSIGNED_BYTE$4;break;case GL_UNSIGNED_SHORT$2:case GL_SHORT$2:dtype=GL_UNSIGNED_SHORT$2;break;case GL_UNSIGNED_INT$2:case GL_INT$2:dtype=GL_UNSIGNED_INT$2;break;default:check$1.raise("unsupported type for element array")}elements.buffer.dtype=dtype}elements.type=dtype,check$1(dtype!==GL_UNSIGNED_INT$2||!!extensions.oes_element_index_uint,"32 bit element buffers not supported, enable oes_element_index_uint first");var vertCount=count;vertCount<0&&(vertCount=elements.buffer.byteLength,dtype===GL_UNSIGNED_SHORT$2?vertCount>>=1:dtype===GL_UNSIGNED_INT$2&&(vertCount>>=2)),elements.vertCount=vertCount;var primType=prim;if(prim<0){primType=GL_TRIANGLES;var dimension=elements.buffer.dimension;1===dimension&&(primType=GL_POINTS),2===dimension&&(primType=GL_LINES),3===dimension&&(primType=GL_TRIANGLES)}elements.primType=primType}function destroyElements(elements){stats.elementsCount--,check$1(null!==elements.buffer,"must not double destroy elements"),delete elementSet[elements.id],elements.buffer.destroy(),elements.buffer=null}function createElements(options,persistent){var buffer=bufferState.create(null,GL_ELEMENT_ARRAY_BUFFER,!0),elements=new REGLElementBuffer(buffer._buffer);function reglElements(options){if(options)if("number"==typeof options)buffer(options),elements.primType=GL_TRIANGLES,elements.vertCount=0|options,elements.type=GL_UNSIGNED_BYTE$4;else{var data=null,usage=GL_STATIC_DRAW$1,primType=-1,vertCount=-1,byteLength=0,dtype=0;Array.isArray(options)||isTypedArray(options)||isNDArrayLike(options)?data=options:(check$1.type(options,"object","invalid arguments for elements"),"data"in options&&(data=options.data,check$1(Array.isArray(data)||isTypedArray(data)||isNDArrayLike(data),"invalid data for element buffer")),"usage"in options&&(check$1.parameter(options.usage,usageTypes,"invalid element buffer usage"),usage=usageTypes[options.usage]),"primitive"in options&&(check$1.parameter(options.primitive,primTypes,"invalid element buffer primitive"),primType=primTypes[options.primitive]),"count"in options&&(check$1("number"==typeof options.count&&options.count>=0,"invalid vertex count for elements"),vertCount=0|options.count),"type"in options&&(check$1.parameter(options.type,elementTypes,"invalid buffer type"),dtype=elementTypes[options.type]),"length"in options?byteLength=0|options.length:(byteLength=vertCount,dtype===GL_UNSIGNED_SHORT$2||dtype===GL_SHORT$2?byteLength*=2:dtype!==GL_UNSIGNED_INT$2&&dtype!==GL_INT$2||(byteLength*=4))),initElements(elements,data,usage,primType,vertCount,byteLength,dtype)}else buffer(),elements.primType=GL_TRIANGLES,elements.vertCount=0,elements.type=GL_UNSIGNED_BYTE$4;return reglElements}return stats.elementsCount++,reglElements(options),reglElements._reglType="elements",reglElements._elements=elements,reglElements.subdata=function(data,offset){return buffer.subdata(data,offset),reglElements},reglElements.destroy=function(){destroyElements(elements)},reglElements}return{create:createElements,createStream:createElementStream,destroyStream:destroyElementStream,getElements:function(elements){return"function"==typeof elements&&elements._elements instanceof REGLElementBuffer?elements._elements:null},clear:function(){values(elementSet).forEach(destroyElements)}}}var FLOAT=new Float32Array(1),INT=new Uint32Array(FLOAT.buffer),GL_UNSIGNED_SHORT$4=5123;function convertToHalfFloat(array){for(var ushorts=pool.allocType(GL_UNSIGNED_SHORT$4,array.length),i=0;i>>31<<15,exp=(x<<1>>>24)-127,frac=x>>13&1023;if(exp<-24)ushorts[i]=sgn;else if(exp<-14){var s=-14-exp;ushorts[i]=sgn+(frac+1024>>s)}else ushorts[i]=exp>15?sgn+31744:sgn+(exp+15<<10)+frac}return ushorts}function isArrayLike(s){return Array.isArray(s)||isTypedArray(s)}var isPow2$1=function(v){return!(v&v-1||!v)},GL_COMPRESSED_TEXTURE_FORMATS=34467,GL_TEXTURE_2D$1=3553,GL_TEXTURE_CUBE_MAP$1=34067,GL_TEXTURE_CUBE_MAP_POSITIVE_X$1=34069,GL_RGBA$1=6408,GL_ALPHA=6406,GL_RGB=6407,GL_LUMINANCE=6409,GL_LUMINANCE_ALPHA=6410,GL_RGBA4=32854,GL_RGB5_A1=32855,GL_RGB565=36194,GL_UNSIGNED_SHORT_4_4_4_4$1=32819,GL_UNSIGNED_SHORT_5_5_5_1$1=32820,GL_UNSIGNED_SHORT_5_6_5$1=33635,GL_UNSIGNED_INT_24_8_WEBGL$1=34042,GL_DEPTH_COMPONENT=6402,GL_DEPTH_STENCIL=34041,GL_SRGB_EXT=35904,GL_SRGB_ALPHA_EXT=35906,GL_HALF_FLOAT_OES$1=36193,GL_COMPRESSED_RGB_S3TC_DXT1_EXT=33776,GL_COMPRESSED_RGBA_S3TC_DXT1_EXT=33777,GL_COMPRESSED_RGBA_S3TC_DXT3_EXT=33778,GL_COMPRESSED_RGBA_S3TC_DXT5_EXT=33779,GL_COMPRESSED_RGB_ATC_WEBGL=35986,GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=35987,GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=34798,GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840,GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG=35841,GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842,GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=35843,GL_COMPRESSED_RGB_ETC1_WEBGL=36196,GL_UNSIGNED_BYTE$5=5121,GL_UNSIGNED_SHORT$3=5123,GL_UNSIGNED_INT$3=5125,GL_FLOAT$4=5126,GL_TEXTURE_WRAP_S=10242,GL_TEXTURE_WRAP_T=10243,GL_REPEAT=10497,GL_CLAMP_TO_EDGE$1=33071,GL_MIRRORED_REPEAT=33648,GL_TEXTURE_MAG_FILTER=10240,GL_TEXTURE_MIN_FILTER=10241,GL_NEAREST$1=9728,GL_LINEAR=9729,GL_NEAREST_MIPMAP_NEAREST$1=9984,GL_LINEAR_MIPMAP_NEAREST$1=9985,GL_NEAREST_MIPMAP_LINEAR$1=9986,GL_LINEAR_MIPMAP_LINEAR$1=9987,GL_GENERATE_MIPMAP_HINT=33170,GL_DONT_CARE=4352,GL_FASTEST=4353,GL_NICEST=4354,GL_TEXTURE_MAX_ANISOTROPY_EXT=34046,GL_UNPACK_ALIGNMENT=3317,GL_UNPACK_FLIP_Y_WEBGL=37440,GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL=37441,GL_UNPACK_COLORSPACE_CONVERSION_WEBGL=37443,GL_BROWSER_DEFAULT_WEBGL=37444,GL_TEXTURE0$1=33984,MIPMAP_FILTERS=[GL_NEAREST_MIPMAP_NEAREST$1,GL_NEAREST_MIPMAP_LINEAR$1,GL_LINEAR_MIPMAP_NEAREST$1,GL_LINEAR_MIPMAP_LINEAR$1],CHANNELS_FORMAT=[0,GL_LUMINANCE,GL_LUMINANCE_ALPHA,GL_RGB,GL_RGBA$1],FORMAT_CHANNELS={};function objectName(str){return"[object "+str+"]"}FORMAT_CHANNELS[GL_LUMINANCE]=FORMAT_CHANNELS[GL_ALPHA]=FORMAT_CHANNELS[GL_DEPTH_COMPONENT]=1,FORMAT_CHANNELS[GL_DEPTH_STENCIL]=FORMAT_CHANNELS[GL_LUMINANCE_ALPHA]=2,FORMAT_CHANNELS[GL_RGB]=FORMAT_CHANNELS[GL_SRGB_EXT]=3,FORMAT_CHANNELS[GL_RGBA$1]=FORMAT_CHANNELS[GL_SRGB_ALPHA_EXT]=4;var CANVAS_CLASS=objectName("HTMLCanvasElement"),OFFSCREENCANVAS_CLASS=objectName("OffscreenCanvas"),CONTEXT2D_CLASS=objectName("CanvasRenderingContext2D"),BITMAP_CLASS=objectName("ImageBitmap"),IMAGE_CLASS=objectName("HTMLImageElement"),VIDEO_CLASS=objectName("HTMLVideoElement"),PIXEL_CLASSES=Object.keys(arrayTypes).concat([CANVAS_CLASS,OFFSCREENCANVAS_CLASS,CONTEXT2D_CLASS,BITMAP_CLASS,IMAGE_CLASS,VIDEO_CLASS]),TYPE_SIZES=[];TYPE_SIZES[GL_UNSIGNED_BYTE$5]=1,TYPE_SIZES[GL_FLOAT$4]=4,TYPE_SIZES[GL_HALF_FLOAT_OES$1]=2,TYPE_SIZES[GL_UNSIGNED_SHORT$3]=2,TYPE_SIZES[GL_UNSIGNED_INT$3]=4;var FORMAT_SIZES_SPECIAL=[];function isNumericArray(arr){return Array.isArray(arr)&&(0===arr.length||"number"==typeof arr[0])}function isRectArray(arr){return!!Array.isArray(arr)&&!(0===arr.length||!isArrayLike(arr[0]))}function classString(x){return Object.prototype.toString.call(x)}function isCanvasElement(object){return classString(object)===CANVAS_CLASS}function isOffscreenCanvas(object){return classString(object)===OFFSCREENCANVAS_CLASS}function isContext2D(object){return classString(object)===CONTEXT2D_CLASS}function isBitmap(object){return classString(object)===BITMAP_CLASS}function isImageElement(object){return classString(object)===IMAGE_CLASS}function isVideoElement(object){return classString(object)===VIDEO_CLASS}function isPixelData(object){if(!object)return!1;var className=classString(object);return PIXEL_CLASSES.indexOf(className)>=0||isNumericArray(object)||isRectArray(object)||isNDArrayLike(object)}function typedArrayCode$1(data){return 0|arrayTypes[Object.prototype.toString.call(data)]}function convertData(result,data){var n=data.length;switch(result.type){case GL_UNSIGNED_BYTE$5:case GL_UNSIGNED_SHORT$3:case GL_UNSIGNED_INT$3:case GL_FLOAT$4:var converted=pool.allocType(result.type,n);converted.set(data),result.data=converted;break;case GL_HALF_FLOAT_OES$1:result.data=convertToHalfFloat(data);break;default:check$1.raise("unsupported texture type, must specify a typed array")}}function preConvert(image,n){return pool.allocType(image.type===GL_HALF_FLOAT_OES$1?GL_FLOAT$4:image.type,n)}function postConvert(image,data){image.type===GL_HALF_FLOAT_OES$1?(image.data=convertToHalfFloat(data),pool.freeType(data)):image.data=data}function transposeData(image,array,strideX,strideY,strideC,offset){for(var w=image.width,h=image.height,c=image.channels,data=preConvert(image,w*h*c),p=0,i=0;i=1;)total+=s*w*w,w/=2;return total}return s*width*height}function createTextureSet(gl,extensions,limits,reglPoll,contextState,stats,config){var mipmapHint={"don't care":GL_DONT_CARE,"dont care":GL_DONT_CARE,nice:GL_NICEST,fast:GL_FASTEST},wrapModes={repeat:GL_REPEAT,clamp:GL_CLAMP_TO_EDGE$1,mirror:GL_MIRRORED_REPEAT},magFilters={nearest:GL_NEAREST$1,linear:GL_LINEAR},minFilters=extend({mipmap:GL_LINEAR_MIPMAP_LINEAR$1,"nearest mipmap nearest":GL_NEAREST_MIPMAP_NEAREST$1,"linear mipmap nearest":GL_LINEAR_MIPMAP_NEAREST$1,"nearest mipmap linear":GL_NEAREST_MIPMAP_LINEAR$1,"linear mipmap linear":GL_LINEAR_MIPMAP_LINEAR$1},magFilters),colorSpace={none:0,browser:GL_BROWSER_DEFAULT_WEBGL},textureTypes={uint8:GL_UNSIGNED_BYTE$5,rgba4:GL_UNSIGNED_SHORT_4_4_4_4$1,rgb565:GL_UNSIGNED_SHORT_5_6_5$1,"rgb5 a1":GL_UNSIGNED_SHORT_5_5_5_1$1},textureFormats={alpha:GL_ALPHA,luminance:GL_LUMINANCE,"luminance alpha":GL_LUMINANCE_ALPHA,rgb:GL_RGB,rgba:GL_RGBA$1,rgba4:GL_RGBA4,"rgb5 a1":GL_RGB5_A1,rgb565:GL_RGB565},compressedTextureFormats={};extensions.ext_srgb&&(textureFormats.srgb=GL_SRGB_EXT,textureFormats.srgba=GL_SRGB_ALPHA_EXT),extensions.oes_texture_float&&(textureTypes.float32=textureTypes.float=GL_FLOAT$4),extensions.oes_texture_half_float&&(textureTypes.float16=textureTypes["half float"]=GL_HALF_FLOAT_OES$1),extensions.webgl_depth_texture&&(extend(textureFormats,{depth:GL_DEPTH_COMPONENT,"depth stencil":GL_DEPTH_STENCIL}),extend(textureTypes,{uint16:GL_UNSIGNED_SHORT$3,uint32:GL_UNSIGNED_INT$3,"depth stencil":GL_UNSIGNED_INT_24_8_WEBGL$1})),extensions.webgl_compressed_texture_s3tc&&extend(compressedTextureFormats,{"rgb s3tc dxt1":GL_COMPRESSED_RGB_S3TC_DXT1_EXT,"rgba s3tc dxt1":GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,"rgba s3tc dxt3":GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,"rgba s3tc dxt5":GL_COMPRESSED_RGBA_S3TC_DXT5_EXT}),extensions.webgl_compressed_texture_atc&&extend(compressedTextureFormats,{"rgb atc":GL_COMPRESSED_RGB_ATC_WEBGL,"rgba atc explicit alpha":GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL,"rgba atc interpolated alpha":GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL}),extensions.webgl_compressed_texture_pvrtc&&extend(compressedTextureFormats,{"rgb pvrtc 4bppv1":GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG,"rgb pvrtc 2bppv1":GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG,"rgba pvrtc 4bppv1":GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG,"rgba pvrtc 2bppv1":GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}),extensions.webgl_compressed_texture_etc1&&(compressedTextureFormats["rgb etc1"]=GL_COMPRESSED_RGB_ETC1_WEBGL);var supportedCompressedFormats=Array.prototype.slice.call(gl.getParameter(GL_COMPRESSED_TEXTURE_FORMATS));Object.keys(compressedTextureFormats).forEach((function(name){var format=compressedTextureFormats[name];supportedCompressedFormats.indexOf(format)>=0&&(textureFormats[name]=format)}));var supportedFormats=Object.keys(textureFormats);limits.textureFormats=supportedFormats;var textureFormatsInvert=[];Object.keys(textureFormats).forEach((function(key){var val=textureFormats[key];textureFormatsInvert[val]=key}));var textureTypesInvert=[];Object.keys(textureTypes).forEach((function(key){var val=textureTypes[key];textureTypesInvert[val]=key}));var magFiltersInvert=[];Object.keys(magFilters).forEach((function(key){var val=magFilters[key];magFiltersInvert[val]=key}));var minFiltersInvert=[];Object.keys(minFilters).forEach((function(key){var val=minFilters[key];minFiltersInvert[val]=key}));var wrapModesInvert=[];Object.keys(wrapModes).forEach((function(key){var val=wrapModes[key];wrapModesInvert[val]=key}));var colorFormats=supportedFormats.reduce((function(color,key){var glenum=textureFormats[key];return glenum===GL_LUMINANCE||glenum===GL_ALPHA||glenum===GL_LUMINANCE||glenum===GL_LUMINANCE_ALPHA||glenum===GL_DEPTH_COMPONENT||glenum===GL_DEPTH_STENCIL||extensions.ext_srgb&&(glenum===GL_SRGB_EXT||glenum===GL_SRGB_ALPHA_EXT)?color[glenum]=glenum:glenum===GL_RGB5_A1||key.indexOf("rgba")>=0?color[glenum]=GL_RGBA$1:color[glenum]=GL_RGB,color}),{});function TexFlags(){this.internalformat=GL_RGBA$1,this.format=GL_RGBA$1,this.type=GL_UNSIGNED_BYTE$5,this.compressed=!1,this.premultiplyAlpha=!1,this.flipY=!1,this.unpackAlignment=1,this.colorSpace=GL_BROWSER_DEFAULT_WEBGL,this.width=0,this.height=0,this.channels=0}function copyFlags(result,other){result.internalformat=other.internalformat,result.format=other.format,result.type=other.type,result.compressed=other.compressed,result.premultiplyAlpha=other.premultiplyAlpha,result.flipY=other.flipY,result.unpackAlignment=other.unpackAlignment,result.colorSpace=other.colorSpace,result.width=other.width,result.height=other.height,result.channels=other.channels}function parseFlags(flags,options){if("object"==typeof options&&options){if("premultiplyAlpha"in options&&(check$1.type(options.premultiplyAlpha,"boolean","invalid premultiplyAlpha"),flags.premultiplyAlpha=options.premultiplyAlpha),"flipY"in options&&(check$1.type(options.flipY,"boolean","invalid texture flip"),flags.flipY=options.flipY),"alignment"in options&&(check$1.oneOf(options.alignment,[1,2,4,8],"invalid texture unpack alignment"),flags.unpackAlignment=options.alignment),"colorSpace"in options&&(check$1.parameter(options.colorSpace,colorSpace,"invalid colorSpace"),flags.colorSpace=colorSpace[options.colorSpace]),"type"in options){var type=options.type;check$1(extensions.oes_texture_float||!("float"===type||"float32"===type),"you must enable the OES_texture_float extension in order to use floating point textures."),check$1(extensions.oes_texture_half_float||!("half float"===type||"float16"===type),"you must enable the OES_texture_half_float extension in order to use 16-bit floating point textures."),check$1(extensions.webgl_depth_texture||!("uint16"===type||"uint32"===type||"depth stencil"===type),"you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures."),check$1.parameter(type,textureTypes,"invalid texture type"),flags.type=textureTypes[type]}var w=flags.width,h=flags.height,c=flags.channels,hasChannels=!1;"shape"in options?(check$1(Array.isArray(options.shape)&&options.shape.length>=2,"shape must be an array"),w=options.shape[0],h=options.shape[1],3===options.shape.length&&(c=options.shape[2],check$1(c>0&&c<=4,"invalid number of channels"),hasChannels=!0),check$1(w>=0&&w<=limits.maxTextureSize,"invalid width"),check$1(h>=0&&h<=limits.maxTextureSize,"invalid height")):("radius"in options&&(w=h=options.radius,check$1(w>=0&&w<=limits.maxTextureSize,"invalid radius")),"width"in options&&(w=options.width,check$1(w>=0&&w<=limits.maxTextureSize,"invalid width")),"height"in options&&(h=options.height,check$1(h>=0&&h<=limits.maxTextureSize,"invalid height")),"channels"in options&&(c=options.channels,check$1(c>0&&c<=4,"invalid number of channels"),hasChannels=!0)),flags.width=0|w,flags.height=0|h,flags.channels=0|c;var hasFormat=!1;if("format"in options){var formatStr=options.format;check$1(extensions.webgl_depth_texture||!("depth"===formatStr||"depth stencil"===formatStr),"you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures."),check$1.parameter(formatStr,textureFormats,"invalid texture format");var internalformat=flags.internalformat=textureFormats[formatStr];flags.format=colorFormats[internalformat],formatStr in textureTypes&&("type"in options||(flags.type=textureTypes[formatStr])),formatStr in compressedTextureFormats&&(flags.compressed=!0),hasFormat=!0}!hasChannels&&hasFormat?flags.channels=FORMAT_CHANNELS[flags.format]:hasChannels&&!hasFormat?flags.channels!==CHANNELS_FORMAT[flags.format]&&(flags.format=flags.internalformat=CHANNELS_FORMAT[flags.channels]):hasFormat&&hasChannels&&check$1(flags.channels===FORMAT_CHANNELS[flags.format],"number of channels inconsistent with specified format")}}function setFlags(flags){gl.pixelStorei(GL_UNPACK_FLIP_Y_WEBGL,flags.flipY),gl.pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL,flags.premultiplyAlpha),gl.pixelStorei(GL_UNPACK_COLORSPACE_CONVERSION_WEBGL,flags.colorSpace),gl.pixelStorei(GL_UNPACK_ALIGNMENT,flags.unpackAlignment)}function TexImage(){TexFlags.call(this),this.xOffset=0,this.yOffset=0,this.data=null,this.needsFree=!1,this.element=null,this.needsCopy=!1}function parseImage(image,options){var data=null;if(isPixelData(options)?data=options:options&&(check$1.type(options,"object","invalid pixel data type"),parseFlags(image,options),"x"in options&&(image.xOffset=0|options.x),"y"in options&&(image.yOffset=0|options.y),isPixelData(options.data)&&(data=options.data)),check$1(!image.compressed||data instanceof Uint8Array,"compressed texture data must be stored in a uint8array"),options.copy){check$1(!data,"can not specify copy and data field for the same texture");var viewW=contextState.viewportWidth,viewH=contextState.viewportHeight;image.width=image.width||viewW-image.xOffset,image.height=image.height||viewH-image.yOffset,image.needsCopy=!0,check$1(image.xOffset>=0&&image.xOffset=0&&image.yOffset0&&image.width<=viewW&&image.height>0&&image.height<=viewH,"copy texture read out of bounds")}else if(data){if(isTypedArray(data))image.channels=image.channels||4,image.data=data,"type"in options||image.type!==GL_UNSIGNED_BYTE$5||(image.type=typedArrayCode$1(data));else if(isNumericArray(data))image.channels=image.channels||4,convertData(image,data),image.alignment=1,image.needsFree=!0;else if(isNDArrayLike(data)){var array=data.data;Array.isArray(array)||image.type!==GL_UNSIGNED_BYTE$5||(image.type=typedArrayCode$1(array));var shapeX,shapeY,shapeC,strideX,strideY,strideC,shape=data.shape,stride=data.stride;3===shape.length?(shapeC=shape[2],strideC=stride[2]):(check$1(2===shape.length,"invalid ndarray pixel data, must be 2 or 3D"),shapeC=1,strideC=1),shapeX=shape[0],shapeY=shape[1],strideX=stride[0],strideY=stride[1],image.alignment=1,image.width=shapeX,image.height=shapeY,image.channels=shapeC,image.format=image.internalformat=CHANNELS_FORMAT[shapeC],image.needsFree=!0,transposeData(image,array,strideX,strideY,strideC,data.offset)}else if(isCanvasElement(data)||isOffscreenCanvas(data)||isContext2D(data))isCanvasElement(data)||isOffscreenCanvas(data)?image.element=data:image.element=data.canvas,image.width=image.element.width,image.height=image.element.height,image.channels=4;else if(isBitmap(data))image.element=data,image.width=data.width,image.height=data.height,image.channels=4;else if(isImageElement(data))image.element=data,image.width=data.naturalWidth,image.height=data.naturalHeight,image.channels=4;else if(isVideoElement(data))image.element=data,image.width=data.videoWidth,image.height=data.videoHeight,image.channels=4;else if(isRectArray(data)){var w=image.width||data[0].length,h=image.height||data.length,c=image.channels;c=isArrayLike(data[0][0])?c||data[0][0].length:c||1;for(var arrayShape=flattenUtils.shape(data),n=1,dd=0;dd=0,"oes_texture_float extension not enabled"):image.type===GL_HALF_FLOAT_OES$1&&check$1(limits.extensions.indexOf("oes_texture_half_float")>=0,"oes_texture_half_float extension not enabled")}function setImage(info,target,miplevel){var element=info.element,data=info.data,internalformat=info.internalformat,format=info.format,type=info.type,width=info.width,height=info.height;setFlags(info),element?gl.texImage2D(target,miplevel,format,format,type,element):info.compressed?gl.compressedTexImage2D(target,miplevel,internalformat,width,height,0,data):info.needsCopy?(reglPoll(),gl.copyTexImage2D(target,miplevel,format,info.xOffset,info.yOffset,width,height,0)):gl.texImage2D(target,miplevel,format,width,height,0,format,type,data||null)}function setSubImage(info,target,x,y,miplevel){var element=info.element,data=info.data,internalformat=info.internalformat,format=info.format,type=info.type,width=info.width,height=info.height;setFlags(info),element?gl.texSubImage2D(target,miplevel,x,y,format,type,element):info.compressed?gl.compressedTexSubImage2D(target,miplevel,x,y,internalformat,width,height,data):info.needsCopy?(reglPoll(),gl.copyTexSubImage2D(target,miplevel,x,y,info.xOffset,info.yOffset,width,height)):gl.texSubImage2D(target,miplevel,x,y,width,height,format,type,data)}var imagePool=[];function allocImage(){return imagePool.pop()||new TexImage}function freeImage(image){image.needsFree&&pool.freeType(image.data),TexImage.call(image),imagePool.push(image)}function MipMap(){TexFlags.call(this),this.genMipmaps=!1,this.mipmapHint=GL_DONT_CARE,this.mipmask=0,this.images=Array(16)}function parseMipMapFromShape(mipmap,width,height){var img=mipmap.images[0]=allocImage();mipmap.mipmask=1,img.width=mipmap.width=width,img.height=mipmap.height=height,img.channels=mipmap.channels=4}function parseMipMapFromObject(mipmap,options){var imgData=null;if(isPixelData(options))copyFlags(imgData=mipmap.images[0]=allocImage(),mipmap),parseImage(imgData,options),mipmap.mipmask=1;else if(parseFlags(mipmap,options),Array.isArray(options.mipmap))for(var mipData=options.mipmap,i=0;i>=i,imgData.height>>=i,parseImage(imgData,mipData[i]),mipmap.mipmask|=1<=0&&!("faces"in options)&&(info.genMipmaps=!0)}if("mag"in options){var magFilter=options.mag;check$1.parameter(magFilter,magFilters),info.magFilter=magFilters[magFilter]}var wrapS=info.wrapS,wrapT=info.wrapT;if("wrap"in options){var wrap=options.wrap;"string"==typeof wrap?(check$1.parameter(wrap,wrapModes),wrapS=wrapT=wrapModes[wrap]):Array.isArray(wrap)&&(check$1.parameter(wrap[0],wrapModes),check$1.parameter(wrap[1],wrapModes),wrapS=wrapModes[wrap[0]],wrapT=wrapModes[wrap[1]])}else{if("wrapS"in options){var optWrapS=options.wrapS;check$1.parameter(optWrapS,wrapModes),wrapS=wrapModes[optWrapS]}if("wrapT"in options){var optWrapT=options.wrapT;check$1.parameter(optWrapT,wrapModes),wrapT=wrapModes[optWrapT]}}if(info.wrapS=wrapS,info.wrapT=wrapT,"anisotropic"in options){var anisotropic=options.anisotropic;check$1("number"==typeof anisotropic&&anisotropic>=1&&anisotropic<=limits.maxAnisotropic,"aniso samples must be between 1 and "),info.anisotropic=options.anisotropic}if("mipmap"in options){var hasMipMap=!1;switch(typeof options.mipmap){case"string":check$1.parameter(options.mipmap,mipmapHint,"invalid mipmap hint"),info.mipmapHint=mipmapHint[options.mipmap],info.genMipmaps=!0,hasMipMap=!0;break;case"boolean":hasMipMap=info.genMipmaps=options.mipmap;break;case"object":check$1(Array.isArray(options.mipmap),"invalid mipmap type"),info.genMipmaps=!1,hasMipMap=!0;break;default:check$1.raise("invalid mipmap type")}hasMipMap&&!("min"in options)&&(info.minFilter=GL_NEAREST_MIPMAP_NEAREST$1)}}function setTexInfo(info,target){gl.texParameteri(target,GL_TEXTURE_MIN_FILTER,info.minFilter),gl.texParameteri(target,GL_TEXTURE_MAG_FILTER,info.magFilter),gl.texParameteri(target,GL_TEXTURE_WRAP_S,info.wrapS),gl.texParameteri(target,GL_TEXTURE_WRAP_T,info.wrapT),extensions.ext_texture_filter_anisotropic&&gl.texParameteri(target,GL_TEXTURE_MAX_ANISOTROPY_EXT,info.anisotropic),info.genMipmaps&&(gl.hint(GL_GENERATE_MIPMAP_HINT,info.mipmapHint),gl.generateMipmap(target))}var textureCount=0,textureSet={},numTexUnits=limits.maxTextureUnits,textureUnits=Array(numTexUnits).map((function(){return null}));function REGLTexture(target){TexFlags.call(this),this.mipmask=0,this.internalformat=GL_RGBA$1,this.id=textureCount++,this.refCount=1,this.target=target,this.texture=gl.createTexture(),this.unit=-1,this.bindCount=0,this.texInfo=new TexInfo,config.profile&&(this.stats={size:0})}function tempBind(texture){gl.activeTexture(GL_TEXTURE0$1),gl.bindTexture(texture.target,texture.texture)}function tempRestore(){var prev=textureUnits[0];prev?gl.bindTexture(prev.target,prev.texture):gl.bindTexture(GL_TEXTURE_2D$1,null)}function destroy(texture){var handle=texture.texture;check$1(handle,"must not double destroy texture");var unit=texture.unit,target=texture.target;unit>=0&&(gl.activeTexture(GL_TEXTURE0$1+unit),gl.bindTexture(target,null),textureUnits[unit]=null),gl.deleteTexture(handle),texture.texture=null,texture.params=null,texture.pixels=null,texture.refCount=0,delete textureSet[texture.id],stats.textureCount--}function createTexture2D(a,b){var texture=new REGLTexture(GL_TEXTURE_2D$1);function reglTexture2D(a,b){var texInfo=texture.texInfo;TexInfo.call(texInfo);var mipData=allocMipMap();return"number"==typeof a?parseMipMapFromShape(mipData,0|a,"number"==typeof b?0|b:0|a):a?(check$1.type(a,"object","invalid arguments to regl.texture"),parseTexInfo(texInfo,a),parseMipMapFromObject(mipData,a)):parseMipMapFromShape(mipData,1,1),texInfo.genMipmaps&&(mipData.mipmask=(mipData.width<<1)-1),texture.mipmask=mipData.mipmask,copyFlags(texture,mipData),check$1.texture2D(texInfo,mipData,limits),texture.internalformat=mipData.internalformat,reglTexture2D.width=mipData.width,reglTexture2D.height=mipData.height,tempBind(texture),setMipMap(mipData,GL_TEXTURE_2D$1),setTexInfo(texInfo,GL_TEXTURE_2D$1),tempRestore(),freeMipMap(mipData),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,mipData.width,mipData.height,texInfo.genMipmaps,!1)),reglTexture2D.format=textureFormatsInvert[texture.internalformat],reglTexture2D.type=textureTypesInvert[texture.type],reglTexture2D.mag=magFiltersInvert[texInfo.magFilter],reglTexture2D.min=minFiltersInvert[texInfo.minFilter],reglTexture2D.wrapS=wrapModesInvert[texInfo.wrapS],reglTexture2D.wrapT=wrapModesInvert[texInfo.wrapT],reglTexture2D}function subimage(image,x_,y_,level_){check$1(!!image,"must specify image data");var x=0|x_,y=0|y_,level=0|level_,imageData=allocImage();return copyFlags(imageData,texture),imageData.width=0,imageData.height=0,parseImage(imageData,image),imageData.width=imageData.width||(texture.width>>level)-x,imageData.height=imageData.height||(texture.height>>level)-y,check$1(texture.type===imageData.type&&texture.format===imageData.format&&texture.internalformat===imageData.internalformat,"incompatible format for texture.subimage"),check$1(x>=0&&y>=0&&x+imageData.width<=texture.width&&y+imageData.height<=texture.height,"texture.subimage write out of bounds"),check$1(texture.mipmask&1<>i;++i){var _w=w>>i,_h=h>>i;if(!_w||!_h)break;gl.texImage2D(GL_TEXTURE_2D$1,i,texture.format,_w,_h,0,texture.format,texture.type,null)}return tempRestore(),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,w,h,!1,!1)),reglTexture2D}return textureSet[texture.id]=texture,stats.textureCount++,reglTexture2D(a,b),reglTexture2D.subimage=subimage,reglTexture2D.resize=resize,reglTexture2D._reglType="texture2d",reglTexture2D._texture=texture,config.profile&&(reglTexture2D.stats=texture.stats),reglTexture2D.destroy=function(){texture.decRef()},reglTexture2D}function createTextureCube(a0,a1,a2,a3,a4,a5){var texture=new REGLTexture(GL_TEXTURE_CUBE_MAP$1);textureSet[texture.id]=texture,stats.cubeCount++;var faces=new Array(6);function reglTextureCube(a0,a1,a2,a3,a4,a5){var i,texInfo=texture.texInfo;for(TexInfo.call(texInfo),i=0;i<6;++i)faces[i]=allocMipMap();if("number"!=typeof a0&&a0)if("object"==typeof a0)if(a1)parseMipMapFromObject(faces[0],a0),parseMipMapFromObject(faces[1],a1),parseMipMapFromObject(faces[2],a2),parseMipMapFromObject(faces[3],a3),parseMipMapFromObject(faces[4],a4),parseMipMapFromObject(faces[5],a5);else if(parseTexInfo(texInfo,a0),parseFlags(texture,a0),"faces"in a0){var faceInput=a0.faces;for(check$1(Array.isArray(faceInput)&&6===faceInput.length,"cube faces must be a length 6 array"),i=0;i<6;++i)check$1("object"==typeof faceInput[i]&&!!faceInput[i],"invalid input for cube map face"),copyFlags(faces[i],texture),parseMipMapFromObject(faces[i],faceInput[i])}else for(i=0;i<6;++i)parseMipMapFromObject(faces[i],a0);else check$1.raise("invalid arguments to cube map");else{var s=0|a0||1;for(i=0;i<6;++i)parseMipMapFromShape(faces[i],s,s)}for(copyFlags(texture,faces[0]),check$1.optional((function(){limits.npotTextureCube||check$1(isPow2$1(texture.width)&&isPow2$1(texture.height),"your browser does not support non power or two texture dimensions")})),texInfo.genMipmaps?texture.mipmask=(faces[0].width<<1)-1:texture.mipmask=faces[0].mipmask,check$1.textureCube(texture,texInfo,faces,limits),texture.internalformat=faces[0].internalformat,reglTextureCube.width=faces[0].width,reglTextureCube.height=faces[0].height,tempBind(texture),i=0;i<6;++i)setMipMap(faces[i],GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+i);for(setTexInfo(texInfo,GL_TEXTURE_CUBE_MAP$1),tempRestore(),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,reglTextureCube.width,reglTextureCube.height,texInfo.genMipmaps,!0)),reglTextureCube.format=textureFormatsInvert[texture.internalformat],reglTextureCube.type=textureTypesInvert[texture.type],reglTextureCube.mag=magFiltersInvert[texInfo.magFilter],reglTextureCube.min=minFiltersInvert[texInfo.minFilter],reglTextureCube.wrapS=wrapModesInvert[texInfo.wrapS],reglTextureCube.wrapT=wrapModesInvert[texInfo.wrapT],i=0;i<6;++i)freeMipMap(faces[i]);return reglTextureCube}function subimage(face,image,x_,y_,level_){check$1(!!image,"must specify image data"),check$1("number"==typeof face&&face===(0|face)&&face>=0&&face<6,"invalid face");var x=0|x_,y=0|y_,level=0|level_,imageData=allocImage();return copyFlags(imageData,texture),imageData.width=0,imageData.height=0,parseImage(imageData,image),imageData.width=imageData.width||(texture.width>>level)-x,imageData.height=imageData.height||(texture.height>>level)-y,check$1(texture.type===imageData.type&&texture.format===imageData.format&&texture.internalformat===imageData.internalformat,"incompatible format for texture.subimage"),check$1(x>=0&&y>=0&&x+imageData.width<=texture.width&&y+imageData.height<=texture.height,"texture.subimage write out of bounds"),check$1(texture.mipmask&1<>j;++j)gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+i,j,texture.format,radius>>j,radius>>j,0,texture.format,texture.type,null);return tempRestore(),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,reglTextureCube.width,reglTextureCube.height,!1,!0)),reglTextureCube}}return reglTextureCube(a0,a1,a2,a3,a4,a5),reglTextureCube.subimage=subimage,reglTextureCube.resize=resize,reglTextureCube._reglType="textureCube",reglTextureCube._texture=texture,config.profile&&(reglTextureCube.stats=texture.stats),reglTextureCube.destroy=function(){texture.decRef()},reglTextureCube}function destroyTextures(){for(var i=0;i>i,texture.height>>i,0,texture.internalformat,texture.type,null);else for(var j=0;j<6;++j)gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+j,i,texture.internalformat,texture.width>>i,texture.height>>i,0,texture.internalformat,texture.type,null);setTexInfo(texture.texInfo,texture.target)}))}function refreshTextures(){for(var i=0;i0)continue;other.unit=-1}textureUnits[i]=texture,unit=i;break}unit>=numTexUnits&&check$1.raise("insufficient number of texture units"),config.profile&&stats.maxTextureUnits=2,"invalid renderbuffer shape"),w=0|shape[0],h=0|shape[1]}else"radius"in options&&(w=h=0|options.radius),"width"in options&&(w=0|options.width),"height"in options&&(h=0|options.height);"format"in options&&(check$1.parameter(options.format,formatTypes,"invalid renderbuffer format"),format=formatTypes[options.format])}else"number"==typeof a?(w=0|a,h="number"==typeof b?0|b:w):a?check$1.raise("invalid arguments to renderbuffer constructor"):w=h=1;if(check$1(w>0&&h>0&&w<=limits.maxRenderbufferSize&&h<=limits.maxRenderbufferSize,"invalid renderbuffer size"),w!==renderbuffer.width||h!==renderbuffer.height||format!==renderbuffer.format)return reglRenderbuffer.width=renderbuffer.width=w,reglRenderbuffer.height=renderbuffer.height=h,renderbuffer.format=format,gl.bindRenderbuffer(GL_RENDERBUFFER,renderbuffer.renderbuffer),gl.renderbufferStorage(GL_RENDERBUFFER,format,w,h),check$1(0===gl.getError(),"invalid render buffer format"),config.profile&&(renderbuffer.stats.size=getRenderbufferSize(renderbuffer.format,renderbuffer.width,renderbuffer.height)),reglRenderbuffer.format=formatTypesInvert[renderbuffer.format],reglRenderbuffer}function resize(w_,h_){var w=0|w_,h=0|h_||w;return w===renderbuffer.width&&h===renderbuffer.height||(check$1(w>0&&h>0&&w<=limits.maxRenderbufferSize&&h<=limits.maxRenderbufferSize,"invalid renderbuffer size"),reglRenderbuffer.width=renderbuffer.width=w,reglRenderbuffer.height=renderbuffer.height=h,gl.bindRenderbuffer(GL_RENDERBUFFER,renderbuffer.renderbuffer),gl.renderbufferStorage(GL_RENDERBUFFER,renderbuffer.format,w,h),check$1(0===gl.getError(),"invalid render buffer format"),config.profile&&(renderbuffer.stats.size=getRenderbufferSize(renderbuffer.format,renderbuffer.width,renderbuffer.height))),reglRenderbuffer}return renderbufferSet[renderbuffer.id]=renderbuffer,stats.renderbufferCount++,reglRenderbuffer(a,b),reglRenderbuffer.resize=resize,reglRenderbuffer._reglType="renderbuffer",reglRenderbuffer._renderbuffer=renderbuffer,config.profile&&(reglRenderbuffer.stats=renderbuffer.stats),reglRenderbuffer.destroy=function(){renderbuffer.decRef()},reglRenderbuffer}function restoreRenderbuffers(){values(renderbufferSet).forEach((function(rb){rb.renderbuffer=gl.createRenderbuffer(),gl.bindRenderbuffer(GL_RENDERBUFFER,rb.renderbuffer),gl.renderbufferStorage(GL_RENDERBUFFER,rb.format,rb.width,rb.height)})),gl.bindRenderbuffer(GL_RENDERBUFFER,null)}return REGLRenderbuffer.prototype.decRef=function(){--this.refCount<=0&&destroy(this)},config.profile&&(stats.getTotalRenderbufferSize=function(){var total=0;return Object.keys(renderbufferSet).forEach((function(key){total+=renderbufferSet[key].stats.size})),total}),{create:createRenderbuffer,clear:function(){values(renderbufferSet).forEach(destroy)},restore:restoreRenderbuffers}},GL_FRAMEBUFFER$1=36160,GL_RENDERBUFFER$1=36161,GL_TEXTURE_2D$2=3553,GL_TEXTURE_CUBE_MAP_POSITIVE_X$2=34069,GL_COLOR_ATTACHMENT0$1=36064,GL_DEPTH_ATTACHMENT=36096,GL_STENCIL_ATTACHMENT=36128,GL_DEPTH_STENCIL_ATTACHMENT=33306,GL_FRAMEBUFFER_COMPLETE$1=36053,GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT=36054,GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT=36055,GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS=36057,GL_FRAMEBUFFER_UNSUPPORTED=36061,GL_HALF_FLOAT_OES$2=36193,GL_UNSIGNED_BYTE$6=5121,GL_FLOAT$5=5126,GL_RGB$1=6407,GL_RGBA$2=6408,GL_DEPTH_COMPONENT$1=6402,colorTextureFormatEnums=[GL_RGB$1,GL_RGBA$2],textureFormatChannels=[];textureFormatChannels[GL_RGBA$2]=4,textureFormatChannels[GL_RGB$1]=3;var textureTypeSizes=[];textureTypeSizes[GL_UNSIGNED_BYTE$6]=1,textureTypeSizes[GL_FLOAT$5]=4,textureTypeSizes[GL_HALF_FLOAT_OES$2]=2;var GL_DEPTH_COMPONENT16$1=33189,GL_STENCIL_INDEX8$1=36168,GL_DEPTH_STENCIL$2=34041,colorRenderbufferFormatEnums=[32854,32855,36194,35907,34842,34843,34836],statusCode={};function wrapFBOState(gl,extensions,limits,textureState,renderbufferState,stats){var framebufferState={cur:null,next:null,dirty:!1,setFBO:null},colorTextureFormats=["rgba"],colorRenderbufferFormats=["rgba4","rgb565","rgb5 a1"];extensions.ext_srgb&&colorRenderbufferFormats.push("srgba"),extensions.ext_color_buffer_half_float&&colorRenderbufferFormats.push("rgba16f","rgb16f"),extensions.webgl_color_buffer_float&&colorRenderbufferFormats.push("rgba32f");var colorTypes=["uint8"];function FramebufferAttachment(target,texture,renderbuffer){this.target=target,this.texture=texture,this.renderbuffer=renderbuffer;var w=0,h=0;texture?(w=texture.width,h=texture.height):renderbuffer&&(w=renderbuffer.width,h=renderbuffer.height),this.width=w,this.height=h}function decRef(attachment){attachment&&(attachment.texture&&attachment.texture._texture.decRef(),attachment.renderbuffer&&attachment.renderbuffer._renderbuffer.decRef())}function incRefAndCheckShape(attachment,width,height){if(attachment)if(attachment.texture){var texture=attachment.texture._texture,tw=Math.max(1,texture.width),th=Math.max(1,texture.height);check$1(tw===width&&th===height,"inconsistent width/height for supplied texture"),texture.refCount+=1}else{var renderbuffer=attachment.renderbuffer._renderbuffer;check$1(renderbuffer.width===width&&renderbuffer.height===height,"inconsistent width/height for renderbuffer"),renderbuffer.refCount+=1}}function attach(location,attachment){attachment&&(attachment.texture?gl.framebufferTexture2D(GL_FRAMEBUFFER$1,location,attachment.target,attachment.texture._texture.texture,0):gl.framebufferRenderbuffer(GL_FRAMEBUFFER$1,location,GL_RENDERBUFFER$1,attachment.renderbuffer._renderbuffer.renderbuffer))}function parseAttachment(attachment){var target=GL_TEXTURE_2D$2,texture=null,renderbuffer=null,data=attachment;"object"==typeof attachment&&(data=attachment.data,"target"in attachment&&(target=0|attachment.target)),check$1.type(data,"function","invalid attachment data");var type=data._reglType;return"texture2d"===type?(texture=data,check$1(target===GL_TEXTURE_2D$2)):"textureCube"===type?(texture=data,check$1(target>=GL_TEXTURE_CUBE_MAP_POSITIVE_X$2&&target=2,"invalid shape for framebuffer"),width=shape[0],height=shape[1]}else"radius"in options&&(width=height=options.radius),"width"in options&&(width=options.width),"height"in options&&(height=options.height);("color"in options||"colors"in options)&&(colorBuffer=options.color||options.colors,Array.isArray(colorBuffer)&&check$1(1===colorBuffer.length||extensions.webgl_draw_buffers,"multiple render targets not supported")),colorBuffer||("colorCount"in options&&(colorCount=0|options.colorCount,check$1(colorCount>0,"invalid color buffer count")),"colorTexture"in options&&(colorTexture=!!options.colorTexture,colorFormat="rgba4"),"colorType"in options&&(colorType=options.colorType,colorTexture?(check$1(extensions.oes_texture_float||!("float"===colorType||"float32"===colorType),"you must enable OES_texture_float in order to use floating point framebuffer objects"),check$1(extensions.oes_texture_half_float||!("half float"===colorType||"float16"===colorType),"you must enable OES_texture_half_float in order to use 16-bit floating point framebuffer objects")):"half float"===colorType||"float16"===colorType?(check$1(extensions.ext_color_buffer_half_float,"you must enable EXT_color_buffer_half_float to use 16-bit render buffers"),colorFormat="rgba16f"):"float"!==colorType&&"float32"!==colorType||(check$1(extensions.webgl_color_buffer_float,"you must enable WEBGL_color_buffer_float in order to use 32-bit floating point renderbuffers"),colorFormat="rgba32f"),check$1.oneOf(colorType,colorTypes,"invalid color type")),"colorFormat"in options&&(colorFormat=options.colorFormat,colorTextureFormats.indexOf(colorFormat)>=0?colorTexture=!0:colorRenderbufferFormats.indexOf(colorFormat)>=0?colorTexture=!1:check$1.optional((function(){colorTexture?check$1.oneOf(options.colorFormat,colorTextureFormats,"invalid color format for texture"):check$1.oneOf(options.colorFormat,colorRenderbufferFormats,"invalid color format for renderbuffer")})))),("depthTexture"in options||"depthStencilTexture"in options)&&(depthStencilTexture=!(!options.depthTexture&&!options.depthStencilTexture),check$1(!depthStencilTexture||extensions.webgl_depth_texture,"webgl_depth_texture extension not supported")),"depth"in options&&("boolean"==typeof options.depth?needsDepth=options.depth:(depthBuffer=options.depth,needsStencil=!1)),"stencil"in options&&("boolean"==typeof options.stencil?needsStencil=options.stencil:(stencilBuffer=options.stencil,needsDepth=!1)),"depthStencil"in options&&("boolean"==typeof options.depthStencil?needsDepth=needsStencil=options.depthStencil:(depthStencilBuffer=options.depthStencil,needsDepth=!1,needsStencil=!1))}else width=height=1;var colorAttachments=null,depthAttachment=null,stencilAttachment=null,depthStencilAttachment=null;if(Array.isArray(colorBuffer))colorAttachments=colorBuffer.map(parseAttachment);else if(colorBuffer)colorAttachments=[parseAttachment(colorBuffer)];else for(colorAttachments=new Array(colorCount),i=0;i=0||colorAttachments[i].renderbuffer&&colorRenderbufferFormatEnums.indexOf(colorAttachments[i].renderbuffer._renderbuffer.format)>=0,"framebuffer color attachment "+i+" is invalid"),colorAttachments[i]&&colorAttachments[i].texture){var colorAttachmentSize=textureFormatChannels[colorAttachments[i].texture._texture.format]*textureTypeSizes[colorAttachments[i].texture._texture.type];null===commonColorAttachmentSize?commonColorAttachmentSize=colorAttachmentSize:check$1(commonColorAttachmentSize===colorAttachmentSize,"all color attachments much have the same number of bits per pixel.")}return incRefAndCheckShape(depthAttachment,width,height),check$1(!depthAttachment||depthAttachment.texture&&depthAttachment.texture._texture.format===GL_DEPTH_COMPONENT$1||depthAttachment.renderbuffer&&depthAttachment.renderbuffer._renderbuffer.format===GL_DEPTH_COMPONENT16$1,"invalid depth attachment for framebuffer object"),incRefAndCheckShape(stencilAttachment,width,height),check$1(!stencilAttachment||stencilAttachment.renderbuffer&&stencilAttachment.renderbuffer._renderbuffer.format===GL_STENCIL_INDEX8$1,"invalid stencil attachment for framebuffer object"),incRefAndCheckShape(depthStencilAttachment,width,height),check$1(!depthStencilAttachment||depthStencilAttachment.texture&&depthStencilAttachment.texture._texture.format===GL_DEPTH_STENCIL$2||depthStencilAttachment.renderbuffer&&depthStencilAttachment.renderbuffer._renderbuffer.format===GL_DEPTH_STENCIL$2,"invalid depth-stencil attachment for framebuffer object"),decFBORefs(framebuffer),framebuffer.width=width,framebuffer.height=height,framebuffer.colorAttachments=colorAttachments,framebuffer.depthAttachment=depthAttachment,framebuffer.stencilAttachment=stencilAttachment,framebuffer.depthStencilAttachment=depthStencilAttachment,reglFramebuffer.color=colorAttachments.map(unwrapAttachment),reglFramebuffer.depth=unwrapAttachment(depthAttachment),reglFramebuffer.stencil=unwrapAttachment(stencilAttachment),reglFramebuffer.depthStencil=unwrapAttachment(depthStencilAttachment),reglFramebuffer.width=framebuffer.width,reglFramebuffer.height=framebuffer.height,updateFramebuffer(framebuffer),reglFramebuffer}function resize(w_,h_){check$1(framebufferState.next!==framebuffer,"can not resize a framebuffer which is currently in use");var w=Math.max(0|w_,1),h=Math.max(0|h_||w,1);if(w===framebuffer.width&&h===framebuffer.height)return reglFramebuffer;for(var colorAttachments=framebuffer.colorAttachments,i=0;i=2,"invalid shape for framebuffer"),check$1(shape[0]===shape[1],"cube framebuffer must be square"),radius=shape[0]}else"radius"in options&&(radius=0|options.radius),"width"in options?(radius=0|options.width,"height"in options&&check$1(options.height===radius,"must be square")):"height"in options&&(radius=0|options.height);("color"in options||"colors"in options)&&(colorBuffer=options.color||options.colors,Array.isArray(colorBuffer)&&check$1(1===colorBuffer.length||extensions.webgl_draw_buffers,"multiple render targets not supported")),colorBuffer||("colorCount"in options&&(colorCount=0|options.colorCount,check$1(colorCount>0,"invalid color buffer count")),"colorType"in options&&(check$1.oneOf(options.colorType,colorTypes,"invalid color type"),colorType=options.colorType),"colorFormat"in options&&(colorFormat=options.colorFormat,check$1.oneOf(options.colorFormat,colorTextureFormats,"invalid color format for texture"))),"depth"in options&&(params.depth=options.depth),"stencil"in options&&(params.stencil=options.stencil),"depthStencil"in options&&(params.depthStencil=options.depthStencil)}else radius=1;if(colorBuffer)if(Array.isArray(colorBuffer))for(colorCubes=[],i=0;i0&&(params.depth=faces[0].depth,params.stencil=faces[0].stencil,params.depthStencil=faces[0].depthStencil),faces[i]?faces[i](params):faces[i]=createFBO(params)}return extend(reglFramebufferCube,{width:radius,height:radius,color:colorCubes})}function resize(radius_){var i,radius=0|radius_;if(check$1(radius>0&&radius<=limits.maxCubeMapSize,"invalid radius for cube fbo"),radius===reglFramebufferCube.width)return reglFramebufferCube;var colors=reglFramebufferCube.color;for(i=0;i{for(var keys=Object.keys(options),i=0;i=0,'invalid option for vao: "'+keys[i]+'" valid options are '+VAO_OPTIONS)})),check$1(Array.isArray(attributes),"attributes must be an array")}check$1(attributes.length0,"must specify at least one attribute");var bufUpdated={},nattributes=vao.attributes;nattributes.length=attributes.length;for(var i=0;i=data.byteLength?buf.subdata(data):(buf.destroy(),vao.buffers[i]=null)),vao.buffers[i]||(buf=vao.buffers[i]=bufferState.create(spec,GL_ARRAY_BUFFER$1,!1,!0)),rec.buffer=bufferState.getBuffer(buf),rec.size=0|rec.buffer.dimension,rec.normalized=!1,rec.type=rec.buffer.dtype,rec.offset=0,rec.stride=0,rec.divisor=0,rec.state=1,bufUpdated[i]=1):bufferState.getBuffer(spec)?(rec.buffer=bufferState.getBuffer(spec),rec.size=0|rec.buffer.dimension,rec.normalized=!1,rec.type=rec.buffer.dtype,rec.offset=0,rec.stride=0,rec.divisor=0,rec.state=1):bufferState.getBuffer(spec.buffer)?(rec.buffer=bufferState.getBuffer(spec.buffer),rec.size=0|(+spec.size||rec.buffer.dimension),rec.normalized=!!spec.normalized||!1,"type"in spec?(check$1.parameter(spec.type,glTypes,"invalid buffer type"),rec.type=glTypes[spec.type]):rec.type=rec.buffer.dtype,rec.offset=0|(spec.offset||0),rec.stride=0|(spec.stride||0),rec.divisor=0|(spec.divisor||0),rec.state=1,check$1(rec.size>=1&&rec.size<=4,"size must be between 1 and 4"),check$1(rec.offset>=0,"invalid offset"),check$1(rec.stride>=0&&rec.stride<=255,"stride must be between 0 and 255"),check$1(rec.divisor>=0,"divisor must be positive"),check$1(!rec.divisor||!!extensions.angle_instanced_arrays,"ANGLE_instanced_arrays must be enabled to use divisor")):"x"in spec?(check$1(i>0,"first attribute must not be a constant"),rec.x=+spec.x||0,rec.y=+spec.y||0,rec.z=+spec.z||0,rec.w=+spec.w||0,rec.state=2):check$1(!1,"invalid attribute spec for location "+i)}for(var j=0;j1)for(var j=0;j1&&(uniName=uniName.replace("[0]","")),insertActiveInfo(uniforms,new ActiveInfo(uniName,stringStore.id(uniName),gl.getUniformLocation(program,uniName),info))}var numAttributes=gl.getProgramParameter(program,GL_ACTIVE_ATTRIBUTES);config.profile&&(desc.stats.attributesCount=numAttributes);var attributes=desc.attributes;for(i=0;im&&(m=desc.stats.uniformsCount)})),m},stats.getMaxAttributesCount=function(){var m=0;return programList.forEach((function(desc){desc.stats.attributesCount>m&&(m=desc.stats.attributesCount)})),m}),{clear:function(){var deleteShader=gl.deleteShader.bind(gl);values(fragShaders).forEach(deleteShader),fragShaders={},values(vertShaders).forEach(deleteShader),vertShaders={},programList.forEach((function(desc){gl.deleteProgram(desc.program)})),programList.length=0,programCache={},stats.shaderCount=0},program:function(vertId,fragId,command,attribLocations){check$1.command(vertId>=0,"missing vertex shader",command),check$1.command(fragId>=0,"missing fragment shader",command);var cache=programCache[fragId];cache||(cache=programCache[fragId]={});var prevProgram=cache[vertId];if(prevProgram&&(prevProgram.refCount++,!attribLocations))return prevProgram;var program=new REGLProgram(fragId,vertId);return stats.shaderCount++,linkProgram(program,command,attribLocations),prevProgram||(cache[vertId]=program),programList.push(program),extend(program,{destroy:function(){if(program.refCount--,program.refCount<=0){gl.deleteProgram(program.program);var idx=programList.indexOf(program);programList.splice(idx,1),stats.shaderCount--}cache[program.vertId].refCount<=0&&(gl.deleteShader(vertShaders[program.vertId]),delete vertShaders[program.vertId],delete programCache[program.fragId][program.vertId]),Object.keys(programCache[program.fragId]).length||(gl.deleteShader(fragShaders[program.fragId]),delete fragShaders[program.fragId],delete programCache[program.fragId])}})},restore:restoreShaders,shader:getShader,frag:-1,vert:-1}}var GL_RGBA$3=6408,GL_UNSIGNED_BYTE$7=5121,GL_PACK_ALIGNMENT=3333,GL_FLOAT$7=5126;function wrapReadPixels(gl,framebufferState,reglPoll,context,glAttributes,extensions,limits){function readPixelsImpl(input){var type;null===framebufferState.next?(check$1(glAttributes.preserveDrawingBuffer,'you must create a webgl context with "preserveDrawingBuffer":true in order to read pixels from the drawing buffer'),type=GL_UNSIGNED_BYTE$7):(check$1(null!==framebufferState.next.colorAttachments[0].texture,"You cannot read from a renderbuffer"),type=framebufferState.next.colorAttachments[0].texture._texture.type,check$1.optional((function(){extensions.oes_texture_float?(check$1(type===GL_UNSIGNED_BYTE$7||type===GL_FLOAT$7,"Reading from a framebuffer is only allowed for the types 'uint8' and 'float'"),type===GL_FLOAT$7&&check$1(limits.readFloat,"Reading 'float' values is not permitted in your browser. For a fallback, please see: https://www.npmjs.com/package/glsl-read-float")):check$1(type===GL_UNSIGNED_BYTE$7,"Reading from a framebuffer is only allowed for the type 'uint8'")})));var x=0,y=0,width=context.framebufferWidth,height=context.framebufferHeight,data=null;isTypedArray(input)?data=input:input&&(check$1.type(input,"object","invalid arguments to regl.read()"),x=0|input.x,y=0|input.y,check$1(x>=0&&x=0&&y0&&width+x<=context.framebufferWidth,"invalid width for read pixels"),check$1(height>0&&height+y<=context.framebufferHeight,"invalid height for read pixels"),reglPoll();var size=width*height*4;return data||(type===GL_UNSIGNED_BYTE$7?data=new Uint8Array(size):type===GL_FLOAT$7&&(data=data||new Float32Array(size))),check$1.isTypedArray(data,"data buffer for regl.read() must be a typedarray"),check$1(data.byteLength>=size,"data buffer for regl.read() too small"),gl.pixelStorei(GL_PACK_ALIGNMENT,4),gl.readPixels(x,y,width,height,GL_RGBA$3,type,data),data}function readPixelsFBO(options){var result;return framebufferState.setFBO({framebuffer:options.framebuffer},(function(){result=readPixelsImpl(options)})),result}function readPixels(options){return options&&"framebuffer"in options?readPixelsFBO(options):readPixelsImpl(options)}return readPixels}function slice(x){return Array.prototype.slice.call(x)}function join(x){return slice(x).join("")}function createEnvironment(){var varCounter=0,linkedNames=[],linkedValues=[];function link(value){for(var i=0;i0&&(code.push(name,"="),code.push.apply(code,slice(arguments)),code.push(";")),name}return extend(push,{def:def,toString:function(){return join([vars.length>0?"var "+vars.join(",")+";":"",join(code)])}})}function scope(){var entry=block(),exit=block(),entryToString=entry.toString,exitToString=exit.toString;function save(object,prop){exit(object,prop,"=",entry.def(object,prop),";")}return extend((function(){entry.apply(entry,slice(arguments))}),{def:entry.def,entry:entry,exit:exit,save:save,set:function(object,prop,value){save(object,prop),entry(object,prop,"=",value,";")},toString:function(){return entryToString()+exitToString()}})}function conditional(){var pred=join(arguments),thenBlock=scope(),elseBlock=scope(),thenToString=thenBlock.toString,elseToString=elseBlock.toString;return extend(thenBlock,{then:function(){return thenBlock.apply(thenBlock,slice(arguments)),this},else:function(){return elseBlock.apply(elseBlock,slice(arguments)),this},toString:function(){var elseClause=elseToString();return elseClause&&(elseClause="else{"+elseClause+"}"),join(["if(",pred,"){",thenToString(),"}",elseClause])}})}var globalBlock=block(),procedures={};function proc(name,count){var args=[];function arg(){var name="a"+args.length;return args.push(name),name}count=count||0;for(var i=0;i":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},stencilOps={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},shaderType={frag:35632,vert:35633},orientationType={cw:GL_CW,ccw:GL_CCW};function isBufferArgs(x){return Array.isArray(x)||isTypedArray(x)||isNDArrayLike(x)}function sortState(state){return state.sort((function(a,b){return a===S_VIEWPORT?-1:b===S_VIEWPORT?1:a=1,numArgs>=2,append)}if(type===DYN_THUNK){var data=dyn.data;return new Declaration(data.thisDep,data.contextDep,data.propDep,append)}if(type===DYN_CONSTANT$1)return new Declaration(!1,!1,!1,append);if(type===DYN_ARRAY$1){for(var thisDep=!1,contextDep=!1,propDep=!1,i=0;i=1&&(contextDep=!0),subArgs>=2&&(propDep=!0)}else subDyn.type===DYN_THUNK&&(thisDep=thisDep||subDyn.data.thisDep,contextDep=contextDep||subDyn.data.contextDep,propDep=propDep||subDyn.data.propDep)}return new Declaration(thisDep,contextDep,propDep,append)}return new Declaration(type===DYN_STATE$1,type===DYN_CONTEXT$1,type===DYN_PROP$1,append)}var SCOPE_DECL=new Declaration(!1,!1,!1,(function(){}));function reglCore(gl,stringStore,extensions,limits,bufferState,elementState,textureState,framebufferState,uniformState,attributeState,shaderState,drawState,contextState,timer,config){var AttributeRecord=attributeState.Record,blendEquations={add:32774,subtract:32778,"reverse subtract":32779};extensions.ext_blend_minmax&&(blendEquations.min=GL_MIN_EXT,blendEquations.max=GL_MAX_EXT);var extInstancing=extensions.angle_instanced_arrays,extDrawBuffers=extensions.webgl_draw_buffers,extVertexArrays=extensions.oes_vertex_array_object,currentState={dirty:!0,profile:config.profile},nextState={},GL_STATE_NAMES=[],GL_FLAGS={},GL_VARIABLES={};function propName(name){return name.replace(".","_")}function stateFlag(sname,cap,init){var name=propName(sname);GL_STATE_NAMES.push(sname),nextState[name]=currentState[name]=!!init,GL_FLAGS[name]=cap}function stateVariable(sname,func,init){var name=propName(sname);GL_STATE_NAMES.push(sname),Array.isArray(init)?(currentState[name]=init.slice(),nextState[name]=init.slice()):currentState[name]=nextState[name]=init,GL_VARIABLES[name]=func}stateFlag(S_DITHER,GL_DITHER),stateFlag(S_BLEND_ENABLE,GL_BLEND),stateVariable(S_BLEND_COLOR,"blendColor",[0,0,0,0]),stateVariable(S_BLEND_EQUATION,"blendEquationSeparate",[GL_FUNC_ADD,GL_FUNC_ADD]),stateVariable(S_BLEND_FUNC,"blendFuncSeparate",[GL_ONE,GL_ZERO,GL_ONE,GL_ZERO]),stateFlag(S_DEPTH_ENABLE,GL_DEPTH_TEST,!0),stateVariable(S_DEPTH_FUNC,"depthFunc",GL_LESS),stateVariable(S_DEPTH_RANGE,"depthRange",[0,1]),stateVariable(S_DEPTH_MASK,"depthMask",!0),stateVariable(S_COLOR_MASK,S_COLOR_MASK,[!0,!0,!0,!0]),stateFlag(S_CULL_ENABLE,GL_CULL_FACE),stateVariable(S_CULL_FACE,"cullFace",GL_BACK),stateVariable(S_FRONT_FACE,S_FRONT_FACE,GL_CCW),stateVariable(S_LINE_WIDTH,S_LINE_WIDTH,1),stateFlag(S_POLYGON_OFFSET_ENABLE,GL_POLYGON_OFFSET_FILL),stateVariable(S_POLYGON_OFFSET_OFFSET,"polygonOffset",[0,0]),stateFlag(S_SAMPLE_ALPHA,GL_SAMPLE_ALPHA_TO_COVERAGE),stateFlag(S_SAMPLE_ENABLE,GL_SAMPLE_COVERAGE),stateVariable(S_SAMPLE_COVERAGE,"sampleCoverage",[1,!1]),stateFlag(S_STENCIL_ENABLE,GL_STENCIL_TEST),stateVariable(S_STENCIL_MASK,"stencilMask",-1),stateVariable(S_STENCIL_FUNC,"stencilFunc",[GL_ALWAYS,0,-1]),stateVariable(S_STENCIL_OPFRONT,"stencilOpSeparate",[GL_FRONT,GL_KEEP,GL_KEEP,GL_KEEP]),stateVariable(S_STENCIL_OPBACK,"stencilOpSeparate",[GL_BACK,GL_KEEP,GL_KEEP,GL_KEEP]),stateFlag(S_SCISSOR_ENABLE,GL_SCISSOR_TEST),stateVariable(S_SCISSOR_BOX,"scissor",[0,0,gl.drawingBufferWidth,gl.drawingBufferHeight]),stateVariable(S_VIEWPORT,S_VIEWPORT,[0,0,gl.drawingBufferWidth,gl.drawingBufferHeight]);var sharedState={gl:gl,context:contextState,strings:stringStore,next:nextState,current:currentState,draw:drawState,elements:elementState,buffer:bufferState,shader:shaderState,attributes:attributeState.state,vao:attributeState,uniforms:uniformState,framebuffer:framebufferState,extensions:extensions,timer:timer,isBufferArgs:isBufferArgs},sharedConstants={primTypes:primTypes,compareFuncs:compareFuncs,blendFuncs:blendFuncs,blendEquations:blendEquations,stencilOps:stencilOps,glTypes:glTypes,orientationType:orientationType};check$1.optional((function(){sharedState.isArrayLike=isArrayLike})),extDrawBuffers&&(sharedConstants.backBuffer=[GL_BACK],sharedConstants.drawBuffer=loop(limits.maxDrawbuffers,(function(i){return 0===i?[0]:loop(i,(function(j){return GL_COLOR_ATTACHMENT0$2+j}))})));var drawCallCounter=0;function createREGLEnvironment(){var env=createEnvironment(),link=env.link,global=env.global;env.id=drawCallCounter++,env.batchId="0";var SHARED=link(sharedState),shared=env.shared={props:"a0"};Object.keys(sharedState).forEach((function(prop){shared[prop]=global.def(SHARED,".",prop)})),check$1.optional((function(){env.CHECK=link(check$1),env.commandStr=check$1.guessCommand(),env.command=link(env.commandStr),env.assert=function(block,pred,message){block("if(!(",pred,"))",this.CHECK,".commandRaise(",link(message),",",this.command,");")},sharedConstants.invalidBlendCombinations=invalidBlendCombinations}));var nextVars=env.next={},currentVars=env.current={};Object.keys(GL_VARIABLES).forEach((function(variable){Array.isArray(currentState[variable])&&(nextVars[variable]=global.def(shared.next,".",variable),currentVars[variable]=global.def(shared.current,".",variable))}));var constants=env.constants={};Object.keys(sharedConstants).forEach((function(name){constants[name]=global.def(JSON.stringify(sharedConstants[name]))})),env.invoke=function(block,x){switch(x.type){case DYN_FUNC$1:var argList=["this",shared.context,shared.props,env.batchId];return block.def(link(x.data),".call(",argList.slice(0,Math.max(x.data.length+1,4)),")");case DYN_PROP$1:return block.def(shared.props,x.data);case DYN_CONTEXT$1:return block.def(shared.context,x.data);case DYN_STATE$1:return block.def("this",x.data);case DYN_THUNK:return x.data.append(env,block),x.data.ref;case DYN_CONSTANT$1:return x.data.toString();case DYN_ARRAY$1:return x.data.map((function(y){return env.invoke(block,y)}))}},env.attribCache={};var scopeAttribs={};return env.scopeAttrib=function(name){var id=stringStore.id(name);if(id in scopeAttribs)return scopeAttribs[id];var binding=attributeState.scope[id];return binding||(binding=attributeState.scope[id]=new AttributeRecord),scopeAttribs[id]=link(binding)},env}function parseProfile(options){var profileEnable,staticOptions=options.static,dynamicOptions=options.dynamic;if(S_PROFILE in staticOptions){var value=!!staticOptions[S_PROFILE];(profileEnable=createStaticDecl((function(env,scope){return value}))).enable=value}else if(S_PROFILE in dynamicOptions){var dyn=dynamicOptions[S_PROFILE];profileEnable=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))}return profileEnable}function parseFramebuffer(options,env){var staticOptions=options.static,dynamicOptions=options.dynamic;if(S_FRAMEBUFFER in staticOptions){var framebuffer=staticOptions[S_FRAMEBUFFER];return framebuffer?(framebuffer=framebufferState.getFramebuffer(framebuffer),check$1.command(framebuffer,"invalid framebuffer object"),createStaticDecl((function(env,block){var FRAMEBUFFER=env.link(framebuffer),shared=env.shared;block.set(shared.framebuffer,".next",FRAMEBUFFER);var CONTEXT=shared.context;return block.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,FRAMEBUFFER+".width"),block.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,FRAMEBUFFER+".height"),FRAMEBUFFER}))):createStaticDecl((function(env,scope){var shared=env.shared;scope.set(shared.framebuffer,".next","null");var CONTEXT=shared.context;return scope.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,CONTEXT+"."+S_DRAWINGBUFFER_WIDTH),scope.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,CONTEXT+"."+S_DRAWINGBUFFER_HEIGHT),"null"}))}if(S_FRAMEBUFFER in dynamicOptions){var dyn=dynamicOptions[S_FRAMEBUFFER];return createDynamicDecl(dyn,(function(env,scope){var FRAMEBUFFER_FUNC=env.invoke(scope,dyn),shared=env.shared,FRAMEBUFFER_STATE=shared.framebuffer,FRAMEBUFFER=scope.def(FRAMEBUFFER_STATE,".getFramebuffer(",FRAMEBUFFER_FUNC,")");check$1.optional((function(){env.assert(scope,"!"+FRAMEBUFFER_FUNC+"||"+FRAMEBUFFER,"invalid framebuffer object")})),scope.set(FRAMEBUFFER_STATE,".next",FRAMEBUFFER);var CONTEXT=shared.context;return scope.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,FRAMEBUFFER+"?"+FRAMEBUFFER+".width:"+CONTEXT+"."+S_DRAWINGBUFFER_WIDTH),scope.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,FRAMEBUFFER+"?"+FRAMEBUFFER+".height:"+CONTEXT+"."+S_DRAWINGBUFFER_HEIGHT),FRAMEBUFFER}))}return null}function parseViewportScissor(options,framebuffer,env){var staticOptions=options.static,dynamicOptions=options.dynamic;function parseBox(param){if(param in staticOptions){var box=staticOptions[param];check$1.commandType(box,"object","invalid "+param,env.commandStr);var w,h,isStatic=!0,x=0|box.x,y=0|box.y;return"width"in box?(w=0|box.width,check$1.command(w>=0,"invalid "+param,env.commandStr)):isStatic=!1,"height"in box?(h=0|box.height,check$1.command(h>=0,"invalid "+param,env.commandStr)):isStatic=!1,new Declaration(!isStatic&&framebuffer&&framebuffer.thisDep,!isStatic&&framebuffer&&framebuffer.contextDep,!isStatic&&framebuffer&&framebuffer.propDep,(function(env,scope){var CONTEXT=env.shared.context,BOX_W=w;"width"in box||(BOX_W=scope.def(CONTEXT,".",S_FRAMEBUFFER_WIDTH,"-",x));var BOX_H=h;return"height"in box||(BOX_H=scope.def(CONTEXT,".",S_FRAMEBUFFER_HEIGHT,"-",y)),[x,y,BOX_W,BOX_H]}))}if(param in dynamicOptions){var dynBox=dynamicOptions[param],result=createDynamicDecl(dynBox,(function(env,scope){var BOX=env.invoke(scope,dynBox);check$1.optional((function(){env.assert(scope,BOX+"&&typeof "+BOX+'==="object"',"invalid "+param)}));var CONTEXT=env.shared.context,BOX_X=scope.def(BOX,".x|0"),BOX_Y=scope.def(BOX,".y|0"),BOX_W=scope.def('"width" in ',BOX,"?",BOX,".width|0:","(",CONTEXT,".",S_FRAMEBUFFER_WIDTH,"-",BOX_X,")"),BOX_H=scope.def('"height" in ',BOX,"?",BOX,".height|0:","(",CONTEXT,".",S_FRAMEBUFFER_HEIGHT,"-",BOX_Y,")");return check$1.optional((function(){env.assert(scope,BOX_W+">=0&&"+BOX_H+">=0","invalid "+param)})),[BOX_X,BOX_Y,BOX_W,BOX_H]}));return framebuffer&&(result.thisDep=result.thisDep||framebuffer.thisDep,result.contextDep=result.contextDep||framebuffer.contextDep,result.propDep=result.propDep||framebuffer.propDep),result}return framebuffer?new Declaration(framebuffer.thisDep,framebuffer.contextDep,framebuffer.propDep,(function(env,scope){var CONTEXT=env.shared.context;return[0,0,scope.def(CONTEXT,".",S_FRAMEBUFFER_WIDTH),scope.def(CONTEXT,".",S_FRAMEBUFFER_HEIGHT)]})):null}var viewport=parseBox(S_VIEWPORT);if(viewport){var prevViewport=viewport;viewport=new Declaration(viewport.thisDep,viewport.contextDep,viewport.propDep,(function(env,scope){var VIEWPORT=prevViewport.append(env,scope),CONTEXT=env.shared.context;return scope.set(CONTEXT,"."+S_VIEWPORT_WIDTH,VIEWPORT[2]),scope.set(CONTEXT,"."+S_VIEWPORT_HEIGHT,VIEWPORT[3]),VIEWPORT}))}return{viewport:viewport,scissor_box:parseBox(S_SCISSOR_BOX)}}function parseAttribLocations(options,attributes){var staticOptions=options.static;if("string"==typeof staticOptions[S_FRAG]&&"string"==typeof staticOptions[S_VERT]){if(Object.keys(attributes.dynamic).length>0)return null;var staticAttributes=attributes.static,sAttributes=Object.keys(staticAttributes);if(sAttributes.length>0&&"number"==typeof staticAttributes[sAttributes[0]]){for(var bindings=[],i=0;i=0,"invalid "+param,env.commandStr),createStaticDecl((function(env,scope){return isOffset&&(env.OFFSET=value),value}))}if(param in dynamicOptions){var dynValue=dynamicOptions[param];return createDynamicDecl(dynValue,(function(env,scope){var result=env.invoke(scope,dynValue);return isOffset&&(env.OFFSET=result,check$1.optional((function(){env.assert(scope,result+">=0","invalid "+param)}))),result}))}if(isOffset){if(elementsActive)return createStaticDecl((function(env,scope){return env.OFFSET=0,0}));if(vaoActive)return new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao+".currentVAO?"+env.shared.vao+".currentVAO.offset:0")}))}else if(vaoActive)return new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao+".currentVAO?"+env.shared.vao+".currentVAO.instances:-1")}));return null}var OFFSET=parseParam(S_OFFSET,!0);function parseVertCount(){if(S_COUNT in staticOptions){var count=0|staticOptions[S_COUNT];return staticDraw.count=count,check$1.command("number"==typeof count&&count>=0,"invalid vertex count",env.commandStr),createStaticDecl((function(){return count}))}if(S_COUNT in dynamicOptions){var dynCount=dynamicOptions[S_COUNT];return createDynamicDecl(dynCount,(function(env,scope){var result=env.invoke(scope,dynCount);return check$1.optional((function(){env.assert(scope,"typeof "+result+'==="number"&&'+result+">=0&&"+result+"===("+result+"|0)","invalid vertex count")})),result}))}if(elementsActive){if(isStatic(elements)){if(elements)return OFFSET?new Declaration(OFFSET.thisDep,OFFSET.contextDep,OFFSET.propDep,(function(env,scope){var result=scope.def(env.ELEMENTS,".vertCount-",env.OFFSET);return check$1.optional((function(){env.assert(scope,result+">=0","invalid vertex offset/element buffer too small")})),result})):createStaticDecl((function(env,scope){return scope.def(env.ELEMENTS,".vertCount")}));var result=createStaticDecl((function(){return-1}));return check$1.optional((function(){result.MISSING=!0})),result}var variable=new Declaration(elements.thisDep||OFFSET.thisDep,elements.contextDep||OFFSET.contextDep,elements.propDep||OFFSET.propDep,(function(env,scope){var elements=env.ELEMENTS;return env.OFFSET?scope.def(elements,"?",elements,".vertCount-",env.OFFSET,":-1"):scope.def(elements,"?",elements,".vertCount:-1")}));return check$1.optional((function(){variable.DYNAMIC=!0})),variable}if(vaoActive){var countVariable=new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao,".currentVAO?",env.shared.vao,".currentVAO.count:-1")}));return countVariable}return null}var primitive=parsePrimitive(),count=parseVertCount(),instances=parseParam(S_INSTANCES,!1);return{elements:elements,primitive:primitive,count:count,instances:instances,offset:OFFSET,vao:vao,vaoActive:vaoActive,elementsActive:elementsActive,static:staticDraw}}function parseGLState(options,env){var staticOptions=options.static,dynamicOptions=options.dynamic,STATE={};return GL_STATE_NAMES.forEach((function(prop){var param=propName(prop);function parseParam(parseStatic,parseDynamic){if(prop in staticOptions){var value=parseStatic(staticOptions[prop]);STATE[param]=createStaticDecl((function(){return value}))}else if(prop in dynamicOptions){var dyn=dynamicOptions[prop];STATE[param]=createDynamicDecl(dyn,(function(env,scope){return parseDynamic(env,scope,env.invoke(scope,dyn))}))}}switch(prop){case S_CULL_ENABLE:case S_BLEND_ENABLE:case S_DITHER:case S_STENCIL_ENABLE:case S_DEPTH_ENABLE:case S_SCISSOR_ENABLE:case S_POLYGON_OFFSET_ENABLE:case S_SAMPLE_ALPHA:case S_SAMPLE_ENABLE:case S_DEPTH_MASK:return parseParam((function(value){return check$1.commandType(value,"boolean",prop,env.commandStr),value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,"typeof "+value+'==="boolean"',"invalid flag "+prop,env.commandStr)})),value}));case S_DEPTH_FUNC:return parseParam((function(value){return check$1.commandParameter(value,compareFuncs,"invalid "+prop,env.commandStr),compareFuncs[value]}),(function(env,scope,value){var COMPARE_FUNCS=env.constants.compareFuncs;return check$1.optional((function(){env.assert(scope,value+" in "+COMPARE_FUNCS,"invalid "+prop+", must be one of "+Object.keys(compareFuncs))})),scope.def(COMPARE_FUNCS,"[",value,"]")}));case S_DEPTH_RANGE:return parseParam((function(value){return check$1.command(isArrayLike(value)&&2===value.length&&"number"==typeof value[0]&&"number"==typeof value[1]&&value[0]<=value[1],"depth range is 2d array",env.commandStr),value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===2&&typeof "+value+'[0]==="number"&&typeof '+value+'[1]==="number"&&'+value+"[0]<="+value+"[1]","depth range must be a 2d array")})),[scope.def("+",value,"[0]"),scope.def("+",value,"[1]")]}));case S_BLEND_FUNC:return parseParam((function(value){check$1.commandType(value,"object","blend.func",env.commandStr);var srcRGB="srcRGB"in value?value.srcRGB:value.src,srcAlpha="srcAlpha"in value?value.srcAlpha:value.src,dstRGB="dstRGB"in value?value.dstRGB:value.dst,dstAlpha="dstAlpha"in value?value.dstAlpha:value.dst;return check$1.commandParameter(srcRGB,blendFuncs,param+".srcRGB",env.commandStr),check$1.commandParameter(srcAlpha,blendFuncs,param+".srcAlpha",env.commandStr),check$1.commandParameter(dstRGB,blendFuncs,param+".dstRGB",env.commandStr),check$1.commandParameter(dstAlpha,blendFuncs,param+".dstAlpha",env.commandStr),check$1.command(-1===invalidBlendCombinations.indexOf(srcRGB+", "+dstRGB),"unallowed blending combination (srcRGB, dstRGB) = ("+srcRGB+", "+dstRGB+")",env.commandStr),[blendFuncs[srcRGB],blendFuncs[dstRGB],blendFuncs[srcAlpha],blendFuncs[dstAlpha]]}),(function(env,scope,value){var BLEND_FUNCS=env.constants.blendFuncs;function read(prefix,suffix){var func=scope.def('"',prefix,suffix,'" in ',value,"?",value,".",prefix,suffix,":",value,".",prefix);return check$1.optional((function(){env.assert(scope,func+" in "+BLEND_FUNCS,"invalid "+prop+"."+prefix+suffix+", must be one of "+Object.keys(blendFuncs))})),func}check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid blend func, must be an object")}));var srcRGB=read("src","RGB"),dstRGB=read("dst","RGB");check$1.optional((function(){var INVALID_BLEND_COMBINATIONS=env.constants.invalidBlendCombinations;env.assert(scope,INVALID_BLEND_COMBINATIONS+".indexOf("+srcRGB+'+", "+'+dstRGB+") === -1 ","unallowed blending combination for (srcRGB, dstRGB)")}));var SRC_RGB=scope.def(BLEND_FUNCS,"[",srcRGB,"]"),SRC_ALPHA=scope.def(BLEND_FUNCS,"[",read("src","Alpha"),"]");return[SRC_RGB,scope.def(BLEND_FUNCS,"[",dstRGB,"]"),SRC_ALPHA,scope.def(BLEND_FUNCS,"[",read("dst","Alpha"),"]")]}));case S_BLEND_EQUATION:return parseParam((function(value){return"string"==typeof value?(check$1.commandParameter(value,blendEquations,"invalid "+prop,env.commandStr),[blendEquations[value],blendEquations[value]]):"object"==typeof value?(check$1.commandParameter(value.rgb,blendEquations,prop+".rgb",env.commandStr),check$1.commandParameter(value.alpha,blendEquations,prop+".alpha",env.commandStr),[blendEquations[value.rgb],blendEquations[value.alpha]]):void check$1.commandRaise("invalid blend.equation",env.commandStr)}),(function(env,scope,value){var BLEND_EQUATIONS=env.constants.blendEquations,RGB=scope.def(),ALPHA=scope.def(),ifte=env.cond("typeof ",value,'==="string"');return check$1.optional((function(){function checkProp(block,name,value){env.assert(block,value+" in "+BLEND_EQUATIONS,"invalid "+name+", must be one of "+Object.keys(blendEquations))}checkProp(ifte.then,prop,value),env.assert(ifte.else,value+"&&typeof "+value+'==="object"',"invalid "+prop),checkProp(ifte.else,prop+".rgb",value+".rgb"),checkProp(ifte.else,prop+".alpha",value+".alpha")})),ifte.then(RGB,"=",ALPHA,"=",BLEND_EQUATIONS,"[",value,"];"),ifte.else(RGB,"=",BLEND_EQUATIONS,"[",value,".rgb];",ALPHA,"=",BLEND_EQUATIONS,"[",value,".alpha];"),scope(ifte),[RGB,ALPHA]}));case S_BLEND_COLOR:return parseParam((function(value){return check$1.command(isArrayLike(value)&&4===value.length,"blend.color must be a 4d array",env.commandStr),loop(4,(function(i){return+value[i]}))}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===4","blend.color must be a 4d array")})),loop(4,(function(i){return scope.def("+",value,"[",i,"]")}))}));case S_STENCIL_MASK:return parseParam((function(value){return check$1.commandType(value,"number",param,env.commandStr),0|value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,"typeof "+value+'==="number"',"invalid stencil.mask")})),scope.def(value,"|0")}));case S_STENCIL_FUNC:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var cmp=value.cmp||"keep",ref=value.ref||0,mask="mask"in value?value.mask:-1;return check$1.commandParameter(cmp,compareFuncs,prop+".cmp",env.commandStr),check$1.commandType(ref,"number",prop+".ref",env.commandStr),check$1.commandType(mask,"number",prop+".mask",env.commandStr),[compareFuncs[cmp],ref,mask]}),(function(env,scope,value){var COMPARE_FUNCS=env.constants.compareFuncs;return check$1.optional((function(){function assert(){env.assert(scope,Array.prototype.join.call(arguments,""),"invalid stencil.func")}assert(value+"&&typeof ",value,'==="object"'),assert('!("cmp" in ',value,")||(",value,".cmp in ",COMPARE_FUNCS,")")})),[scope.def('"cmp" in ',value,"?",COMPARE_FUNCS,"[",value,".cmp]",":",GL_KEEP),scope.def(value,".ref|0"),scope.def('"mask" in ',value,"?",value,".mask|0:-1")]}));case S_STENCIL_OPFRONT:case S_STENCIL_OPBACK:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var fail=value.fail||"keep",zfail=value.zfail||"keep",zpass=value.zpass||"keep";return check$1.commandParameter(fail,stencilOps,prop+".fail",env.commandStr),check$1.commandParameter(zfail,stencilOps,prop+".zfail",env.commandStr),check$1.commandParameter(zpass,stencilOps,prop+".zpass",env.commandStr),[prop===S_STENCIL_OPBACK?GL_BACK:GL_FRONT,stencilOps[fail],stencilOps[zfail],stencilOps[zpass]]}),(function(env,scope,value){var STENCIL_OPS=env.constants.stencilOps;function read(name){return check$1.optional((function(){env.assert(scope,'!("'+name+'" in '+value+")||("+value+"."+name+" in "+STENCIL_OPS+")","invalid "+prop+"."+name+", must be one of "+Object.keys(stencilOps))})),scope.def('"',name,'" in ',value,"?",STENCIL_OPS,"[",value,".",name,"]:",GL_KEEP)}return check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid "+prop)})),[prop===S_STENCIL_OPBACK?GL_BACK:GL_FRONT,read("fail"),read("zfail"),read("zpass")]}));case S_POLYGON_OFFSET_OFFSET:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var factor=0|value.factor,units=0|value.units;return check$1.commandType(factor,"number",param+".factor",env.commandStr),check$1.commandType(units,"number",param+".units",env.commandStr),[factor,units]}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid "+prop)})),[scope.def(value,".factor|0"),scope.def(value,".units|0")]}));case S_CULL_FACE:return parseParam((function(value){var face=0;return"front"===value?face=GL_FRONT:"back"===value&&(face=GL_BACK),check$1.command(!!face,param,env.commandStr),face}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+'==="front"||'+value+'==="back"',"invalid cull.face")})),scope.def(value,'==="front"?',GL_FRONT,":",GL_BACK)}));case S_LINE_WIDTH:return parseParam((function(value){return check$1.command("number"==typeof value&&value>=limits.lineWidthDims[0]&&value<=limits.lineWidthDims[1],"invalid line width, must be a positive number between "+limits.lineWidthDims[0]+" and "+limits.lineWidthDims[1],env.commandStr),value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,"typeof "+value+'==="number"&&'+value+">="+limits.lineWidthDims[0]+"&&"+value+"<="+limits.lineWidthDims[1],"invalid line width")})),value}));case S_FRONT_FACE:return parseParam((function(value){return check$1.commandParameter(value,orientationType,param,env.commandStr),orientationType[value]}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+'==="cw"||'+value+'==="ccw"',"invalid frontFace, must be one of cw,ccw")})),scope.def(value+'==="cw"?'+GL_CW+":"+GL_CCW)}));case S_COLOR_MASK:return parseParam((function(value){return check$1.command(isArrayLike(value)&&4===value.length,"color.mask must be length 4 array",env.commandStr),value.map((function(v){return!!v}))}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===4","invalid color.mask")})),loop(4,(function(i){return"!!"+value+"["+i+"]"}))}));case S_SAMPLE_COVERAGE:return parseParam((function(value){check$1.command("object"==typeof value&&value,param,env.commandStr);var sampleValue="value"in value?value.value:1,sampleInvert=!!value.invert;return check$1.command("number"==typeof sampleValue&&sampleValue>=0&&sampleValue<=1,"sample.coverage.value must be a number between 0 and 1",env.commandStr),[sampleValue,sampleInvert]}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid sample.coverage")})),[scope.def('"value" in ',value,"?+",value,".value:1"),scope.def("!!",value,".invert")]}))}})),STATE}function parseUniforms(uniforms,env){var staticUniforms=uniforms.static,dynamicUniforms=uniforms.dynamic,UNIFORMS={};return Object.keys(staticUniforms).forEach((function(name){var result,value=staticUniforms[name];if("number"==typeof value||"boolean"==typeof value)result=createStaticDecl((function(){return value}));else if("function"==typeof value){var reglType=value._reglType;"texture2d"===reglType||"textureCube"===reglType?result=createStaticDecl((function(env){return env.link(value)})):"framebuffer"===reglType||"framebufferCube"===reglType?(check$1.command(value.color.length>0,'missing color attachment for framebuffer sent to uniform "'+name+'"',env.commandStr),result=createStaticDecl((function(env){return env.link(value.color[0])}))):check$1.commandRaise('invalid data for uniform "'+name+'"',env.commandStr)}else isArrayLike(value)?result=createStaticDecl((function(env){return env.global.def("[",loop(value.length,(function(i){return check$1.command("number"==typeof value[i]||"boolean"==typeof value[i],"invalid uniform "+name,env.commandStr),value[i]})),"]")})):check$1.commandRaise('invalid or missing data for uniform "'+name+'"',env.commandStr);result.value=value,UNIFORMS[name]=result})),Object.keys(dynamicUniforms).forEach((function(key){var dyn=dynamicUniforms[key];UNIFORMS[key]=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))})),UNIFORMS}function parseAttributes(attributes,env){var staticAttributes=attributes.static,dynamicAttributes=attributes.dynamic,attributeDefs={};return Object.keys(staticAttributes).forEach((function(attribute){var value=staticAttributes[attribute],id=stringStore.id(attribute),record=new AttributeRecord;if(isBufferArgs(value))record.state=ATTRIB_STATE_POINTER,record.buffer=bufferState.getBuffer(bufferState.create(value,GL_ARRAY_BUFFER$2,!1,!0)),record.type=0;else{var buffer=bufferState.getBuffer(value);if(buffer)record.state=ATTRIB_STATE_POINTER,record.buffer=buffer,record.type=0;else if(check$1.command("object"==typeof value&&value,"invalid data for attribute "+attribute,env.commandStr),"constant"in value){var constant=value.constant;record.buffer="null",record.state=ATTRIB_STATE_CONSTANT,"number"==typeof constant?record.x=constant:(check$1.command(isArrayLike(constant)&&constant.length>0&&constant.length<=4,"invalid constant for attribute "+attribute,env.commandStr),CUTE_COMPONENTS.forEach((function(c,i){i=0,'invalid offset for attribute "'+attribute+'"',env.commandStr);var stride=0|value.stride;check$1.command(stride>=0&&stride<256,'invalid stride for attribute "'+attribute+'", must be integer betweeen [0, 255]',env.commandStr);var size=0|value.size;check$1.command(!("size"in value)||size>0&&size<=4,'invalid size for attribute "'+attribute+'", must be 1,2,3,4',env.commandStr);var normalized=!!value.normalized,type=0;"type"in value&&(check$1.commandParameter(value.type,glTypes,"invalid type for attribute "+attribute,env.commandStr),type=glTypes[value.type]);var divisor=0|value.divisor;check$1.optional((function(){"divisor"in value&&(check$1.command(0===divisor||extInstancing,'cannot specify divisor for attribute "'+attribute+'", instancing not supported',env.commandStr),check$1.command(divisor>=0,'invalid divisor for attribute "'+attribute+'"',env.commandStr));var command=env.commandStr,VALID_KEYS=["buffer","offset","divisor","normalized","type","size","stride"];Object.keys(value).forEach((function(prop){check$1.command(VALID_KEYS.indexOf(prop)>=0,'unknown parameter "'+prop+'" for attribute pointer "'+attribute+'" (valid parameters are '+VALID_KEYS+")",command)}))})),record.buffer=buffer,record.state=ATTRIB_STATE_POINTER,record.size=size,record.normalized=normalized,record.type=type||buffer.dtype,record.offset=offset,record.stride=stride,record.divisor=divisor}}attributeDefs[attribute]=createStaticDecl((function(env,scope){var cache=env.attribCache;if(id in cache)return cache[id];var result={isStream:!1};return Object.keys(record).forEach((function(key){result[key]=record[key]})),record.buffer&&(result.buffer=env.link(record.buffer),result.type=result.type||result.buffer+".dtype"),cache[id]=result,result}))})),Object.keys(dynamicAttributes).forEach((function(attribute){var dyn=dynamicAttributes[attribute];function appendAttributeCode(env,block){var VALUE=env.invoke(block,dyn),shared=env.shared,constants=env.constants,IS_BUFFER_ARGS=shared.isBufferArgs,BUFFER_STATE=shared.buffer;check$1.optional((function(){env.assert(block,VALUE+"&&(typeof "+VALUE+'==="object"||typeof '+VALUE+'==="function")&&('+IS_BUFFER_ARGS+"("+VALUE+")||"+BUFFER_STATE+".getBuffer("+VALUE+")||"+BUFFER_STATE+".getBuffer("+VALUE+".buffer)||"+IS_BUFFER_ARGS+"("+VALUE+'.buffer)||("constant" in '+VALUE+"&&(typeof "+VALUE+'.constant==="number"||'+shared.isArrayLike+"("+VALUE+".constant))))",'invalid dynamic attribute "'+attribute+'"')}));var result={isStream:block.def(!1)},defaultRecord=new AttributeRecord;defaultRecord.state=ATTRIB_STATE_POINTER,Object.keys(defaultRecord).forEach((function(key){result[key]=block.def(""+defaultRecord[key])}));var BUFFER=result.buffer,TYPE=result.type;function emitReadRecord(name){block(result[name],"=",VALUE,".",name,"|0;")}return block("if(",IS_BUFFER_ARGS,"(",VALUE,")){",result.isStream,"=true;",BUFFER,"=",BUFFER_STATE,".createStream(",GL_ARRAY_BUFFER$2,",",VALUE,");",TYPE,"=",BUFFER,".dtype;","}else{",BUFFER,"=",BUFFER_STATE,".getBuffer(",VALUE,");","if(",BUFFER,"){",TYPE,"=",BUFFER,".dtype;",'}else if("constant" in ',VALUE,"){",result.state,"=",ATTRIB_STATE_CONSTANT,";","if(typeof "+VALUE+'.constant === "number"){',result[CUTE_COMPONENTS[0]],"=",VALUE,".constant;",CUTE_COMPONENTS.slice(1).map((function(n){return result[n]})).join("="),"=0;","}else{",CUTE_COMPONENTS.map((function(name,i){return result[name]+"="+VALUE+".constant.length>"+i+"?"+VALUE+".constant["+i+"]:0;"})).join(""),"}}else{","if(",IS_BUFFER_ARGS,"(",VALUE,".buffer)){",BUFFER,"=",BUFFER_STATE,".createStream(",GL_ARRAY_BUFFER$2,",",VALUE,".buffer);","}else{",BUFFER,"=",BUFFER_STATE,".getBuffer(",VALUE,".buffer);","}",TYPE,'="type" in ',VALUE,"?",constants.glTypes,"[",VALUE,".type]:",BUFFER,".dtype;",result.normalized,"=!!",VALUE,".normalized;"),emitReadRecord("size"),emitReadRecord("offset"),emitReadRecord("stride"),emitReadRecord("divisor"),block("}}"),block.exit("if(",result.isStream,"){",BUFFER_STATE,".destroyStream(",BUFFER,");","}"),result}attributeDefs[attribute]=createDynamicDecl(dyn,appendAttributeCode)})),attributeDefs}function parseContext(context){var staticContext=context.static,dynamicContext=context.dynamic,result={};return Object.keys(staticContext).forEach((function(name){var value=staticContext[name];result[name]=createStaticDecl((function(env,scope){return"number"==typeof value||"boolean"==typeof value?""+value:env.link(value)}))})),Object.keys(dynamicContext).forEach((function(name){var dyn=dynamicContext[name];result[name]=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))})),result}function parseArguments(options,attributes,uniforms,context,env){var staticOptions=options.static,dynamicOptions=options.dynamic;check$1.optional((function(){var KEY_NAMES=[S_FRAMEBUFFER,S_VERT,S_FRAG,S_ELEMENTS,S_PRIMITIVE,S_OFFSET,S_COUNT,S_INSTANCES,S_PROFILE,S_VAO].concat(GL_STATE_NAMES);function checkKeys(dict){Object.keys(dict).forEach((function(key){check$1.command(KEY_NAMES.indexOf(key)>=0,'unknown parameter "'+key+'"',env.commandStr)}))}checkKeys(staticOptions),checkKeys(dynamicOptions)}));var attribLocations=parseAttribLocations(options,attributes),framebuffer=parseFramebuffer(options),viewportAndScissor=parseViewportScissor(options,framebuffer,env),draw=parseDraw(options,env),state=parseGLState(options,env),shader=parseProgram(options,env,attribLocations);function copyBox(name){var defn=viewportAndScissor[name];defn&&(state[name]=defn)}copyBox(S_VIEWPORT),copyBox(propName(S_SCISSOR_BOX));var dirty=Object.keys(state).length>0,result={framebuffer:framebuffer,draw:draw,shader:shader,state:state,dirty:dirty,scopeVAO:null,drawVAO:null,useVAO:!1,attributes:{}};if(result.profile=parseProfile(options),result.uniforms=parseUniforms(uniforms,env),result.drawVAO=result.scopeVAO=draw.vao,!result.drawVAO&&shader.program&&!attribLocations&&extensions.angle_instanced_arrays&&draw.static.elements){var useVAO=!0,staticBindings=shader.program.attributes.map((function(attr){var binding=attributes.static[attr];return useVAO=useVAO&&!!binding,binding}));if(useVAO&&staticBindings.length>0){var vao=attributeState.getVAO(attributeState.createVAO({attributes:staticBindings,elements:draw.static.elements}));result.drawVAO=new Declaration(null,null,null,(function(env,scope){return env.link(vao)})),result.useVAO=!0}}return attribLocations?result.useVAO=!0:result.attributes=parseAttributes(attributes,env),result.context=parseContext(context),result}function emitContext(env,scope,context){var CONTEXT=env.shared.context,contextEnter=env.scope();Object.keys(context).forEach((function(name){scope.save(CONTEXT,"."+name);var value=context[name].append(env,scope);Array.isArray(value)?contextEnter(CONTEXT,".",name,"=[",value.join(),"];"):contextEnter(CONTEXT,".",name,"=",value,";")})),scope(contextEnter)}function emitPollFramebuffer(env,scope,framebuffer,skipCheck){var EXT_DRAW_BUFFERS,shared=env.shared,GL=shared.gl,FRAMEBUFFER_STATE=shared.framebuffer;extDrawBuffers&&(EXT_DRAW_BUFFERS=scope.def(shared.extensions,".webgl_draw_buffers"));var NEXT,constants=env.constants,DRAW_BUFFERS=constants.drawBuffer,BACK_BUFFER=constants.backBuffer;NEXT=framebuffer?framebuffer.append(env,scope):scope.def(FRAMEBUFFER_STATE,".next"),skipCheck||scope("if(",NEXT,"!==",FRAMEBUFFER_STATE,".cur){"),scope("if(",NEXT,"){",GL,".bindFramebuffer(",GL_FRAMEBUFFER$2,",",NEXT,".framebuffer);"),extDrawBuffers&&scope(EXT_DRAW_BUFFERS,".drawBuffersWEBGL(",DRAW_BUFFERS,"[",NEXT,".colorAttachments.length]);"),scope("}else{",GL,".bindFramebuffer(",GL_FRAMEBUFFER$2,",null);"),extDrawBuffers&&scope(EXT_DRAW_BUFFERS,".drawBuffersWEBGL(",BACK_BUFFER,");"),scope("}",FRAMEBUFFER_STATE,".cur=",NEXT,";"),skipCheck||scope("}")}function emitPollState(env,scope,args){var shared=env.shared,GL=shared.gl,CURRENT_VARS=env.current,NEXT_VARS=env.next,CURRENT_STATE=shared.current,NEXT_STATE=shared.next,block=env.cond(CURRENT_STATE,".dirty");GL_STATE_NAMES.forEach((function(prop){var NEXT,CURRENT,param=propName(prop);if(!(param in args.state))if(param in NEXT_VARS){NEXT=NEXT_VARS[param],CURRENT=CURRENT_VARS[param];var parts=loop(currentState[param].length,(function(i){return block.def(NEXT,"[",i,"]")}));block(env.cond(parts.map((function(p,i){return p+"!=="+CURRENT+"["+i+"]"})).join("||")).then(GL,".",GL_VARIABLES[param],"(",parts,");",parts.map((function(p,i){return CURRENT+"["+i+"]="+p})).join(";"),";"))}else{NEXT=block.def(NEXT_STATE,".",param);var ifte=env.cond(NEXT,"!==",CURRENT_STATE,".",param);block(ifte),param in GL_FLAGS?ifte(env.cond(NEXT).then(GL,".enable(",GL_FLAGS[param],");").else(GL,".disable(",GL_FLAGS[param],");"),CURRENT_STATE,".",param,"=",NEXT,";"):ifte(GL,".",GL_VARIABLES[param],"(",NEXT,");",CURRENT_STATE,".",param,"=",NEXT,";")}})),0===Object.keys(args.state).length&&block(CURRENT_STATE,".dirty=false;"),scope(block)}function emitSetOptions(env,scope,options,filter){var shared=env.shared,CURRENT_VARS=env.current,CURRENT_STATE=shared.current,GL=shared.gl;sortState(Object.keys(options)).forEach((function(param){var defn=options[param];if(!filter||filter(defn)){var variable=defn.append(env,scope);if(GL_FLAGS[param]){var flag=GL_FLAGS[param];isStatic(defn)?scope(GL,variable?".enable(":".disable(",flag,");"):scope(env.cond(variable).then(GL,".enable(",flag,");").else(GL,".disable(",flag,");")),scope(CURRENT_STATE,".",param,"=",variable,";")}else if(isArrayLike(variable)){var CURRENT=CURRENT_VARS[param];scope(GL,".",GL_VARIABLES[param],"(",variable,");",variable.map((function(v,i){return CURRENT+"["+i+"]="+v})).join(";"),";")}else scope(GL,".",GL_VARIABLES[param],"(",variable,");",CURRENT_STATE,".",param,"=",variable,";")}}))}function injectExtensions(env,scope){extInstancing&&(env.instancing=scope.def(env.shared.extensions,".angle_instanced_arrays"))}function emitProfile(env,scope,args,useScope,incrementCounter){var CPU_START,QUERY_COUNTER,USE_PROFILE,shared=env.shared,STATS=env.stats,CURRENT_STATE=shared.current,TIMER=shared.timer,profileArg=args.profile;function perfCounter(){return"undefined"==typeof performance?"Date.now()":"performance.now()"}function emitProfileStart(block){block(CPU_START=scope.def(),"=",perfCounter(),";"),"string"==typeof incrementCounter?block(STATS,".count+=",incrementCounter,";"):block(STATS,".count++;"),timer&&(useScope?block(QUERY_COUNTER=scope.def(),"=",TIMER,".getNumPendingQueries();"):block(TIMER,".beginQuery(",STATS,");"))}function emitProfileEnd(block){block(STATS,".cpuTime+=",perfCounter(),"-",CPU_START,";"),timer&&(useScope?block(TIMER,".pushScopeStats(",QUERY_COUNTER,",",TIMER,".getNumPendingQueries(),",STATS,");"):block(TIMER,".endQuery();"))}function scopeProfile(value){var prev=scope.def(CURRENT_STATE,".profile");scope(CURRENT_STATE,".profile=",value,";"),scope.exit(CURRENT_STATE,".profile=",prev,";")}if(profileArg){if(isStatic(profileArg))return void(profileArg.enable?(emitProfileStart(scope),emitProfileEnd(scope.exit),scopeProfile("true")):scopeProfile("false"));scopeProfile(USE_PROFILE=profileArg.append(env,scope))}else USE_PROFILE=scope.def(CURRENT_STATE,".profile");var start=env.block();emitProfileStart(start),scope("if(",USE_PROFILE,"){",start,"}");var end=env.block();emitProfileEnd(end),scope.exit("if(",USE_PROFILE,"){",end,"}")}function emitAttributes(env,scope,args,attributes,filter){var shared=env.shared;function typeLength(x){switch(x){case GL_FLOAT_VEC2:case GL_INT_VEC2:case GL_BOOL_VEC2:return 2;case GL_FLOAT_VEC3:case GL_INT_VEC3:case GL_BOOL_VEC3:return 3;case GL_FLOAT_VEC4:case GL_INT_VEC4:case GL_BOOL_VEC4:return 4;default:return 1}}function emitBindAttribute(ATTRIBUTE,size,record){var GL=shared.gl,LOCATION=scope.def(ATTRIBUTE,".location"),BINDING=scope.def(shared.attributes,"[",LOCATION,"]"),STATE=record.state,BUFFER=record.buffer,CONST_COMPONENTS=[record.x,record.y,record.z,record.w],COMMON_KEYS=["buffer","normalized","offset","stride"];function emitBuffer(){scope("if(!",BINDING,".buffer){",GL,".enableVertexAttribArray(",LOCATION,");}");var SIZE,TYPE=record.type;if(SIZE=record.size?scope.def(record.size,"||",size):size,scope("if(",BINDING,".type!==",TYPE,"||",BINDING,".size!==",SIZE,"||",COMMON_KEYS.map((function(key){return BINDING+"."+key+"!=="+record[key]})).join("||"),"){",GL,".bindBuffer(",GL_ARRAY_BUFFER$2,",",BUFFER,".buffer);",GL,".vertexAttribPointer(",[LOCATION,SIZE,TYPE,record.normalized,record.stride,record.offset],");",BINDING,".type=",TYPE,";",BINDING,".size=",SIZE,";",COMMON_KEYS.map((function(key){return BINDING+"."+key+"="+record[key]+";"})).join(""),"}"),extInstancing){var DIVISOR=record.divisor;scope("if(",BINDING,".divisor!==",DIVISOR,"){",env.instancing,".vertexAttribDivisorANGLE(",[LOCATION,DIVISOR],");",BINDING,".divisor=",DIVISOR,";}")}}function emitConstant(){scope("if(",BINDING,".buffer){",GL,".disableVertexAttribArray(",LOCATION,");",BINDING,".buffer=null;","}if(",CUTE_COMPONENTS.map((function(c,i){return BINDING+"."+c+"!=="+CONST_COMPONENTS[i]})).join("||"),"){",GL,".vertexAttrib4f(",LOCATION,",",CONST_COMPONENTS,");",CUTE_COMPONENTS.map((function(c,i){return BINDING+"."+c+"="+CONST_COMPONENTS[i]+";"})).join(""),"}")}STATE===ATTRIB_STATE_POINTER?emitBuffer():STATE===ATTRIB_STATE_CONSTANT?emitConstant():(scope("if(",STATE,"===",ATTRIB_STATE_POINTER,"){"),emitBuffer(),scope("}else{"),emitConstant(),scope("}"))}attributes.forEach((function(attribute){var record,name=attribute.name,arg=args.attributes[name];if(arg){if(!filter(arg))return;record=arg.append(env,scope)}else{if(!filter(SCOPE_DECL))return;var scopeAttrib=env.scopeAttrib(name);check$1.optional((function(){env.assert(scope,scopeAttrib+".state","missing attribute "+name)})),record={},Object.keys(new AttributeRecord).forEach((function(key){record[key]=scope.def(scopeAttrib,".",key)}))}emitBindAttribute(env.link(attribute),typeLength(attribute.info.type),record)}))}function emitUniforms(env,scope,args,uniforms,filter,isBatchInnerLoop){for(var infix,shared=env.shared,GL=shared.gl,definedArrUniforms={},i=0;i1){if(!arg)continue;var arrUniformName=name.replace("[0]","");if(definedArrUniforms[arrUniformName])continue;definedArrUniforms[arrUniformName]=1}var VALUE,LOCATION=env.link(uniform)+".location";if(arg){if(!filter(arg))continue;if(isStatic(arg)){var value=arg.value;if(check$1.command(null!=value,'missing uniform "'+name+'"',env.commandStr),type===GL_SAMPLER_2D||type===GL_SAMPLER_CUBE){check$1.command("function"==typeof value&&(type===GL_SAMPLER_2D&&("texture2d"===value._reglType||"framebuffer"===value._reglType)||type===GL_SAMPLER_CUBE&&("textureCube"===value._reglType||"framebufferCube"===value._reglType)),"invalid texture for uniform "+name,env.commandStr);var TEX_VALUE=env.link(value._texture||value.color[0]._texture);scope(GL,".uniform1i(",LOCATION,",",TEX_VALUE+".bind());"),scope.exit(TEX_VALUE,".unbind();")}else if(type===GL_FLOAT_MAT2||type===GL_FLOAT_MAT3||type===GL_FLOAT_MAT4){check$1.optional((function(){check$1.command(isArrayLike(value),"invalid matrix for uniform "+name,env.commandStr),check$1.command(type===GL_FLOAT_MAT2&&4===value.length||type===GL_FLOAT_MAT3&&9===value.length||type===GL_FLOAT_MAT4&&16===value.length,"invalid length for matrix uniform "+name,env.commandStr)}));var MAT_VALUE=env.global.def("new Float32Array(["+Array.prototype.slice.call(value)+"])"),dim=2;type===GL_FLOAT_MAT3?dim=3:type===GL_FLOAT_MAT4&&(dim=4),scope(GL,".uniformMatrix",dim,"fv(",LOCATION,",false,",MAT_VALUE,");")}else{switch(type){case GL_FLOAT$8:1===size?check$1.commandType(value,"number","uniform "+name,env.commandStr):check$1.command(isArrayLike(value)&&value.length===size,"uniform "+name,env.commandStr),infix="1f";break;case GL_FLOAT_VEC2:check$1.command(isArrayLike(value)&&value.length&&value.length%2==0&&value.length<=2*size,"uniform "+name,env.commandStr),infix="2f";break;case GL_FLOAT_VEC3:check$1.command(isArrayLike(value)&&value.length&&value.length%3==0&&value.length<=3*size,"uniform "+name,env.commandStr),infix="3f";break;case GL_FLOAT_VEC4:check$1.command(isArrayLike(value)&&value.length&&value.length%4==0&&value.length<=4*size,"uniform "+name,env.commandStr),infix="4f";break;case GL_BOOL:1===size?check$1.commandType(value,"boolean","uniform "+name,env.commandStr):check$1.command(isArrayLike(value)&&value.length===size,"uniform "+name,env.commandStr),infix="1i";break;case GL_INT$3:1===size?check$1.commandType(value,"number","uniform "+name,env.commandStr):check$1.command(isArrayLike(value)&&value.length===size,"uniform "+name,env.commandStr),infix="1i";break;case GL_BOOL_VEC2:case GL_INT_VEC2:check$1.command(isArrayLike(value)&&value.length&&value.length%2==0&&value.length<=2*size,"uniform "+name,env.commandStr),infix="2i";break;case GL_BOOL_VEC3:case GL_INT_VEC3:check$1.command(isArrayLike(value)&&value.length&&value.length%3==0&&value.length<=3*size,"uniform "+name,env.commandStr),infix="3i";break;case GL_BOOL_VEC4:case GL_INT_VEC4:check$1.command(isArrayLike(value)&&value.length&&value.length%4==0&&value.length<=4*size,"uniform "+name,env.commandStr),infix="4i"}size>1?(infix+="v",value=env.global.def("["+Array.prototype.slice.call(value)+"]")):value=isArrayLike(value)?Array.prototype.slice.call(value):value,scope(GL,".uniform",infix,"(",LOCATION,",",value,");")}continue}VALUE=arg.append(env,scope)}else{if(!filter(SCOPE_DECL))continue;VALUE=scope.def(shared.uniforms,"[",stringStore.id(name),"]")}type===GL_SAMPLER_2D?(check$1(!Array.isArray(VALUE),"must specify a scalar prop for textures"),scope("if(",VALUE,"&&",VALUE,'._reglType==="framebuffer"){',VALUE,"=",VALUE,".color[0];","}")):type===GL_SAMPLER_CUBE&&(check$1(!Array.isArray(VALUE),"must specify a scalar prop for cube maps"),scope("if(",VALUE,"&&",VALUE,'._reglType==="framebufferCube"){',VALUE,"=",VALUE,".color[0];","}")),check$1.optional((function(){function emitCheck(pred,message){env.assert(scope,pred,'bad data or missing for uniform "'+name+'". '+message)}function checkType(type,size){1===size&&check$1(!Array.isArray(VALUE),"must not specify an array type for uniform"),emitCheck("Array.isArray("+VALUE+") && typeof "+VALUE+'[0]===" '+type+'" || typeof '+VALUE+'==="'+type+'"',"invalid type, expected "+type)}function checkVector(n,type,size){Array.isArray(VALUE)?check$1(VALUE.length&&VALUE.length%n==0&&VALUE.length<=n*size,"must have length of "+(1===size?"":"n * ")+n):emitCheck(shared.isArrayLike+"("+VALUE+")&&"+VALUE+".length && "+VALUE+".length % "+n+" === 0 && "+VALUE+".length<="+n*size,"invalid vector, should have length of "+(1===size?"":"n * ")+n,env.commandStr)}function checkTexture(target){check$1(!Array.isArray(VALUE),"must not specify a value type"),emitCheck("typeof "+VALUE+'==="function"&&'+VALUE+'._reglType==="texture'+(target===GL_TEXTURE_2D$3?"2d":"Cube")+'"',"invalid texture type",env.commandStr)}switch(type){case GL_INT$3:checkType("number",size);break;case GL_INT_VEC2:checkVector(2,"number",size);break;case GL_INT_VEC3:checkVector(3,"number",size);break;case GL_INT_VEC4:checkVector(4,"number",size);break;case GL_FLOAT$8:checkType("number",size);break;case GL_FLOAT_VEC2:checkVector(2,"number",size);break;case GL_FLOAT_VEC3:checkVector(3,"number",size);break;case GL_FLOAT_VEC4:checkVector(4,"number",size);break;case GL_BOOL:checkType("boolean",size);break;case GL_BOOL_VEC2:checkVector(2,"boolean",size);break;case GL_BOOL_VEC3:checkVector(3,"boolean",size);break;case GL_BOOL_VEC4:checkVector(4,"boolean",size);break;case GL_FLOAT_MAT2:checkVector(4,"number",size);break;case GL_FLOAT_MAT3:checkVector(9,"number",size);break;case GL_FLOAT_MAT4:checkVector(16,"number",size);break;case GL_SAMPLER_2D:checkTexture(GL_TEXTURE_2D$3);break;case GL_SAMPLER_CUBE:checkTexture(GL_TEXTURE_CUBE_MAP$2)}}));var unroll=1;switch(type){case GL_SAMPLER_2D:case GL_SAMPLER_CUBE:var TEX=scope.def(VALUE,"._texture");scope(GL,".uniform1i(",LOCATION,",",TEX,".bind());"),scope.exit(TEX,".unbind();");continue;case GL_INT$3:case GL_BOOL:infix="1i";break;case GL_INT_VEC2:case GL_BOOL_VEC2:infix="2i",unroll=2;break;case GL_INT_VEC3:case GL_BOOL_VEC3:infix="3i",unroll=3;break;case GL_INT_VEC4:case GL_BOOL_VEC4:infix="4i",unroll=4;break;case GL_FLOAT$8:infix="1f";break;case GL_FLOAT_VEC2:infix="2f",unroll=2;break;case GL_FLOAT_VEC3:infix="3f",unroll=3;break;case GL_FLOAT_VEC4:infix="4f",unroll=4;break;case GL_FLOAT_MAT2:infix="Matrix2fv";break;case GL_FLOAT_MAT3:infix="Matrix3fv";break;case GL_FLOAT_MAT4:infix="Matrix4fv"}if(-1===infix.indexOf("Matrix")&&size>1&&(infix+="v",unroll=1),"M"===infix.charAt(0)){scope(GL,".uniform",infix,"(",LOCATION,",");var matSize=Math.pow(type-GL_FLOAT_MAT2+2,2),STORAGE=env.global.def("new Float32Array(",matSize,")");Array.isArray(VALUE)?scope("false,(",loop(matSize,(function(i){return STORAGE+"["+i+"]="+VALUE[i]})),",",STORAGE,")"):scope("false,(Array.isArray(",VALUE,")||",VALUE," instanceof Float32Array)?",VALUE,":(",loop(matSize,(function(i){return STORAGE+"["+i+"]="+VALUE+"["+i+"]"})),",",STORAGE,")"),scope(");")}else if(unroll>1){for(var prev=[],cur=[],j=0;j=0","missing vertex count")}))):(COUNT=scope.def(DRAW_STATE,".",S_COUNT),check$1.optional((function(){env.assert(scope,COUNT+">=0","missing vertex count")}))),COUNT}var ELEMENTS=emitElements();function emitValue(name){var defn=drawOptions[name];return defn?defn.contextDep&&args.contextDynamic||defn.propDep?defn.append(env,inner):defn.append(env,outer):outer.def(DRAW_STATE,".",name)}var INSTANCES,EXT_INSTANCING,PRIMITIVE=emitValue(S_PRIMITIVE),OFFSET=emitValue(S_OFFSET),COUNT=emitCount();if("number"==typeof COUNT){if(0===COUNT)return}else inner("if(",COUNT,"){"),inner.exit("}");extInstancing&&(INSTANCES=emitValue(S_INSTANCES),EXT_INSTANCING=env.instancing);var ELEMENT_TYPE=ELEMENTS+".type",elementsStatic=drawOptions.elements&&isStatic(drawOptions.elements)&&!drawOptions.vaoActive;function emitInstancing(){function drawElements(){inner(EXT_INSTANCING,".drawElementsInstancedANGLE(",[PRIMITIVE,COUNT,ELEMENT_TYPE,OFFSET+"<<(("+ELEMENT_TYPE+"-"+GL_UNSIGNED_BYTE$8+")>>1)",INSTANCES],");")}function drawArrays(){inner(EXT_INSTANCING,".drawArraysInstancedANGLE(",[PRIMITIVE,OFFSET,COUNT,INSTANCES],");")}ELEMENTS&&"null"!==ELEMENTS?elementsStatic?drawElements():(inner("if(",ELEMENTS,"){"),drawElements(),inner("}else{"),drawArrays(),inner("}")):drawArrays()}function emitRegular(){function drawElements(){inner(GL+".drawElements("+[PRIMITIVE,COUNT,ELEMENT_TYPE,OFFSET+"<<(("+ELEMENT_TYPE+"-"+GL_UNSIGNED_BYTE$8+")>>1)"]+");")}function drawArrays(){inner(GL+".drawArrays("+[PRIMITIVE,OFFSET,COUNT]+");")}ELEMENTS&&"null"!==ELEMENTS?elementsStatic?drawElements():(inner("if(",ELEMENTS,"){"),drawElements(),inner("}else{"),drawArrays(),inner("}")):drawArrays()}extInstancing&&("number"!=typeof INSTANCES||INSTANCES>=0)?"string"==typeof INSTANCES?(inner("if(",INSTANCES,">0){"),emitInstancing(),inner("}else if(",INSTANCES,"<0){"),emitRegular(),inner("}")):emitInstancing():emitRegular()}function createBody(emitBody,parentEnv,args,program,count){var env=createREGLEnvironment(),scope=env.proc("body",count);return check$1.optional((function(){env.commandStr=parentEnv.commandStr,env.command=env.link(parentEnv.commandStr)})),extInstancing&&(env.instancing=scope.def(env.shared.extensions,".angle_instanced_arrays")),emitBody(env,scope,args,program),env.compile().body}function emitDrawBody(env,draw,args,program){injectExtensions(env,draw),args.useVAO?args.drawVAO?draw(env.shared.vao,".setVAO(",args.drawVAO.append(env,draw),");"):draw(env.shared.vao,".setVAO(",env.shared.vao,".targetVAO);"):(draw(env.shared.vao,".setVAO(null);"),emitAttributes(env,draw,args,program.attributes,(function(){return!0}))),emitUniforms(env,draw,args,program.uniforms,(function(){return!0}),!1),emitDraw(env,draw,draw,args)}function emitDrawProc(env,args){var draw=env.proc("draw",1);injectExtensions(env,draw),emitContext(env,draw,args.context),emitPollFramebuffer(env,draw,args.framebuffer),emitPollState(env,draw,args),emitSetOptions(env,draw,args.state),emitProfile(env,draw,args,!1,!0);var program=args.shader.progVar.append(env,draw);if(draw(env.shared.gl,".useProgram(",program,".program);"),args.shader.program)emitDrawBody(env,draw,args,args.shader.program);else{draw(env.shared.vao,".setVAO(null);");var drawCache=env.global.def("{}"),PROG_ID=draw.def(program,".id"),CACHED_PROC=draw.def(drawCache,"[",PROG_ID,"]");draw(env.cond(CACHED_PROC).then(CACHED_PROC,".call(this,a0);").else(CACHED_PROC,"=",drawCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitDrawBody,env,args,program,1)})),"(",program,");",CACHED_PROC,".call(this,a0);"))}Object.keys(args.state).length>0&&draw(env.shared.current,".dirty=true;"),env.shared.vao&&draw(env.shared.vao,".setVAO(null);")}function emitBatchDynamicShaderBody(env,scope,args,program){function all(){return!0}env.batchId="a1",injectExtensions(env,scope),emitAttributes(env,scope,args,program.attributes,all),emitUniforms(env,scope,args,program.uniforms,all,!1),emitDraw(env,scope,scope,args)}function emitBatchBody(env,scope,args,program){injectExtensions(env,scope);var contextDynamic=args.contextDep,BATCH_ID=scope.def(),PROP_LIST="a0",NUM_PROPS="a1",PROPS=scope.def();env.shared.props=PROPS,env.batchId=BATCH_ID;var outer=env.scope(),inner=env.scope();function isInnerDefn(defn){return defn.contextDep&&contextDynamic||defn.propDep}function isOuterDefn(defn){return!isInnerDefn(defn)}if(scope(outer.entry,"for(",BATCH_ID,"=0;",BATCH_ID,"<",NUM_PROPS,";++",BATCH_ID,"){",PROPS,"=",PROP_LIST,"[",BATCH_ID,"];",inner,"}",outer.exit),args.needsContext&&emitContext(env,inner,args.context),args.needsFramebuffer&&emitPollFramebuffer(env,inner,args.framebuffer),emitSetOptions(env,inner,args.state,isInnerDefn),args.profile&&isInnerDefn(args.profile)&&emitProfile(env,inner,args,!1,!0),program)args.useVAO?args.drawVAO?isInnerDefn(args.drawVAO)?inner(env.shared.vao,".setVAO(",args.drawVAO.append(env,inner),");"):outer(env.shared.vao,".setVAO(",args.drawVAO.append(env,outer),");"):outer(env.shared.vao,".setVAO(",env.shared.vao,".targetVAO);"):(outer(env.shared.vao,".setVAO(null);"),emitAttributes(env,outer,args,program.attributes,isOuterDefn),emitAttributes(env,inner,args,program.attributes,isInnerDefn)),emitUniforms(env,outer,args,program.uniforms,isOuterDefn,!1),emitUniforms(env,inner,args,program.uniforms,isInnerDefn,!0),emitDraw(env,outer,inner,args);else{var progCache=env.global.def("{}"),PROGRAM=args.shader.progVar.append(env,inner),PROG_ID=inner.def(PROGRAM,".id"),CACHED_PROC=inner.def(progCache,"[",PROG_ID,"]");inner(env.shared.gl,".useProgram(",PROGRAM,".program);","if(!",CACHED_PROC,"){",CACHED_PROC,"=",progCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitBatchDynamicShaderBody,env,args,program,2)})),"(",PROGRAM,");}",CACHED_PROC,".call(this,a0[",BATCH_ID,"],",BATCH_ID,");")}}function emitBatchProc(env,args){var batch=env.proc("batch",2);env.batchId="0",injectExtensions(env,batch);var contextDynamic=!1,needsContext=!0;Object.keys(args.context).forEach((function(name){contextDynamic=contextDynamic||args.context[name].propDep})),contextDynamic||(emitContext(env,batch,args.context),needsContext=!1);var framebuffer=args.framebuffer,needsFramebuffer=!1;function isInnerDefn(defn){return defn.contextDep&&contextDynamic||defn.propDep}framebuffer?(framebuffer.propDep?contextDynamic=needsFramebuffer=!0:framebuffer.contextDep&&contextDynamic&&(needsFramebuffer=!0),needsFramebuffer||emitPollFramebuffer(env,batch,framebuffer)):emitPollFramebuffer(env,batch,null),args.state.viewport&&args.state.viewport.propDep&&(contextDynamic=!0),emitPollState(env,batch,args),emitSetOptions(env,batch,args.state,(function(defn){return!isInnerDefn(defn)})),args.profile&&isInnerDefn(args.profile)||emitProfile(env,batch,args,!1,"a1"),args.contextDep=contextDynamic,args.needsContext=needsContext,args.needsFramebuffer=needsFramebuffer;var progDefn=args.shader.progVar;if(progDefn.contextDep&&contextDynamic||progDefn.propDep)emitBatchBody(env,batch,args,null);else{var PROGRAM=progDefn.append(env,batch);if(batch(env.shared.gl,".useProgram(",PROGRAM,".program);"),args.shader.program)emitBatchBody(env,batch,args,args.shader.program);else{batch(env.shared.vao,".setVAO(null);");var batchCache=env.global.def("{}"),PROG_ID=batch.def(PROGRAM,".id"),CACHED_PROC=batch.def(batchCache,"[",PROG_ID,"]");batch(env.cond(CACHED_PROC).then(CACHED_PROC,".call(this,a0,a1);").else(CACHED_PROC,"=",batchCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitBatchBody,env,args,program,2)})),"(",PROGRAM,");",CACHED_PROC,".call(this,a0,a1);"))}}Object.keys(args.state).length>0&&batch(env.shared.current,".dirty=true;"),env.shared.vao&&batch(env.shared.vao,".setVAO(null);")}function emitScopeProc(env,args){var scope=env.proc("scope",3);env.batchId="a2";var shared=env.shared,CURRENT_STATE=shared.current;function saveShader(name){var shader=args.shader[name];shader&&scope.set(shared.shader,"."+name,shader.append(env,scope))}emitContext(env,scope,args.context),args.framebuffer&&args.framebuffer.append(env,scope),sortState(Object.keys(args.state)).forEach((function(name){var value=args.state[name].append(env,scope);isArrayLike(value)?value.forEach((function(v,i){scope.set(env.next[name],"["+i+"]",v)})):scope.set(shared.next,"."+name,value)})),emitProfile(env,scope,args,!0,!0),[S_ELEMENTS,S_OFFSET,S_COUNT,S_INSTANCES,S_PRIMITIVE].forEach((function(opt){var variable=args.draw[opt];variable&&scope.set(shared.draw,"."+opt,""+variable.append(env,scope))})),Object.keys(args.uniforms).forEach((function(opt){var value=args.uniforms[opt].append(env,scope);Array.isArray(value)&&(value="["+value.join()+"]"),scope.set(shared.uniforms,"["+stringStore.id(opt)+"]",value)})),Object.keys(args.attributes).forEach((function(name){var record=args.attributes[name].append(env,scope),scopeAttrib=env.scopeAttrib(name);Object.keys(new AttributeRecord).forEach((function(prop){scope.set(scopeAttrib,"."+prop,record[prop])}))})),args.scopeVAO&&scope.set(shared.vao,".targetVAO",args.scopeVAO.append(env,scope)),saveShader(S_VERT),saveShader(S_FRAG),Object.keys(args.state).length>0&&(scope(CURRENT_STATE,".dirty=true;"),scope.exit(CURRENT_STATE,".dirty=true;")),scope("a1(",env.shared.context,",a0,",env.batchId,");")}function isDynamicObject(object){if("object"==typeof object&&!isArrayLike(object)){for(var props=Object.keys(object),i=0;i=0;--i){var cb=rafCallbacks[i];cb&&cb(contextState,null,0)}gl.flush(),timer&&timer.update()}function startRAF(){!activeRAF&&rafCallbacks.length>0&&(activeRAF=raf.next(handleRAF))}function stopRAF(){activeRAF&&(raf.cancel(handleRAF),activeRAF=null)}function handleContextLoss(event){event.preventDefault(),contextLost=!0,stopRAF(),lossCallbacks.forEach((function(cb){cb()}))}function handleContextRestored(event){gl.getError(),contextLost=!1,extensionState.restore(),shaderState.restore(),bufferState.restore(),textureState.restore(),renderbufferState.restore(),framebufferState.restore(),attributeState.restore(),timer&&timer.restore(),core.procs.refresh(),startRAF(),restoreCallbacks.forEach((function(cb){cb()}))}function destroy(){rafCallbacks.length=0,stopRAF(),canvas&&(canvas.removeEventListener(CONTEXT_LOST_EVENT,handleContextLoss),canvas.removeEventListener(CONTEXT_RESTORED_EVENT,handleContextRestored)),shaderState.clear(),framebufferState.clear(),renderbufferState.clear(),attributeState.clear(),textureState.clear(),elementState.clear(),bufferState.clear(),timer&&timer.clear(),destroyCallbacks.forEach((function(cb){cb()}))}function compileProcedure(options){function flattenNestedOptions(options){var result=extend({},options);function merge(name){if(name in result){var child=result[name];delete result[name],Object.keys(child).forEach((function(prop){result[name+"."+prop]=child[prop]}))}}return delete result.uniforms,delete result.attributes,delete result.context,delete result.vao,"stencil"in result&&result.stencil.op&&(result.stencil.opBack=result.stencil.opFront=result.stencil.op,delete result.stencil.op),merge("blend"),merge("depth"),merge("cull"),merge("stencil"),merge("polygonOffset"),merge("scissor"),merge("sample"),"vao"in options&&(result.vao=options.vao),result}function separateDynamic(object,useArrays){var staticItems={},dynamicItems={};return Object.keys(object).forEach((function(option){var value=object[option];if(dynamic.isDynamic(value))dynamicItems[option]=dynamic.unbox(value,option);else{if(useArrays&&Array.isArray(value))for(var i=0;i0)return batch.call(this,reserve(0|args),0|args)}else{if(!Array.isArray(args))return draw.call(this,args);if(args.length)return batch.call(this,args,args.length)}}return extend(REGLCommand,{stats:stats$$1,destroy:function(){compiled.destroy()}})}canvas&&(canvas.addEventListener(CONTEXT_LOST_EVENT,handleContextLoss,!1),canvas.addEventListener(CONTEXT_RESTORED_EVENT,handleContextRestored,!1));var setFBO=framebufferState.setFBO=compileProcedure({framebuffer:dynamic.define.call(null,DYN_PROP,"framebuffer")});function clearImpl(_,options){var clearFlags=0;core.procs.poll();var c=options.color;c&&(gl.clearColor(+c[0]||0,+c[1]||0,+c[2]||0,+c[3]||0),clearFlags|=GL_COLOR_BUFFER_BIT),"depth"in options&&(gl.clearDepth(+options.depth),clearFlags|=GL_DEPTH_BUFFER_BIT),"stencil"in options&&(gl.clearStencil(0|options.stencil),clearFlags|=GL_STENCIL_BUFFER_BIT),check$1(!!clearFlags,"called regl.clear with no buffer specified"),gl.clear(clearFlags)}function clear(options){if(check$1("object"==typeof options&&options,"regl.clear() takes an object as input"),"framebuffer"in options)if(options.framebuffer&&"framebufferCube"===options.framebuffer_reglType)for(var i=0;i<6;++i)setFBO(extend({framebuffer:options.framebuffer.faces[i]},options),clearImpl);else setFBO(options,clearImpl);else clearImpl(null,options)}function frame(cb){function cancel(){var i=find(rafCallbacks,cb);function pendingCancel(){var index=find(rafCallbacks,pendingCancel);rafCallbacks[index]=rafCallbacks[rafCallbacks.length-1],rafCallbacks.length-=1,rafCallbacks.length<=0&&stopRAF()}check$1(i>=0,"cannot cancel a frame twice"),rafCallbacks[i]=pendingCancel}return check$1.type(cb,"function","regl.frame() callback must be a function"),rafCallbacks.push(cb),startRAF(),{cancel:cancel}}function pollViewport(){var viewport=nextState.viewport,scissorBox=nextState.scissor_box;viewport[0]=viewport[1]=scissorBox[0]=scissorBox[1]=0,contextState.viewportWidth=contextState.framebufferWidth=contextState.drawingBufferWidth=viewport[2]=scissorBox[2]=gl.drawingBufferWidth,contextState.viewportHeight=contextState.framebufferHeight=contextState.drawingBufferHeight=viewport[3]=scissorBox[3]=gl.drawingBufferHeight}function poll(){contextState.tick+=1,contextState.time=now(),pollViewport(),core.procs.poll()}function refresh(){textureState.refresh(),pollViewport(),core.procs.refresh(),timer&&timer.update()}function now(){return(clock()-START_TIME)/1e3}function addListener(event,callback){var callbacks;switch(check$1.type(callback,"function","listener callback must be a function"),event){case"frame":return frame(callback);case"lost":callbacks=lossCallbacks;break;case"restore":callbacks=restoreCallbacks;break;case"destroy":callbacks=destroyCallbacks;break;default:check$1.raise("invalid event, must be one of frame,lost,restore,destroy")}return callbacks.push(callback),{cancel:function(){for(var i=0;i=0},read:readPixels,destroy:destroy,_gl:gl,_refresh:refresh,poll:function(){poll(),timer&&timer.update()},now:now,stats:stats$$1});return config.onDone(null,regl),regl}return wrapREGL}();var regl=reglExports;const prepareRender=params=>{const options=Object.assign({},{},params.glOptions,{onDone:(err,callback)=>{if(err)throw err}}),base=regl(options),drawCache2=new Map,command=props=>{props.rendering=Object.assign({},renderDefaults,props.rendering),((regl,params={})=>{const{fbo:fbo}=params,commandParams={cull:{enable:!0},context:{lightDirection:[.2,.2,1]},uniforms:{view:(context,props)=>props.camera.view,eye:(context,props)=>props.camera.position,projection:(context,props)=>props.camera.projection,camNear:(context,props)=>props.camera.near,camFar:(context,props)=>props.camera.far,invertedView:(context,props)=>glMat4.invert([],props.camera.view),lightPosition:(context,props)=>props&&props.rendering&&props.rendering.lightPosition?props.rendering.lightPosition:[100,200,100],lightDirection:(context,props)=>props&&props.rendering&&props.rendering.lightDirection?props.rendering.lightDirection:context.lightDirection||[0,0,0],lightView:context=>glMat4.lookAt([],context.lightDirection,[0,0,0],[0,0,1]),lightProjection:glMat4.ortho([],-25,-25,-20,20,-25,25),lightColor:(context,props)=>props&&props.rendering&&props.rendering.lightColor?props.rendering.lightColor:[1,.8,0],ambientLightAmount:(context,props)=>props&&props.rendering&&props.rendering.ambientLightAmount?props.rendering.ambientLightAmount:.3,diffuseLightAmount:(context,props)=>props&&props.rendering&&props.rendering.diffuseLightAmount?props&&props.rendering&&props.rendering.diffuseLightAmount:.89,specularLightAmount:(context,props)=>props&&props.rendering&&props.rendering.specularLightAmount?props.rendering.specularLightAmount:.16,uMaterialShininess:(context,props)=>props&&props.rendering&&props.rendering.materialShininess?props.rendering.materialShininess:8,materialAmbient:[.5,.8,.3],materialDiffuse:[.5,.8,.3],materialSpecular:[.5,.8,.3]},framebuffer:fbo};return regl(Object.assign({},commandParams,params.extras))})(base)(props,(context=>{base.clear({color:props.rendering.background,depth:1}),props.entities&&props.entities.sort(((a,b)=>{const aTransparent="transparent"in a.visuals&&a.visuals.transparent;return aTransparent===("transparent"in b.visuals&&b.visuals.transparent)?0:aTransparent?1:-1})).forEach((entity=>{const{visuals:visuals}=entity;if((!("show"in visuals)||visuals.show)&&visuals.drawCmd&&props.drawCommands[visuals.drawCmd]){let drawCmd;visuals.cacheId?drawCmd=drawCache2.get(visuals.cacheId):(visuals.cacheId=drawCache2.size,drawCmd=props.drawCommands[visuals.drawCmd](base,entity),drawCache2.set(visuals.cacheId,drawCmd));drawCmd({...entity,...visuals,camera:props.camera})}}))}))};return function(data){base.poll(),command(data)}};export{index$2 as cameras,index$1 as commands,index as controls,entitiesFromSolids,prepareRender}; diff --git a/packages/utils/regl-renderer/dist/jscad-regl-renderer.min.js b/packages/utils/regl-renderer/dist/jscad-regl-renderer.min.js index 5d77bf4de..fca81d9bb 100644 --- a/packages/utils/regl-renderer/dist/jscad-regl-renderer.min.js +++ b/packages/utils/regl-renderer/dist/jscad-regl-renderer.min.js @@ -1,13 +1,13 @@ /** * Renderer for JSCAD Geometries * @module @jscad/regl-renderer - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */ !function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadReglRenderer={})}(this,(function(exports){"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var create_1$1=function(){var out=new Float32Array(3);return out[0]=0,out[1]=0,out[2]=0,out};var clone_1$1=function(a){var out=new Float32Array(3);return out[0]=a[0],out[1]=a[1],out[2]=a[2],out};var fromValues_1=function(x,y,z){var out=new Float32Array(3);return out[0]=x,out[1]=y,out[2]=z,out};var normalize_1=function(out,a){var x=a[0],y=a[1],z=a[2],len=x*x+y*y+z*z;len>0&&(len=1/Math.sqrt(len),out[0]=a[0]*len,out[1]=a[1]*len,out[2]=a[2]*len);return out};var dot_1=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]};var angle_1=function(a,b){var tempA=fromValues(a[0],a[1],a[2]),tempB=fromValues(b[0],b[1],b[2]);normalize(tempA,tempA),normalize(tempB,tempB);var cosine=dot(tempA,tempB);return cosine>1?0:Math.acos(cosine)},fromValues=fromValues_1,normalize=normalize_1,dot=dot_1;var copy_1$1=function(out,a){return out[0]=a[0],out[1]=a[1],out[2]=a[2],out};var set_1=function(out,x,y,z){return out[0]=x,out[1]=y,out[2]=z,out};var equals_1=function(a,b){var a0=a[0],a1=a[1],a2=a[2],b0=b[0],b1=b[1],b2=b[2];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))},EPSILON=1e-6;var exactEquals_1=function(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]};var add_1=function(out,a,b){return out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out};var subtract_1=function(out,a,b){return out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out};var subExports={};!function(module){module.exports=subtract_1}({get exports(){return subExports},set exports(v){subExports=v}});var multiply_1$1=function(out,a,b){return out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out};var mulExports={};!function(module){module.exports=multiply_1$1}({get exports(){return mulExports},set exports(v){mulExports=v}});var divide_1=function(out,a,b){return out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out};var divExports={};!function(module){module.exports=divide_1}({get exports(){return divExports},set exports(v){divExports=v}});var min_1=function(out,a,b){return out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out};var max_1=function(out,a,b){return out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out};var floor_1=function(out,a){return out[0]=Math.floor(a[0]),out[1]=Math.floor(a[1]),out[2]=Math.floor(a[2]),out};var ceil_1=function(out,a){return out[0]=Math.ceil(a[0]),out[1]=Math.ceil(a[1]),out[2]=Math.ceil(a[2]),out};var round_1=function(out,a){return out[0]=Math.round(a[0]),out[1]=Math.round(a[1]),out[2]=Math.round(a[2]),out};var scale_1$1=function(out,a,b){return out[0]=a[0]*b,out[1]=a[1]*b,out[2]=a[2]*b,out};var scaleAndAdd_1=function(out,a,b,scale){return out[0]=a[0]+b[0]*scale,out[1]=a[1]+b[1]*scale,out[2]=a[2]+b[2]*scale,out};var distance_1=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)};var distExports={};!function(module){module.exports=distance_1}({get exports(){return distExports},set exports(v){distExports=v}});var squaredDistance_1=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z};var sqrDistExports={};!function(module){module.exports=squaredDistance_1}({get exports(){return sqrDistExports},set exports(v){sqrDistExports=v}});var length_1=function(a){var x=a[0],y=a[1],z=a[2];return Math.sqrt(x*x+y*y+z*z)};var lenExports={};!function(module){module.exports=length_1}({get exports(){return lenExports},set exports(v){lenExports=v}});var squaredLength_1=function(a){var x=a[0],y=a[1],z=a[2];return x*x+y*y+z*z};var sqrLenExports={};!function(module){module.exports=squaredLength_1}({get exports(){return sqrLenExports},set exports(v){sqrLenExports=v}});var negate_1=function(out,a){return out[0]=-a[0],out[1]=-a[1],out[2]=-a[2],out};var inverse_1=function(out,a){return out[0]=1/a[0],out[1]=1/a[1],out[2]=1/a[2],out};var cross_1=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out};var lerp_1=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out[2]=az+t*(b[2]-az),out};var random_1=function(out,scale){scale=scale||1;var r=2*Math.random()*Math.PI,z=2*Math.random()-1,zScale=Math.sqrt(1-z*z)*scale;return out[0]=Math.cos(r)*zScale,out[1]=Math.sin(r)*zScale,out[2]=z*scale,out};var transformMat4_1=function(out,a,m){var x=a[0],y=a[1],z=a[2],w=m[3]*x+m[7]*y+m[11]*z+m[15];return w=w||1,out[0]=(m[0]*x+m[4]*y+m[8]*z+m[12])/w,out[1]=(m[1]*x+m[5]*y+m[9]*z+m[13])/w,out[2]=(m[2]*x+m[6]*y+m[10]*z+m[14])/w,out};var transformMat3_1=function(out,a,m){var x=a[0],y=a[1],z=a[2];return out[0]=x*m[0]+y*m[3]+z*m[6],out[1]=x*m[1]+y*m[4]+z*m[7],out[2]=x*m[2]+y*m[5]+z*m[8],out};var transformQuat_1=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;return out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy,out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz,out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx,out};var rotateX_1$1=function(out,a,b,c){var by=b[1],bz=b[2],py=a[1]-by,pz=a[2]-bz,sc=Math.sin(c),cc=Math.cos(c);return out[0]=a[0],out[1]=by+py*cc-pz*sc,out[2]=bz+py*sc+pz*cc,out};var rotateY_1$1=function(out,a,b,c){var bx=b[0],bz=b[2],px=a[0]-bx,pz=a[2]-bz,sc=Math.sin(c),cc=Math.cos(c);return out[0]=bx+pz*sc+px*cc,out[1]=a[1],out[2]=bz+pz*cc-px*sc,out};var rotateZ_1$1=function(out,a,b,c){var bx=b[0],by=b[1],px=a[0]-bx,py=a[1]-by,sc=Math.sin(c),cc=Math.cos(c);return out[0]=bx+px*cc-py*sc,out[1]=by+px*sc+py*cc,out[2]=a[2],out};var forEach_1=function(a,stride,offset,count,fn,arg){var i,l;stride||(stride=3);offset||(offset=0);l=count?Math.min(count*stride+offset,a.length):a.length;for(i=offset;i{const{width:width,height:height}=input,aspect=width/height,viewport=[0,0,width,height],multiplier=camera.zoom,left=-width*multiplier,right=width*multiplier,bottom=-height*multiplier,top=height*multiplier;return{projection:glMat4.ortho([],left,right,bottom,top,camera.near,camera.far),aspect:aspect,viewport:viewport}};var orthographicCamera=Object.freeze({__proto__:null,cameraState:cameraState$1,cameraProps:{},setProjection:setProjection$1});const cameraState={view:glMat4.identity(new Float32Array(16)),projection:glMat4.identity(new Float32Array(16)),matrix:glMat4.identity(new Float32Array(16)),near:1,far:18e3,up:[0,0,1],eye:new Float32Array(3),position:[450,550,700],target:[0,0,0],fov:Math.PI/4,aspect:1,viewport:[0,0,0,0],projectionType:"perspective"},cameraProps={},defaults$1=Object.assign({},cameraState,cameraProps),setProjection=(output,camera,input)=>{const aspect=input.width/input.height,projection=glMat4.perspective(glMat4.identity([]),camera.fov,aspect,camera.near,camera.far),viewport=[0,0,input.width,input.height],out=output||{};return out.projection=projection,out.aspect=aspect,out.viewport=viewport,out};var perspectiveCamera=Object.freeze({__proto__:null,cameraState:cameraState,cameraProps:cameraProps,defaults:defaults$1,setProjection:setProjection,update:(output,camera)=>{camera||(camera=output);const{position:position,target:target,up:up}=camera,offset=glVec3.subtract([],position,target),newPosition=glVec3.add(glVec3.create(),target,offset),newView=glMat4.lookAt(glMat4.create(),newPosition,target,up),out=output||{};return out.position=newPosition,out.view=newView,out}});var camera=Object.freeze({__proto__:null,fromOrthographicToPerspective:orthographicCamera=>{const{near:near,far:far,fov:fov}=orthographicCamera,{viewport:viewport}=orthographicCamera,projection=setProjection(orthographicCamera,{width:viewport[2],height:viewport[3]}),{projectionType:projectionType}=cameraState;return Object.assign({},orthographicCamera,projection,{projectionType:projectionType},{near:near,far:far,fov:fov})},fromPerspectiveToOrthographic:perspectiveCamera=>{const{fov:fov,aspect:aspect}=perspectiveCamera,distance=.3*glVec3.length(glVec3.subtract([],perspectiveCamera.position,perspectiveCamera.target)),width=Math.tan(fov)*distance*aspect,height=Math.tan(fov)*distance,{near:near,far:far,viewport:viewport}=perspectiveCamera,projectionType=cameraState$1.projectionType,projection=setProjection$1({zoom:1,near:near,far:far},{width:width,height:height});return Object.assign({},orthographicCamera,perspectiveCamera,projection,{projectionType:projectionType,viewport:viewport})},toPerspectiveView:({camera:camera})=>{const offsetToTarget=glVec3.distance(camera.position,camera.target),position=[offsetToTarget,offsetToTarget,offsetToTarget];return{view:glMat4.lookAt(glMat4.create(),position,camera.target,camera.up),position:position}},toPresetView:(viewName,{camera:camera})=>{const offsetToTarget=glVec3.distance(camera.position,camera.target),position=glVec3.add(glVec3.create(),{top:[0,-1e-6,1],bottom:[0,0,-1],front:[0,1,0],back:[0,-1,0],left:[-1,0,0],right:[1,0,0],undefined:[0,0,0]}[viewName].map((x=>x*offsetToTarget)),camera.target);return{view:glMat4.lookAt(glMat4.create(),position,camera.target,camera.up),position:position}}}),index$2=Object.freeze({__proto__:null,camera:camera,orthographic:orthographicCamera,perspective:perspectiveCamera});const makeDrawGrid=(regl,params={})=>{const positions=[],defaults={visuals:{color:[0,0,1,1],fadeOut:!1},ticks:1,size:[16,16],centered:!1,lineWidth:2},visuals=Object.assign({},defaults.visuals,params.visuals||{}),{fadeOut:fadeOut,color:color}=visuals,{size:size,ticks:ticks,centered:centered,lineWidth:lineWidth}=Object.assign({},defaults,params),width=size[0],length=size[1];if(centered){const halfWidth=.5*width,halfLength=.5*length,widthStart=-halfWidth+halfWidth%ticks,widthEnd=-widthStart,lengthStart=-halfLength+halfLength%ticks,lengthEnd=-lengthStart,skipEvery=0;for(let i=widthStart,j=0;i<=widthEnd;i+=ticks,j+=1)j%skipEvery!=0&&(positions.push(lengthStart,i,0),positions.push(lengthEnd,i,0),positions.push(lengthStart,i,0));for(let i=lengthStart,j=0;i<=lengthEnd;i+=ticks,j+=1)j%skipEvery!=0&&(positions.push(i,widthStart,0),positions.push(i,widthEnd,0),positions.push(i,widthStart,0))}else{for(let i=.5*-width;i<=.5*width;i+=ticks)positions.push(.5*-length,i,0),positions.push(.5*length,i,0),positions.push(.5*-length,i,0);for(let i=.5*-length;i<=.5*length;i+=ticks)positions.push(i,.5*-width,0),positions.push(i,.5*width,0),positions.push(i,.5*-width,0)}return regl({vert:"precision mediump float;\n\n uniform float camNear, camFar;\n uniform mat4 model, view, projection;\n\n attribute vec3 position;\n varying vec3 fragNormal, fragPosition;\n varying vec4 worldPosition;\n\n void main() {\n fragPosition = position;\n worldPosition = model * vec4(position, 1);\n vec4 glPosition = projection * view * worldPosition;\n gl_Position = glPosition;\n }",frag:"precision mediump float;\n uniform vec4 color;\n varying vec3 fragNormal, fragPosition;\n varying vec4 worldPosition;\n\n uniform vec4 fogColor;\n uniform bool fadeOut;\n void main() {\n float dist = .5;\n if(fadeOut){\n dist = distance( vec2(0.,0.), vec2(worldPosition.x, worldPosition.y));\n dist *= 0.0025;\n dist = sqrt(dist);\n }\n\n gl_FragColor = mix(color, fogColor, dist);\n }\n ",attributes:{position:regl.buffer(positions)},count:positions.length/3,uniforms:{model:(context,props)=>props&&props.model?props.model:glMat4.identity([]),color:(context,props)=>props&&props.color?props.color:color,fogColor:(context,props)=>props&&props.color?[props.color[0],props.color[1],props.color[2],0]:[color[0],color[1],color[2],0],fadeOut:(context,props)=>props&&void 0!==props.fadeOut?props.fadeOut:fadeOut},lineWidth:(context,props)=>Math.min(props&&props.lineWidth?props.lineWidth:lineWidth,regl.limits.lineWidthDims[1]),primitive:"lines",cull:{enable:!0,face:"front"},polygonOffset:{enable:!0,offset:{factor:1,units:10*Math.random()}},blend:{enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}})},meshColor=[0,.6,1,1];var renderDefaults=Object.freeze({__proto__:null,background:[1,1,1,1],meshColor:meshColor,lightColor:[1,1,1,1],lightDirection:[.2,.2,1],lightPosition:[100,200,100],ambientLightAmount:.3,diffuseLightAmount:.89,specularLightAmount:.16,materialShininess:8});var index$1=Object.freeze({__proto__:null,drawGrid:(regl,params)=>{const{size:size,ticks:ticks}=Object.assign({},{size:[50,50],ticks:[10,1]},params),drawMainGrid=makeDrawGrid(regl,{size:size,ticks:ticks[0]}),drawSubGrid=makeDrawGrid(regl,{size:size,ticks:ticks[1]});return props=>{drawMainGrid(props),drawSubGrid({color:props.subColor,fadeOut:props.fadeOut})}},drawAxis:(regl,params)=>{let{size:size,xColor:xColor,yColor:yColor,zColor:zColor,lineWidth:lineWidth,alwaysVisible:alwaysVisible}=Object.assign({},{xColor:[1,0,0,1],yColor:[0,1,0,1],zColor:[0,0,1,1],size:10,lineWidth:3,alwaysVisible:!0},params);lineWidth>regl.limits.lineWidthDims[1]&&(lineWidth=regl.limits.lineWidthDims[1]);const points=[0,0,0,size,0,0],commandParams={frag:"precision mediump float;\n uniform vec4 color;\n void main() {\n gl_FragColor = color;\n }",vert:"\n precision mediump float;\n attribute vec3 position;\n uniform mat4 model, view, projection;\n void main() {\n gl_Position = projection * view * model * vec4(position, 1);\n }",uniforms:{model:(context,props)=>props&&props.model?props.model:glMat4.identity([]),color:(context,props)=>props.color,angle:(contet,props)=>props.angle},attributes:{position:points},count:points.length/3,primitive:"line loop",lineWidth:lineWidth,depth:{enable:!alwaysVisible}},xAxisModel=glMat4.identity([]),yAxisModel=glMat4.rotateZ(glMat4.create(),glMat4.identity([]),Math.PI/2),zAxisModel=glMat4.rotateY(glMat4.create(),glMat4.identity([]),-Math.PI/2),single=regl(commandParams);return props=>{const defaults={model:glMat4.identity([])};return props=Object.assign({},defaults,props),single([{color:xColor,model:glMat4.multiply(glMat4.create(),props.model,xAxisModel)},{color:yColor,model:glMat4.multiply(glMat4.create(),props.model,yAxisModel)},{color:zColor,model:glMat4.multiply(glMat4.create(),props.model,zAxisModel)}])}},drawMesh:(regl,params={extras:{}})=>{const defaults={useVertexColors:!0,dynamicCulling:!0,geometry:void 0,color:meshColor,visuals:{}},{geometry:geometry,dynamicCulling:dynamicCulling,useVertexColors:useVertexColors,color:color,visuals:visuals}=Object.assign({},defaults,params),ambientOcclusion=regl.buffer([]),hasIndices=!!(geometry.indices&&geometry.indices.length>0),hasNormals=!!(geometry.normals&&geometry.normals.length>0),transparent="transparent"in visuals&&visuals.transparent,hasVertexColors=!!(useVertexColors&&geometry.colors&&geometry.colors.length>0),transforms=geometry.transforms||glMat4.create(),flip=glMat4.determinant(transforms)<0,cullFace=dynamicCulling&&flip?"front":"back",vert=hasVertexColors?"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection, unormal;\n\nattribute vec3 position, normal;\nattribute vec4 color;\n\nattribute float ao;\nvarying float ambientAo;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\nvarying vec4 vColor;\n\nvoid main() {\n surfacePosition = (unormal * vec4(position, 1.0)).xyz;\n surfaceNormal = normalize((unormal * vec4(normal, 1.0)).xyz); //vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n //gl_Position = projection * view * worldSpacePosition;\n\n vColor = color;\n\n //ambientAo = (1. - ao) * (0.5 * max(normal.x, 0.) + 0.5);\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n //gl_Position = zBufferAdjust(glPosition, camNear, camFar);\n}\n":"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\n\nvoid main() {\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n",frag=hasVertexColors?"\nprecision mediump float;\nvarying vec3 surfaceNormal, surfacePosition;\n\nuniform float ambientLightAmount;\nuniform float diffuseLightAmount;\nuniform float specularLightAmount;\n\nuniform vec3 lightDirection;\nuniform vec4 lightColor;\nuniform vec3 opacity;\nuniform float uMaterialShininess;\n\nvarying vec4 vColor;\nuniform vec4 ucolor;\nuniform float vColorToggler;\n\nuniform vec2 printableArea;\nvec4 errorColor = vec4(0.15, 0.15, 0.15, 0.3);//vec4(0.15, 0.15, 0.15, 0.3);\nvarying vec4 _worldSpacePosition;\nvarying float ambientAo;\n\nvoid main () {\n vec4 depth = gl_FragCoord;\n vec4 endColor = vColor * vColorToggler + ucolor * (1.0 - vColorToggler);\n\n vec3 ambient = ambientLightAmount * endColor.rgb ; //ambientAo * \n\n float diffuseWeight = dot(surfaceNormal, lightDirection);\n vec3 diffuse = diffuseLightAmount * endColor.rgb * clamp(diffuseWeight , 0.0, 1.0 );\n\n //specular\n \n vec4 specularColor = vec4(lightColor);\n vec3 eyeDirection = normalize(surfacePosition.xyz);\n vec3 reflectionDirection = reflect(-lightDirection, -surfaceNormal);\n float specularLightWeight = pow(max(dot(reflectionDirection, eyeDirection), 0.0), uMaterialShininess);\n vec3 specular = specularColor.rgb * specularLightWeight * specularLightAmount;\n\n gl_FragColor = vec4((ambient + diffuse + specular), endColor.a);\n}\n":"\nprecision mediump float;\nvarying vec3 surfaceNormal;\nuniform float ambientLightAmount;\nuniform float diffuseLightAmount;\nuniform vec4 ucolor;\nuniform vec3 lightDirection;\nuniform vec3 opacity;\n\nvarying vec4 _worldSpacePosition;\n\nuniform vec2 printableArea;\n\nvec4 errorColor = vec4(0.15, 0.15, 0.15, 0.3);\n\nvoid main () {\n vec4 depth = gl_FragCoord;\n\n float v = 0.8; // shadow value\n vec4 endColor = ucolor;\n\n vec3 ambient = ambientLightAmount * endColor.rgb;\n float cosTheta = dot(surfaceNormal, lightDirection);\n vec3 diffuse = diffuseLightAmount * endColor.rgb * clamp(cosTheta , 0.0, 1.0 );\n\n float cosTheta2 = dot(surfaceNormal, vec3(-lightDirection.x, -lightDirection.y, lightDirection.z));\n vec3 diffuse2 = diffuseLightAmount * endColor.rgb * clamp(cosTheta2 , 0.0, 1.0 );\n\n gl_FragColor = vec4((ambient + diffuse + diffuse2 * v), endColor.a);\n}",modelMatrixInv=glMat4.invert(glMat4.create(),transforms);let commandParams={primitive:"triangles",vert:vert,frag:frag,uniforms:{model:(context,props)=>transforms,ucolor:(context,props)=>props&&props.color?props.color:color,vColorToggler:(context,props)=>props&&props.useVertexColors&&!0===props.useVertexColors?1:0,unormal:(context,props)=>{const modelViewMatrix=glMat4.invert(glMat4.create(),props.camera.view);return glMat4.multiply(modelViewMatrix,modelMatrixInv,modelViewMatrix),glMat4.transpose(modelViewMatrix,modelViewMatrix),modelViewMatrix}},attributes:{position:regl.buffer({usage:"static",type:"float",data:geometry.positions}),ao:ambientOcclusion},cull:{enable:!0,face:cullFace}};return transparent&&(commandParams.blend={enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}),geometry.cells?commandParams.elements=geometry.cells:hasIndices?commandParams.elements=regl.elements({usage:"static",type:"uint16",data:geometry.indices}):geometry.triangles?commandParams.elements=geometry.triangles:commandParams.count=geometry.positions.length/3,hasNormals&&(commandParams.attributes.normal=regl.buffer({usage:"static",type:"float",data:geometry.normals})),hasVertexColors&&(commandParams.attributes.color=regl.buffer({usage:"static",type:"float",data:geometry.colors})),commandParams=Object.assign({},commandParams,params.extras),regl(commandParams)},drawLines:(regl,params={})=>{const defaults={color:meshColor,geometry:void 0};let{geometry:geometry,color:color,transparent:transparent}=Object.assign({},defaults,params);"color"in geometry&&(color=geometry.color);const hasIndices=!!(geometry.indices&&geometry.indices.length>0),hasNormals=!!(geometry.normals&&geometry.normals.length>0),hasVertexColors=!!(geometry.colors&&geometry.colors.length>0),commandParams={primitive:"lines",vert:hasVertexColors?"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\nattribute vec4 color;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\nvarying vec4 vColor;\n\nvoid main() {\n vColor = color;\n\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n":"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\n\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\n\n\nvoid main() {\n\n\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n",frag:hasVertexColors?"\nprecision mediump float;\nvarying vec4 vColor;\n\nvoid main () {\n gl_FragColor = vColor;\n}\n":"\nprecision mediump float;\nuniform vec4 ucolor;\n\nvoid main () {\n gl_FragColor = ucolor;\n}\n",uniforms:{model:(context,props)=>props.model||geometry.transforms||glMat4.create(),ucolor:(context,props)=>props&&props.color?props.color:color},attributes:{position:regl.buffer({usage:"static",type:"float",data:geometry.positions})}};return transparent&&(commandParams.blend={enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}),hasVertexColors&&(commandParams.attributes.color=regl.buffer({usage:"static",type:"float",data:geometry.colors})),hasIndices&&(commandParams.elements=regl.elements({usage:"static",type:"uint16",data:geometry.indices})),hasNormals&&(commandParams.attributes.normal=regl.buffer({usage:"static",type:"float",data:geometry.normals})),regl(commandParams)}}),projectMat4=function(out,vec,m){var x=vec[0],y=vec[1],z=vec[2],a00=m[0],a01=m[1],a02=m[2],a03=m[3],a10=m[4],a11=m[5],a12=m[6],a13=m[7],a20=m[8],a21=m[9],a22=m[10],a23=m[11],a30=m[12],a31=m[13],a32=m[14],a33=m[15],lw=1/(x*a03+y*a13+z*a23+a33);return out[0]=(x*a00+y*a10+z*a20+a30)*lw,out[1]=(x*a01+y*a11+z*a21+a31)*lw,out[2]=(x*a02+y*a12+z*a22+a32)*lw,out};var transform=projectMat4,cameraUnproject=function(out,vec,viewport,invProjectionView){var viewX=viewport[0],viewY=viewport[1],viewWidth=viewport[2],viewHeight=viewport[3],x=vec[0],y=vec[1],z=vec[2];return x-=viewX,y=viewHeight-y-1,y-=viewY,out[0]=2*x/viewWidth-1,out[1]=2*y/viewHeight-1,out[2]=2*z-1,transform(out,out,invProjectionView)} /** * JSCAD Utility functions for arrays * @module @jscad/array-utils - * @version 3.0.0-alpha.0 + * @version 3.0.1-alpha.0 * @license MIT */;const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),computeBounds=(...geometries)=>{let bbox;(geometries=flatten(geometries)).forEach((geometry=>{let gbbox=(positions=>{if(0===positions.length)return[[0,0,0],[0,0,0]];const nested=Array.isArray(positions)&&Array.isArray(positions[0]),dimensions=nested?positions[0].length:3,min=new Array(dimensions),max=new Array(dimensions);for(let i=0;i{for(let i=0;imax[i]?_position:max[i],min[i]=_positionmax[i]?_position:max[i],min[i]=_positionglVec3.transformMat4(bounds,bounds,geometry.transforms))),bbox?(glVec3.min(bbox[0],bbox[0],gbbox[0]),glVec3.max(bbox[1],bbox[1],gbbox[1])):bbox=gbbox}));const min=glVec3.min(glVec3.create(),bbox[1],bbox[0]),max=glVec3.max(glVec3.create(),bbox[1],bbox[0]),size=glVec3.subtract(glVec3.create(),max,min);let center=glVec3.scale(glVec3.create(),size,.5);center=glVec3.add(center,min,center);return{dia:glVec3.distance(center,max),center:[...center],min:[...min],max:[...max],size:[...size]}},{max:max,min:min,sqrt:sqrt,PI:PI,sin:sin,cos:cos,atan2:atan2}=Math,controlsProps={limits:{minDistance:.01,maxDistance:1e4},drag:.27,EPS:1e-6,zoomToFit:{auto:!0,targets:"all",tightness:1.5},userControl:{zoom:!0,zoomSpeed:1,rotate:!0,rotateSpeed:1,pan:!0,panSpeed:1},autoRotate:{enabled:!1,speed:1},autoAdjustPlanes:!0},controlsState={thetaDelta:0,phiDelta:0,scale:1},defaults=Object.assign({},controlsState,controlsProps);var orbitControls=Object.freeze({__proto__:null,controlsProps:controlsProps,controlsState:controlsState,defaults:defaults,update:({controls:controls,camera:camera},output)=>{const{EPS:EPS,drag:drag}=controls,{position:position,target:target}=camera,up=controls.up?controls.up:camera.up;let curThetaDelta=controls.thetaDelta;const curPhiDelta=controls.phiDelta,curScale=controls.scale,offset=glVec3.subtract([],position,target);let theta,phi;1===up[2]?(theta=atan2(offset[0],offset[1]),phi=atan2(sqrt(offset[0]*offset[0]+offset[1]*offset[1]),offset[2])):(theta=atan2(offset[0],offset[2]),phi=atan2(sqrt(offset[0]*offset[0]+offset[2]*offset[2]),offset[1])),controls.autoRotate.enabled&&controls.userControl.rotate&&(curThetaDelta+=2*Math.PI/60/60*controls.autoRotate.speed),theta+=curThetaDelta,phi+=curPhiDelta,phi=max(EPS,min(PI-EPS,phi));const radius=max(controls.limits.minDistance,min(controls.limits.maxDistance,glVec3.length(offset)*curScale));1===up[2]?(offset[0]=radius*sin(phi)*sin(theta),offset[2]=radius*cos(phi),offset[1]=radius*sin(phi)*cos(theta)):(offset[0]=radius*sin(phi)*sin(theta),offset[1]=radius*cos(phi),offset[2]=radius*sin(phi)*cos(theta));const newPosition=glVec3.add(glVec3.create(),target,offset),newView=glMat4.lookAt(glMat4.create(),newPosition,target,up),dragEffect=1-max(min(drag,1),.01);return{controls:{thetaDelta:curThetaDelta*dragEffect,phiDelta:curPhiDelta*dragEffect,scale:1,changed:glVec3.distance(position,newPosition)>.001},camera:{position:newPosition,view:newView}}},rotate:({controls:controls,camera:camera,speed:speed=1},angle)=>{let{thetaDelta:thetaDelta,phiDelta:phiDelta}=controls;return controls.userControl.rotate&&(thetaDelta+=angle[0]*speed,phiDelta+=angle[1]*speed),{controls:{thetaDelta:thetaDelta,phiDelta:phiDelta},camera:camera}},zoom:({controls:controls,camera:camera,speed:speed=1},zoomDelta=0)=>{let{scale:scale}=controls;if(controls.userControl.zoom&&camera&&void 0!==zoomDelta&&0!==zoomDelta&&!isNaN(zoomDelta)){const newScale=(zoomDelta=zoomDelta/zoomDelta*(0===Math.sign(zoomDelta)?1:Math.sign(zoomDelta))*speed)+controls.scale,newDistance=glVec3.distance(camera.position,camera.target)*newScale;if(newDistance>controls.limits.minDistance&&newDistance{const{projection:projection,view:view,viewport:viewport}=camera,combinedProjView=glMat4.multiply([],projection,view),invProjView=glMat4.invert([],combinedProjView),panStart=[viewport[2],viewport[3],0],panEnd=[viewport[2]-delta[0],viewport[3]+delta[1],0],unPanStart=cameraUnproject.unproject([],panStart,viewport,invProjView),unPanEnd=cameraUnproject.unproject([],panEnd,viewport,invProjView),eyeDistance=glVec3.distance(camera.position,camera.eye),offset=glVec3.subtract([],unPanStart,unPanEnd).map((x=>x*speed*eyeDistance*controls.scale));return{controls:controls,camera:{position:glVec3.add(glVec3.create(),camera.position,offset),target:glVec3.add(glVec3.create(),camera.target,offset)}}},zoomToFit:({controls:controls,camera:camera,entities:entities})=>{const{zoomToFit:zoomToFit}=controls;if("all"!==zoomToFit.targets)return{controls:controls,camera:camera};if(0===entities.length)return{controls:controls,camera:camera};const geometries=entities.map((entity=>entity.geometry)),bounds=computeBounds(geometries),{fov:fov,target:target,position:position}=camera,{tightness:tightness}=Object.assign({},zoomToFit,controlsProps.zoomToFit),scaleForIdealDistance=bounds.dia*tightness/Math.tan(fov/2)/glVec3.distance(target,position);return{camera:{target:bounds.center},controls:{scale:scaleForIdealDistance}}},reset:({controls:controls,camera:camera},desiredState)=>({camera:{position:desiredState.camera.position,target:desiredState.camera.target,projection:glMat4.perspective([],camera.fov,camera.aspect,camera.near,camera.far),view:desiredState.camera.view},controls:{thetaDelta:desiredState.controls.thetaDelta,phiDelta:desiredState.controls.phiDelta,scale:desiredState.controls.scale}})}),index=Object.freeze({__proto__:null,orbit:orbitControls});const maxIndex$2=Math.floor(32767.5),polygonColor=(polygon,color)=>{let faceColor=color;return polygon.color&&(faceColor=polygon.color),faceColor&&faceColor.length<4&&faceColor.push(1),faceColor},calculateNormal=polygon=>{if(polygon.plane)return glVec3.clone(polygon.plane);const vertices=polygon.vertices,ba=glVec3.create();glVec3.subtract(ba,vertices[1],vertices[0]);const ca=glVec3.create();glVec3.subtract(ca,vertices[2],vertices[0]);const normal=glVec3.create();return glVec3.cross(normal,ba,ca),glVec3.normalize(normal,normal),normal},maxIndex=Math.floor(32767.5)-2;var reglExports={};!function(module,exports){module.exports=function(){var isTypedArray=function(x){return x instanceof Uint8Array||x instanceof Uint16Array||x instanceof Uint32Array||x instanceof Int8Array||x instanceof Int16Array||x instanceof Int32Array||x instanceof Float32Array||x instanceof Float64Array||x instanceof Uint8ClampedArray},extend=function(base,opts){for(var keys=Object.keys(opts),i=0;i=0&&(0|value)===value||raise("invalid parameter type, ("+value+")"+encolon(message)+". must be a nonnegative integer")}function checkOneOf(value,list,message){list.indexOf(value)<0&&raise("invalid value"+encolon(message)+". must be one of: "+list)}var constructorKeys=["gl","canvas","container","attributes","pixelRatio","extensions","optionalExtensions","profile","onDone"];function checkConstructor(obj){Object.keys(obj).forEach((function(key){constructorKeys.indexOf(key)<0&&raise('invalid regl constructor argument "'+key+'". must be one of '+constructorKeys)}))}function leftPad(str,n){for(str+="";str.length0&&result.push(new ShaderError("unknown",0,errMsg))}})),result}function annotateFiles(files,errors){errors.forEach((function(error){var file=files[error.file];if(file){var line=file.index[error.line];if(line)return line.errors.push(error),void(file.hasErrors=!0)}files.unknown.hasErrors=!0,files.unknown.lines[0].errors.push(error)}))}function checkShaderError(gl,shader,source,type,command){if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){var errLog=gl.getShaderInfoLog(shader),typeName=type===gl.FRAGMENT_SHADER?"fragment":"vertex";checkCommandType(source,"string",typeName+" shader source must be a string",command);var files=parseSource(source,command),errors=parseErrorLog(errLog);annotateFiles(files,errors),Object.keys(files).forEach((function(fileNumber){var file=files[fileNumber];if(file.hasErrors){var strings=[""],styles=[""];push("file number "+fileNumber+": "+file.name+"\n","color:red;text-decoration:underline;font-weight:bold"),file.lines.forEach((function(line){if(line.errors.length>0){push(leftPad(line.number,4)+"| ","background-color:yellow; font-weight:bold"),push(line.line+endl,"color:red; background-color:yellow; font-weight:bold");var offset=0;line.errors.forEach((function(error){var message=error.message,token=/^\s*'(.*)'\s*:\s*(.*)$/.exec(message);if(token){var tokenPat=token[1];message=token[2],"assign"===tokenPat&&(tokenPat="="),offset=Math.max(line.line.indexOf(tokenPat,offset),0)}else offset=0;push(leftPad("| ",6)),push(leftPad("^^^",offset+3)+endl,"font-weight:bold"),push(leftPad("| ",6)),push(message+endl,"font-weight:bold")})),push(leftPad("| ",6)+endl)}else push(leftPad(line.number,4)+"| "),push(line.line+endl,"color:red")})),"undefined"==typeof document||window.chrome?console.log(strings.join("")):(styles[0]=strings.join("%c"),console.log.apply(console,styles))}function push(str,style){strings.push(str),styles.push(style||"")}})),check.raise("Error compiling "+typeName+" shader, "+files[0].name)}}function checkLinkError(gl,program,fragShader,vertShader,command){if(!gl.getProgramParameter(program,gl.LINK_STATUS)){var errLog=gl.getProgramInfoLog(program),fragParse=parseSource(fragShader,command),header='Error linking program with vertex shader, "'+parseSource(vertShader,command)[0].name+'", and fragment shader "'+fragParse[0].name+'"';"undefined"!=typeof document?console.log("%c"+header+endl+"%c"+errLog,"color:red;text-decoration:underline;font-weight:bold","color:red"):console.log(header+endl+errLog),check.raise(header)}}function saveCommandRef(object){object._commandRef=guessCommand()}function saveDrawCommandInfo(opts,uniforms,attributes,stringStore){function id(str){return str?stringStore.id(str):0}function addProps(dict,set){Object.keys(set).forEach((function(u){dict[stringStore.id(u)]=!0}))}saveCommandRef(opts),opts._fragId=id(opts.static.frag),opts._vertId=id(opts.static.vert);var uniformSet=opts._uniformSet={};addProps(uniformSet,uniforms.static),addProps(uniformSet,uniforms.dynamic);var attributeSet=opts._attributeSet={};addProps(attributeSet,attributes.static),addProps(attributeSet,attributes.dynamic),opts._hasCount="count"in opts.static||"count"in opts.dynamic||"elements"in opts.static||"elements"in opts.dynamic}function commandRaise(message,command){var callSite=guessCallSite();raise(message+" in command "+(command||guessCommand())+("unknown"===callSite?"":" called from "+callSite))}function checkCommand(pred,message,command){pred||commandRaise(message,command||guessCommand())}function checkParameterCommand(param,possibilities,message,command){param in possibilities||commandRaise("unknown parameter ("+param+")"+encolon(message)+". possible values: "+Object.keys(possibilities).join(),command||guessCommand())}function checkCommandType(value,type,message,command){standardTypeEh(value,type)||commandRaise("invalid parameter type"+encolon(message)+". expected "+type+", got "+typeof value,command||guessCommand())}function checkOptional(block){block()}function checkFramebufferFormat(attachment,texFormats,rbFormats){attachment.texture?checkOneOf(attachment.texture._texture.internalformat,texFormats,"unsupported texture format for attachment"):checkOneOf(attachment.renderbuffer._renderbuffer.format,rbFormats,"unsupported renderbuffer format for attachment")}var GL_CLAMP_TO_EDGE=33071,GL_NEAREST=9728,GL_NEAREST_MIPMAP_NEAREST=9984,GL_LINEAR_MIPMAP_NEAREST=9985,GL_NEAREST_MIPMAP_LINEAR=9986,GL_LINEAR_MIPMAP_LINEAR=9987,GL_UNSIGNED_BYTE=5121,GL_SHORT=5122,GL_UNSIGNED_SHORT=5123,GL_INT=5124,GL_UNSIGNED_INT=5125,GL_FLOAT=5126,GL_UNSIGNED_SHORT_4_4_4_4=32819,GL_UNSIGNED_SHORT_5_5_5_1=32820,GL_UNSIGNED_SHORT_5_6_5=33635,GL_UNSIGNED_INT_24_8_WEBGL=34042,GL_HALF_FLOAT_OES=36193,TYPE_SIZE={};function pixelSize(type,channels){return type===GL_UNSIGNED_SHORT_5_5_5_1||type===GL_UNSIGNED_SHORT_4_4_4_4||type===GL_UNSIGNED_SHORT_5_6_5?2:type===GL_UNSIGNED_INT_24_8_WEBGL?4:TYPE_SIZE[type]*channels}function isPow2(v){return!(v&v-1||!v)}function checkTexture2D(info,mipData,limits){var i,w=mipData.width,h=mipData.height,c=mipData.channels;check(w>0&&w<=limits.maxTextureSize&&h>0&&h<=limits.maxTextureSize,"invalid texture shape"),info.wrapS===GL_CLAMP_TO_EDGE&&info.wrapT===GL_CLAMP_TO_EDGE||check(isPow2(w)&&isPow2(h),"incompatible wrap mode for texture, both width and height must be power of 2"),1===mipData.mipmask?1!==w&&1!==h&&check(info.minFilter!==GL_NEAREST_MIPMAP_NEAREST&&info.minFilter!==GL_NEAREST_MIPMAP_LINEAR&&info.minFilter!==GL_LINEAR_MIPMAP_NEAREST&&info.minFilter!==GL_LINEAR_MIPMAP_LINEAR,"min filter requires mipmap"):(check(isPow2(w)&&isPow2(h),"texture must be a square power of 2 to support mipmapping"),check(mipData.mipmask===(w<<1)-1,"missing or incomplete mipmap data")),mipData.type===GL_FLOAT&&(limits.extensions.indexOf("oes_texture_float_linear")<0&&check(info.minFilter===GL_NEAREST&&info.magFilter===GL_NEAREST,"filter not supported, must enable oes_texture_float_linear"),check(!info.genMipmaps,"mipmap generation not supported with float textures"));var mipimages=mipData.images;for(i=0;i<16;++i)if(mipimages[i]){var mw=w>>i,mh=h>>i;check(mipData.mipmask&1<0&&w<=limits.maxTextureSize&&h>0&&h<=limits.maxTextureSize,"invalid texture shape"),check(w===h,"cube map must be square"),check(info.wrapS===GL_CLAMP_TO_EDGE&&info.wrapT===GL_CLAMP_TO_EDGE,"wrap mode not supported by cube map");for(var i=0;i>j,mh=h>>j;check(face.mipmask&1<1&&firstChar===lastChar&&('"'===firstChar||"'"===firstChar))return['"'+escapeStr(str.substr(1,str.length-2))+'"'];var parts=/\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(str);if(parts)return splitParts(str.substr(0,parts.index)).concat(splitParts(parts[1])).concat(splitParts(str.substr(parts.index+parts[0].length)));var subparts=str.split(".");if(1===subparts.length)return['"'+escapeStr(str)+'"'];for(var result=[],i=0;i0,"invalid pixel ratio"))):check$1.raise("invalid arguments to regl"),element&&("canvas"===element.nodeName.toLowerCase()?canvas=element:container=element),!gl){if(!canvas){check$1("undefined"!=typeof document,"must manually specify webgl context outside of DOM environments");var result=createCanvas(container||document.body,onDone,pixelRatio);if(!result)return null;canvas=result.canvas,onDestroy=result.onDestroy}void 0===contextAttributes.premultipliedAlpha&&(contextAttributes.premultipliedAlpha=!0),gl=createContext(canvas,contextAttributes)}return gl?{gl:gl,canvas:canvas,container:container,extensions:extensions,optionalExtensions:optionalExtensions,pixelRatio:pixelRatio,profile:profile,onDone:onDone,onDestroy:onDestroy}:(onDestroy(),onDone("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"),null)}function createExtensionCache(gl,config){var extensions={};function tryLoadExtension(name_){check$1.type(name_,"string","extension name must be string");var ext,name=name_.toLowerCase();try{ext=extensions[name]=gl.getExtension(name)}catch(e){}return!!ext}for(var i=0;i65535)<<4,r|=shift=((v>>>=r)>255)<<3,r|=shift=((v>>>=shift)>15)<<2,(r|=shift=((v>>>=shift)>3)<<1)|(v>>>=shift)>>1}function createPool(){var bufferPool=loop(8,(function(){return[]}));function alloc(n){var sz=nextPow16(n),bin=bufferPool[log2(sz)>>2];return bin.length>0?bin.pop():new ArrayBuffer(sz)}function free(buf){bufferPool[log2(buf.byteLength)>>2].push(buf)}function allocType(type,n){var result=null;switch(type){case GL_BYTE$1:result=new Int8Array(alloc(n),0,n);break;case GL_UNSIGNED_BYTE$2:result=new Uint8Array(alloc(n),0,n);break;case GL_SHORT$1:result=new Int16Array(alloc(2*n),0,n);break;case GL_UNSIGNED_SHORT$1:result=new Uint16Array(alloc(2*n),0,n);break;case GL_INT$1:result=new Int32Array(alloc(4*n),0,n);break;case GL_UNSIGNED_INT$1:result=new Uint32Array(alloc(4*n),0,n);break;case GL_FLOAT$2:result=new Float32Array(alloc(4*n),0,n);break;default:return null}return result.length!==n?result.subarray(0,n):result}function freeType(array){free(array.buffer)}return{alloc:alloc,free:free,allocType:allocType,freeType:freeType}}var pool=createPool();pool.zero=createPool();var GL_SUBPIXEL_BITS=3408,GL_RED_BITS=3410,GL_GREEN_BITS=3411,GL_BLUE_BITS=3412,GL_ALPHA_BITS=3413,GL_DEPTH_BITS=3414,GL_STENCIL_BITS=3415,GL_ALIASED_POINT_SIZE_RANGE=33901,GL_ALIASED_LINE_WIDTH_RANGE=33902,GL_MAX_TEXTURE_SIZE=3379,GL_MAX_VIEWPORT_DIMS=3386,GL_MAX_VERTEX_ATTRIBS=34921,GL_MAX_VERTEX_UNIFORM_VECTORS=36347,GL_MAX_VARYING_VECTORS=36348,GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS=35661,GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS=35660,GL_MAX_TEXTURE_IMAGE_UNITS=34930,GL_MAX_FRAGMENT_UNIFORM_VECTORS=36349,GL_MAX_CUBE_MAP_TEXTURE_SIZE=34076,GL_MAX_RENDERBUFFER_SIZE=34024,GL_VENDOR=7936,GL_RENDERER=7937,GL_VERSION=7938,GL_SHADING_LANGUAGE_VERSION=35724,GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT=34047,GL_MAX_COLOR_ATTACHMENTS_WEBGL=36063,GL_MAX_DRAW_BUFFERS_WEBGL=34852,GL_TEXTURE_2D=3553,GL_TEXTURE_CUBE_MAP=34067,GL_TEXTURE_CUBE_MAP_POSITIVE_X=34069,GL_TEXTURE0=33984,GL_RGBA=6408,GL_FLOAT$1=5126,GL_UNSIGNED_BYTE$1=5121,GL_FRAMEBUFFER=36160,GL_FRAMEBUFFER_COMPLETE=36053,GL_COLOR_ATTACHMENT0=36064,GL_COLOR_BUFFER_BIT$1=16384,wrapLimits=function(gl,extensions){var maxAnisotropic=1;extensions.ext_texture_filter_anisotropic&&(maxAnisotropic=gl.getParameter(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT));var maxDrawbuffers=1,maxColorAttachments=1;extensions.webgl_draw_buffers&&(maxDrawbuffers=gl.getParameter(GL_MAX_DRAW_BUFFERS_WEBGL),maxColorAttachments=gl.getParameter(GL_MAX_COLOR_ATTACHMENTS_WEBGL));var readFloat=!!extensions.oes_texture_float;if(readFloat){var readFloatTexture=gl.createTexture();gl.bindTexture(GL_TEXTURE_2D,readFloatTexture),gl.texImage2D(GL_TEXTURE_2D,0,GL_RGBA,1,1,0,GL_RGBA,GL_FLOAT$1,null);var fbo=gl.createFramebuffer();if(gl.bindFramebuffer(GL_FRAMEBUFFER,fbo),gl.framebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,readFloatTexture,0),gl.bindTexture(GL_TEXTURE_2D,null),gl.checkFramebufferStatus(GL_FRAMEBUFFER)!==GL_FRAMEBUFFER_COMPLETE)readFloat=!1;else{gl.viewport(0,0,1,1),gl.clearColor(1,0,0,1),gl.clear(GL_COLOR_BUFFER_BIT$1);var pixels=pool.allocType(GL_FLOAT$1,4);gl.readPixels(0,0,1,1,GL_RGBA,GL_FLOAT$1,pixels),gl.getError()?readFloat=!1:(gl.deleteFramebuffer(fbo),gl.deleteTexture(readFloatTexture),readFloat=1===pixels[0]),pool.freeType(pixels)}}var npotTextureCube=!0;if("undefined"==typeof navigator||!(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)||/Edge/.test(navigator.userAgent))){var cubeTexture=gl.createTexture(),data=pool.allocType(GL_UNSIGNED_BYTE$1,36);gl.activeTexture(GL_TEXTURE0),gl.bindTexture(GL_TEXTURE_CUBE_MAP,cubeTexture),gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X,0,GL_RGBA,3,3,0,GL_RGBA,GL_UNSIGNED_BYTE$1,data),pool.freeType(data),gl.bindTexture(GL_TEXTURE_CUBE_MAP,null),gl.deleteTexture(cubeTexture),npotTextureCube=!gl.getError()}return{colorBits:[gl.getParameter(GL_RED_BITS),gl.getParameter(GL_GREEN_BITS),gl.getParameter(GL_BLUE_BITS),gl.getParameter(GL_ALPHA_BITS)],depthBits:gl.getParameter(GL_DEPTH_BITS),stencilBits:gl.getParameter(GL_STENCIL_BITS),subpixelBits:gl.getParameter(GL_SUBPIXEL_BITS),extensions:Object.keys(extensions).filter((function(ext){return!!extensions[ext]})),maxAnisotropic:maxAnisotropic,maxDrawbuffers:maxDrawbuffers,maxColorAttachments:maxColorAttachments,pointSizeDims:gl.getParameter(GL_ALIASED_POINT_SIZE_RANGE),lineWidthDims:gl.getParameter(GL_ALIASED_LINE_WIDTH_RANGE),maxViewportDims:gl.getParameter(GL_MAX_VIEWPORT_DIMS),maxCombinedTextureUnits:gl.getParameter(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxCubeMapSize:gl.getParameter(GL_MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderbufferSize:gl.getParameter(GL_MAX_RENDERBUFFER_SIZE),maxTextureUnits:gl.getParameter(GL_MAX_TEXTURE_IMAGE_UNITS),maxTextureSize:gl.getParameter(GL_MAX_TEXTURE_SIZE),maxAttributes:gl.getParameter(GL_MAX_VERTEX_ATTRIBS),maxVertexUniforms:gl.getParameter(GL_MAX_VERTEX_UNIFORM_VECTORS),maxVertexTextureUnits:gl.getParameter(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxVaryingVectors:gl.getParameter(GL_MAX_VARYING_VECTORS),maxFragmentUniforms:gl.getParameter(GL_MAX_FRAGMENT_UNIFORM_VECTORS),glsl:gl.getParameter(GL_SHADING_LANGUAGE_VERSION),renderer:gl.getParameter(GL_RENDERER),vendor:gl.getParameter(GL_VENDOR),version:gl.getParameter(GL_VERSION),readFloat:readFloat,npotTextureCube:npotTextureCube}};function isNDArrayLike(obj){return!!obj&&"object"==typeof obj&&Array.isArray(obj.shape)&&Array.isArray(obj.stride)&&"number"==typeof obj.offset&&obj.shape.length===obj.stride.length&&(Array.isArray(obj.data)||isTypedArray(obj.data))}var values=function(obj){return Object.keys(obj).map((function(key){return obj[key]}))},flattenUtils={shape:arrayShape$1,flatten:flattenArray};function flatten1D(array,nx,out){for(var i=0;i0)if(Array.isArray(data[0])){shape=arrayShape(data);for(var dim=1,i=1;i0)if("number"==typeof data[0]){var converted=pool.allocType(buffer.dtype,data.length);copyArray(converted,data),setSubData(converted,offset),pool.freeType(converted)}else if(Array.isArray(data[0])||isTypedArray(data[0])){shape=arrayShape(data);var flatData=arrayFlatten(data,shape,buffer.dtype);setSubData(flatData,offset),pool.freeType(flatData)}else check$1.raise("invalid buffer data")}else if(isNDArrayLike(data)){shape=data.shape;var stride=data.stride,shapeX=0,shapeY=0,strideX=0,strideY=0;1===shape.length?(shapeX=shape[0],shapeY=1,strideX=stride[0],strideY=0):2===shape.length?(shapeX=shape[0],shapeY=shape[1],strideX=stride[0],strideY=stride[1]):check$1.raise("invalid shape");var dtype=Array.isArray(data.data)?buffer.dtype:typedArrayCode(data.data),transposeData=pool.allocType(dtype,shapeX*shapeY);transpose(transposeData,data.data,shapeX,shapeY,strideX,strideY,data.offset),setSubData(transposeData,offset),pool.freeType(transposeData)}else check$1.raise("invalid data for buffer subdata");return reglBuffer}return bufferSet[buffer.id]=buffer,deferInit||reglBuffer(options),reglBuffer._reglType="buffer",reglBuffer._buffer=buffer,reglBuffer.subdata=subdata,config.profile&&(reglBuffer.stats=buffer.stats),reglBuffer.destroy=function(){destroy(buffer)},reglBuffer}function restoreBuffers(){values(bufferSet).forEach((function(buffer){buffer.buffer=gl.createBuffer(),gl.bindBuffer(buffer.type,buffer.buffer),gl.bufferData(buffer.type,buffer.persistentData||buffer.byteLength,buffer.usage)}))}return config.profile&&(stats.getTotalBufferSize=function(){var total=0;return Object.keys(bufferSet).forEach((function(key){total+=bufferSet[key].stats.size})),total}),{create:createBuffer,createStream:createStream,destroyStream:destroyStream,clear:function(){values(bufferSet).forEach(destroy),streamPool.forEach(destroy)},getBuffer:function(wrapper){return wrapper&&wrapper._buffer instanceof REGLBuffer?wrapper._buffer:null},restore:restoreBuffers,_initBuffer:initBufferFromData}}DTYPES_SIZES[5120]=1,DTYPES_SIZES[5122]=2,DTYPES_SIZES[5124]=4,DTYPES_SIZES[5121]=1,DTYPES_SIZES[5123]=2,DTYPES_SIZES[5125]=4,DTYPES_SIZES[5126]=4;var primTypes={points:0,point:0,lines:1,line:1,triangles:4,triangle:4,"line loop":2,"line strip":3,"triangle strip":5,"triangle fan":6},GL_POINTS=0,GL_LINES=1,GL_TRIANGLES=4,GL_BYTE$2=5120,GL_UNSIGNED_BYTE$4=5121,GL_SHORT$2=5122,GL_UNSIGNED_SHORT$2=5123,GL_INT$2=5124,GL_UNSIGNED_INT$2=5125,GL_ELEMENT_ARRAY_BUFFER=34963,GL_STREAM_DRAW$1=35040,GL_STATIC_DRAW$1=35044;function wrapElementsState(gl,extensions,bufferState,stats){var elementSet={},elementCount=0,elementTypes={uint8:GL_UNSIGNED_BYTE$4,uint16:GL_UNSIGNED_SHORT$2};function REGLElementBuffer(buffer){this.id=elementCount++,elementSet[this.id]=this,this.buffer=buffer,this.primType=GL_TRIANGLES,this.vertCount=0,this.type=0}extensions.oes_element_index_uint&&(elementTypes.uint32=GL_UNSIGNED_INT$2),REGLElementBuffer.prototype.bind=function(){this.buffer.bind()};var bufferPool=[];function createElementStream(data){var result=bufferPool.pop();return result||(result=new REGLElementBuffer(bufferState.create(null,GL_ELEMENT_ARRAY_BUFFER,!0,!1)._buffer)),initElements(result,data,GL_STREAM_DRAW$1,-1,-1,0,0),result}function destroyElementStream(elements){bufferPool.push(elements)}function initElements(elements,data,usage,prim,count,byteLength,type){var dtype;if(elements.buffer.bind(),data){var predictedType=type;type||isTypedArray(data)&&(!isNDArrayLike(data)||isTypedArray(data.data))||(predictedType=extensions.oes_element_index_uint?GL_UNSIGNED_INT$2:GL_UNSIGNED_SHORT$2),bufferState._initBuffer(elements.buffer,data,usage,predictedType,3)}else gl.bufferData(GL_ELEMENT_ARRAY_BUFFER,byteLength,usage),elements.buffer.dtype=dtype||GL_UNSIGNED_BYTE$4,elements.buffer.usage=usage,elements.buffer.dimension=3,elements.buffer.byteLength=byteLength;if(dtype=type,!type){switch(elements.buffer.dtype){case GL_UNSIGNED_BYTE$4:case GL_BYTE$2:dtype=GL_UNSIGNED_BYTE$4;break;case GL_UNSIGNED_SHORT$2:case GL_SHORT$2:dtype=GL_UNSIGNED_SHORT$2;break;case GL_UNSIGNED_INT$2:case GL_INT$2:dtype=GL_UNSIGNED_INT$2;break;default:check$1.raise("unsupported type for element array")}elements.buffer.dtype=dtype}elements.type=dtype,check$1(dtype!==GL_UNSIGNED_INT$2||!!extensions.oes_element_index_uint,"32 bit element buffers not supported, enable oes_element_index_uint first");var vertCount=count;vertCount<0&&(vertCount=elements.buffer.byteLength,dtype===GL_UNSIGNED_SHORT$2?vertCount>>=1:dtype===GL_UNSIGNED_INT$2&&(vertCount>>=2)),elements.vertCount=vertCount;var primType=prim;if(prim<0){primType=GL_TRIANGLES;var dimension=elements.buffer.dimension;1===dimension&&(primType=GL_POINTS),2===dimension&&(primType=GL_LINES),3===dimension&&(primType=GL_TRIANGLES)}elements.primType=primType}function destroyElements(elements){stats.elementsCount--,check$1(null!==elements.buffer,"must not double destroy elements"),delete elementSet[elements.id],elements.buffer.destroy(),elements.buffer=null}function createElements(options,persistent){var buffer=bufferState.create(null,GL_ELEMENT_ARRAY_BUFFER,!0),elements=new REGLElementBuffer(buffer._buffer);function reglElements(options){if(options)if("number"==typeof options)buffer(options),elements.primType=GL_TRIANGLES,elements.vertCount=0|options,elements.type=GL_UNSIGNED_BYTE$4;else{var data=null,usage=GL_STATIC_DRAW$1,primType=-1,vertCount=-1,byteLength=0,dtype=0;Array.isArray(options)||isTypedArray(options)||isNDArrayLike(options)?data=options:(check$1.type(options,"object","invalid arguments for elements"),"data"in options&&(data=options.data,check$1(Array.isArray(data)||isTypedArray(data)||isNDArrayLike(data),"invalid data for element buffer")),"usage"in options&&(check$1.parameter(options.usage,usageTypes,"invalid element buffer usage"),usage=usageTypes[options.usage]),"primitive"in options&&(check$1.parameter(options.primitive,primTypes,"invalid element buffer primitive"),primType=primTypes[options.primitive]),"count"in options&&(check$1("number"==typeof options.count&&options.count>=0,"invalid vertex count for elements"),vertCount=0|options.count),"type"in options&&(check$1.parameter(options.type,elementTypes,"invalid buffer type"),dtype=elementTypes[options.type]),"length"in options?byteLength=0|options.length:(byteLength=vertCount,dtype===GL_UNSIGNED_SHORT$2||dtype===GL_SHORT$2?byteLength*=2:dtype!==GL_UNSIGNED_INT$2&&dtype!==GL_INT$2||(byteLength*=4))),initElements(elements,data,usage,primType,vertCount,byteLength,dtype)}else buffer(),elements.primType=GL_TRIANGLES,elements.vertCount=0,elements.type=GL_UNSIGNED_BYTE$4;return reglElements}return stats.elementsCount++,reglElements(options),reglElements._reglType="elements",reglElements._elements=elements,reglElements.subdata=function(data,offset){return buffer.subdata(data,offset),reglElements},reglElements.destroy=function(){destroyElements(elements)},reglElements}return{create:createElements,createStream:createElementStream,destroyStream:destroyElementStream,getElements:function(elements){return"function"==typeof elements&&elements._elements instanceof REGLElementBuffer?elements._elements:null},clear:function(){values(elementSet).forEach(destroyElements)}}}var FLOAT=new Float32Array(1),INT=new Uint32Array(FLOAT.buffer),GL_UNSIGNED_SHORT$4=5123;function convertToHalfFloat(array){for(var ushorts=pool.allocType(GL_UNSIGNED_SHORT$4,array.length),i=0;i>>31<<15,exp=(x<<1>>>24)-127,frac=x>>13&1023;if(exp<-24)ushorts[i]=sgn;else if(exp<-14){var s=-14-exp;ushorts[i]=sgn+(frac+1024>>s)}else ushorts[i]=exp>15?sgn+31744:sgn+(exp+15<<10)+frac}return ushorts}function isArrayLike(s){return Array.isArray(s)||isTypedArray(s)}var isPow2$1=function(v){return!(v&v-1||!v)},GL_COMPRESSED_TEXTURE_FORMATS=34467,GL_TEXTURE_2D$1=3553,GL_TEXTURE_CUBE_MAP$1=34067,GL_TEXTURE_CUBE_MAP_POSITIVE_X$1=34069,GL_RGBA$1=6408,GL_ALPHA=6406,GL_RGB=6407,GL_LUMINANCE=6409,GL_LUMINANCE_ALPHA=6410,GL_RGBA4=32854,GL_RGB5_A1=32855,GL_RGB565=36194,GL_UNSIGNED_SHORT_4_4_4_4$1=32819,GL_UNSIGNED_SHORT_5_5_5_1$1=32820,GL_UNSIGNED_SHORT_5_6_5$1=33635,GL_UNSIGNED_INT_24_8_WEBGL$1=34042,GL_DEPTH_COMPONENT=6402,GL_DEPTH_STENCIL=34041,GL_SRGB_EXT=35904,GL_SRGB_ALPHA_EXT=35906,GL_HALF_FLOAT_OES$1=36193,GL_COMPRESSED_RGB_S3TC_DXT1_EXT=33776,GL_COMPRESSED_RGBA_S3TC_DXT1_EXT=33777,GL_COMPRESSED_RGBA_S3TC_DXT3_EXT=33778,GL_COMPRESSED_RGBA_S3TC_DXT5_EXT=33779,GL_COMPRESSED_RGB_ATC_WEBGL=35986,GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=35987,GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=34798,GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840,GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG=35841,GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842,GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=35843,GL_COMPRESSED_RGB_ETC1_WEBGL=36196,GL_UNSIGNED_BYTE$5=5121,GL_UNSIGNED_SHORT$3=5123,GL_UNSIGNED_INT$3=5125,GL_FLOAT$4=5126,GL_TEXTURE_WRAP_S=10242,GL_TEXTURE_WRAP_T=10243,GL_REPEAT=10497,GL_CLAMP_TO_EDGE$1=33071,GL_MIRRORED_REPEAT=33648,GL_TEXTURE_MAG_FILTER=10240,GL_TEXTURE_MIN_FILTER=10241,GL_NEAREST$1=9728,GL_LINEAR=9729,GL_NEAREST_MIPMAP_NEAREST$1=9984,GL_LINEAR_MIPMAP_NEAREST$1=9985,GL_NEAREST_MIPMAP_LINEAR$1=9986,GL_LINEAR_MIPMAP_LINEAR$1=9987,GL_GENERATE_MIPMAP_HINT=33170,GL_DONT_CARE=4352,GL_FASTEST=4353,GL_NICEST=4354,GL_TEXTURE_MAX_ANISOTROPY_EXT=34046,GL_UNPACK_ALIGNMENT=3317,GL_UNPACK_FLIP_Y_WEBGL=37440,GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL=37441,GL_UNPACK_COLORSPACE_CONVERSION_WEBGL=37443,GL_BROWSER_DEFAULT_WEBGL=37444,GL_TEXTURE0$1=33984,MIPMAP_FILTERS=[GL_NEAREST_MIPMAP_NEAREST$1,GL_NEAREST_MIPMAP_LINEAR$1,GL_LINEAR_MIPMAP_NEAREST$1,GL_LINEAR_MIPMAP_LINEAR$1],CHANNELS_FORMAT=[0,GL_LUMINANCE,GL_LUMINANCE_ALPHA,GL_RGB,GL_RGBA$1],FORMAT_CHANNELS={};function objectName(str){return"[object "+str+"]"}FORMAT_CHANNELS[GL_LUMINANCE]=FORMAT_CHANNELS[GL_ALPHA]=FORMAT_CHANNELS[GL_DEPTH_COMPONENT]=1,FORMAT_CHANNELS[GL_DEPTH_STENCIL]=FORMAT_CHANNELS[GL_LUMINANCE_ALPHA]=2,FORMAT_CHANNELS[GL_RGB]=FORMAT_CHANNELS[GL_SRGB_EXT]=3,FORMAT_CHANNELS[GL_RGBA$1]=FORMAT_CHANNELS[GL_SRGB_ALPHA_EXT]=4;var CANVAS_CLASS=objectName("HTMLCanvasElement"),OFFSCREENCANVAS_CLASS=objectName("OffscreenCanvas"),CONTEXT2D_CLASS=objectName("CanvasRenderingContext2D"),BITMAP_CLASS=objectName("ImageBitmap"),IMAGE_CLASS=objectName("HTMLImageElement"),VIDEO_CLASS=objectName("HTMLVideoElement"),PIXEL_CLASSES=Object.keys(arrayTypes).concat([CANVAS_CLASS,OFFSCREENCANVAS_CLASS,CONTEXT2D_CLASS,BITMAP_CLASS,IMAGE_CLASS,VIDEO_CLASS]),TYPE_SIZES=[];TYPE_SIZES[GL_UNSIGNED_BYTE$5]=1,TYPE_SIZES[GL_FLOAT$4]=4,TYPE_SIZES[GL_HALF_FLOAT_OES$1]=2,TYPE_SIZES[GL_UNSIGNED_SHORT$3]=2,TYPE_SIZES[GL_UNSIGNED_INT$3]=4;var FORMAT_SIZES_SPECIAL=[];function isNumericArray(arr){return Array.isArray(arr)&&(0===arr.length||"number"==typeof arr[0])}function isRectArray(arr){return!!Array.isArray(arr)&&!(0===arr.length||!isArrayLike(arr[0]))}function classString(x){return Object.prototype.toString.call(x)}function isCanvasElement(object){return classString(object)===CANVAS_CLASS}function isOffscreenCanvas(object){return classString(object)===OFFSCREENCANVAS_CLASS}function isContext2D(object){return classString(object)===CONTEXT2D_CLASS}function isBitmap(object){return classString(object)===BITMAP_CLASS}function isImageElement(object){return classString(object)===IMAGE_CLASS}function isVideoElement(object){return classString(object)===VIDEO_CLASS}function isPixelData(object){if(!object)return!1;var className=classString(object);return PIXEL_CLASSES.indexOf(className)>=0||isNumericArray(object)||isRectArray(object)||isNDArrayLike(object)}function typedArrayCode$1(data){return 0|arrayTypes[Object.prototype.toString.call(data)]}function convertData(result,data){var n=data.length;switch(result.type){case GL_UNSIGNED_BYTE$5:case GL_UNSIGNED_SHORT$3:case GL_UNSIGNED_INT$3:case GL_FLOAT$4:var converted=pool.allocType(result.type,n);converted.set(data),result.data=converted;break;case GL_HALF_FLOAT_OES$1:result.data=convertToHalfFloat(data);break;default:check$1.raise("unsupported texture type, must specify a typed array")}}function preConvert(image,n){return pool.allocType(image.type===GL_HALF_FLOAT_OES$1?GL_FLOAT$4:image.type,n)}function postConvert(image,data){image.type===GL_HALF_FLOAT_OES$1?(image.data=convertToHalfFloat(data),pool.freeType(data)):image.data=data}function transposeData(image,array,strideX,strideY,strideC,offset){for(var w=image.width,h=image.height,c=image.channels,data=preConvert(image,w*h*c),p=0,i=0;i=1;)total+=s*w*w,w/=2;return total}return s*width*height}function createTextureSet(gl,extensions,limits,reglPoll,contextState,stats,config){var mipmapHint={"don't care":GL_DONT_CARE,"dont care":GL_DONT_CARE,nice:GL_NICEST,fast:GL_FASTEST},wrapModes={repeat:GL_REPEAT,clamp:GL_CLAMP_TO_EDGE$1,mirror:GL_MIRRORED_REPEAT},magFilters={nearest:GL_NEAREST$1,linear:GL_LINEAR},minFilters=extend({mipmap:GL_LINEAR_MIPMAP_LINEAR$1,"nearest mipmap nearest":GL_NEAREST_MIPMAP_NEAREST$1,"linear mipmap nearest":GL_LINEAR_MIPMAP_NEAREST$1,"nearest mipmap linear":GL_NEAREST_MIPMAP_LINEAR$1,"linear mipmap linear":GL_LINEAR_MIPMAP_LINEAR$1},magFilters),colorSpace={none:0,browser:GL_BROWSER_DEFAULT_WEBGL},textureTypes={uint8:GL_UNSIGNED_BYTE$5,rgba4:GL_UNSIGNED_SHORT_4_4_4_4$1,rgb565:GL_UNSIGNED_SHORT_5_6_5$1,"rgb5 a1":GL_UNSIGNED_SHORT_5_5_5_1$1},textureFormats={alpha:GL_ALPHA,luminance:GL_LUMINANCE,"luminance alpha":GL_LUMINANCE_ALPHA,rgb:GL_RGB,rgba:GL_RGBA$1,rgba4:GL_RGBA4,"rgb5 a1":GL_RGB5_A1,rgb565:GL_RGB565},compressedTextureFormats={};extensions.ext_srgb&&(textureFormats.srgb=GL_SRGB_EXT,textureFormats.srgba=GL_SRGB_ALPHA_EXT),extensions.oes_texture_float&&(textureTypes.float32=textureTypes.float=GL_FLOAT$4),extensions.oes_texture_half_float&&(textureTypes.float16=textureTypes["half float"]=GL_HALF_FLOAT_OES$1),extensions.webgl_depth_texture&&(extend(textureFormats,{depth:GL_DEPTH_COMPONENT,"depth stencil":GL_DEPTH_STENCIL}),extend(textureTypes,{uint16:GL_UNSIGNED_SHORT$3,uint32:GL_UNSIGNED_INT$3,"depth stencil":GL_UNSIGNED_INT_24_8_WEBGL$1})),extensions.webgl_compressed_texture_s3tc&&extend(compressedTextureFormats,{"rgb s3tc dxt1":GL_COMPRESSED_RGB_S3TC_DXT1_EXT,"rgba s3tc dxt1":GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,"rgba s3tc dxt3":GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,"rgba s3tc dxt5":GL_COMPRESSED_RGBA_S3TC_DXT5_EXT}),extensions.webgl_compressed_texture_atc&&extend(compressedTextureFormats,{"rgb atc":GL_COMPRESSED_RGB_ATC_WEBGL,"rgba atc explicit alpha":GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL,"rgba atc interpolated alpha":GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL}),extensions.webgl_compressed_texture_pvrtc&&extend(compressedTextureFormats,{"rgb pvrtc 4bppv1":GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG,"rgb pvrtc 2bppv1":GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG,"rgba pvrtc 4bppv1":GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG,"rgba pvrtc 2bppv1":GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}),extensions.webgl_compressed_texture_etc1&&(compressedTextureFormats["rgb etc1"]=GL_COMPRESSED_RGB_ETC1_WEBGL);var supportedCompressedFormats=Array.prototype.slice.call(gl.getParameter(GL_COMPRESSED_TEXTURE_FORMATS));Object.keys(compressedTextureFormats).forEach((function(name){var format=compressedTextureFormats[name];supportedCompressedFormats.indexOf(format)>=0&&(textureFormats[name]=format)}));var supportedFormats=Object.keys(textureFormats);limits.textureFormats=supportedFormats;var textureFormatsInvert=[];Object.keys(textureFormats).forEach((function(key){var val=textureFormats[key];textureFormatsInvert[val]=key}));var textureTypesInvert=[];Object.keys(textureTypes).forEach((function(key){var val=textureTypes[key];textureTypesInvert[val]=key}));var magFiltersInvert=[];Object.keys(magFilters).forEach((function(key){var val=magFilters[key];magFiltersInvert[val]=key}));var minFiltersInvert=[];Object.keys(minFilters).forEach((function(key){var val=minFilters[key];minFiltersInvert[val]=key}));var wrapModesInvert=[];Object.keys(wrapModes).forEach((function(key){var val=wrapModes[key];wrapModesInvert[val]=key}));var colorFormats=supportedFormats.reduce((function(color,key){var glenum=textureFormats[key];return glenum===GL_LUMINANCE||glenum===GL_ALPHA||glenum===GL_LUMINANCE||glenum===GL_LUMINANCE_ALPHA||glenum===GL_DEPTH_COMPONENT||glenum===GL_DEPTH_STENCIL||extensions.ext_srgb&&(glenum===GL_SRGB_EXT||glenum===GL_SRGB_ALPHA_EXT)?color[glenum]=glenum:glenum===GL_RGB5_A1||key.indexOf("rgba")>=0?color[glenum]=GL_RGBA$1:color[glenum]=GL_RGB,color}),{});function TexFlags(){this.internalformat=GL_RGBA$1,this.format=GL_RGBA$1,this.type=GL_UNSIGNED_BYTE$5,this.compressed=!1,this.premultiplyAlpha=!1,this.flipY=!1,this.unpackAlignment=1,this.colorSpace=GL_BROWSER_DEFAULT_WEBGL,this.width=0,this.height=0,this.channels=0}function copyFlags(result,other){result.internalformat=other.internalformat,result.format=other.format,result.type=other.type,result.compressed=other.compressed,result.premultiplyAlpha=other.premultiplyAlpha,result.flipY=other.flipY,result.unpackAlignment=other.unpackAlignment,result.colorSpace=other.colorSpace,result.width=other.width,result.height=other.height,result.channels=other.channels}function parseFlags(flags,options){if("object"==typeof options&&options){if("premultiplyAlpha"in options&&(check$1.type(options.premultiplyAlpha,"boolean","invalid premultiplyAlpha"),flags.premultiplyAlpha=options.premultiplyAlpha),"flipY"in options&&(check$1.type(options.flipY,"boolean","invalid texture flip"),flags.flipY=options.flipY),"alignment"in options&&(check$1.oneOf(options.alignment,[1,2,4,8],"invalid texture unpack alignment"),flags.unpackAlignment=options.alignment),"colorSpace"in options&&(check$1.parameter(options.colorSpace,colorSpace,"invalid colorSpace"),flags.colorSpace=colorSpace[options.colorSpace]),"type"in options){var type=options.type;check$1(extensions.oes_texture_float||!("float"===type||"float32"===type),"you must enable the OES_texture_float extension in order to use floating point textures."),check$1(extensions.oes_texture_half_float||!("half float"===type||"float16"===type),"you must enable the OES_texture_half_float extension in order to use 16-bit floating point textures."),check$1(extensions.webgl_depth_texture||!("uint16"===type||"uint32"===type||"depth stencil"===type),"you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures."),check$1.parameter(type,textureTypes,"invalid texture type"),flags.type=textureTypes[type]}var w=flags.width,h=flags.height,c=flags.channels,hasChannels=!1;"shape"in options?(check$1(Array.isArray(options.shape)&&options.shape.length>=2,"shape must be an array"),w=options.shape[0],h=options.shape[1],3===options.shape.length&&(c=options.shape[2],check$1(c>0&&c<=4,"invalid number of channels"),hasChannels=!0),check$1(w>=0&&w<=limits.maxTextureSize,"invalid width"),check$1(h>=0&&h<=limits.maxTextureSize,"invalid height")):("radius"in options&&(w=h=options.radius,check$1(w>=0&&w<=limits.maxTextureSize,"invalid radius")),"width"in options&&(w=options.width,check$1(w>=0&&w<=limits.maxTextureSize,"invalid width")),"height"in options&&(h=options.height,check$1(h>=0&&h<=limits.maxTextureSize,"invalid height")),"channels"in options&&(c=options.channels,check$1(c>0&&c<=4,"invalid number of channels"),hasChannels=!0)),flags.width=0|w,flags.height=0|h,flags.channels=0|c;var hasFormat=!1;if("format"in options){var formatStr=options.format;check$1(extensions.webgl_depth_texture||!("depth"===formatStr||"depth stencil"===formatStr),"you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures."),check$1.parameter(formatStr,textureFormats,"invalid texture format");var internalformat=flags.internalformat=textureFormats[formatStr];flags.format=colorFormats[internalformat],formatStr in textureTypes&&("type"in options||(flags.type=textureTypes[formatStr])),formatStr in compressedTextureFormats&&(flags.compressed=!0),hasFormat=!0}!hasChannels&&hasFormat?flags.channels=FORMAT_CHANNELS[flags.format]:hasChannels&&!hasFormat?flags.channels!==CHANNELS_FORMAT[flags.format]&&(flags.format=flags.internalformat=CHANNELS_FORMAT[flags.channels]):hasFormat&&hasChannels&&check$1(flags.channels===FORMAT_CHANNELS[flags.format],"number of channels inconsistent with specified format")}}function setFlags(flags){gl.pixelStorei(GL_UNPACK_FLIP_Y_WEBGL,flags.flipY),gl.pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL,flags.premultiplyAlpha),gl.pixelStorei(GL_UNPACK_COLORSPACE_CONVERSION_WEBGL,flags.colorSpace),gl.pixelStorei(GL_UNPACK_ALIGNMENT,flags.unpackAlignment)}function TexImage(){TexFlags.call(this),this.xOffset=0,this.yOffset=0,this.data=null,this.needsFree=!1,this.element=null,this.needsCopy=!1}function parseImage(image,options){var data=null;if(isPixelData(options)?data=options:options&&(check$1.type(options,"object","invalid pixel data type"),parseFlags(image,options),"x"in options&&(image.xOffset=0|options.x),"y"in options&&(image.yOffset=0|options.y),isPixelData(options.data)&&(data=options.data)),check$1(!image.compressed||data instanceof Uint8Array,"compressed texture data must be stored in a uint8array"),options.copy){check$1(!data,"can not specify copy and data field for the same texture");var viewW=contextState.viewportWidth,viewH=contextState.viewportHeight;image.width=image.width||viewW-image.xOffset,image.height=image.height||viewH-image.yOffset,image.needsCopy=!0,check$1(image.xOffset>=0&&image.xOffset=0&&image.yOffset0&&image.width<=viewW&&image.height>0&&image.height<=viewH,"copy texture read out of bounds")}else if(data){if(isTypedArray(data))image.channels=image.channels||4,image.data=data,"type"in options||image.type!==GL_UNSIGNED_BYTE$5||(image.type=typedArrayCode$1(data));else if(isNumericArray(data))image.channels=image.channels||4,convertData(image,data),image.alignment=1,image.needsFree=!0;else if(isNDArrayLike(data)){var array=data.data;Array.isArray(array)||image.type!==GL_UNSIGNED_BYTE$5||(image.type=typedArrayCode$1(array));var shapeX,shapeY,shapeC,strideX,strideY,strideC,shape=data.shape,stride=data.stride;3===shape.length?(shapeC=shape[2],strideC=stride[2]):(check$1(2===shape.length,"invalid ndarray pixel data, must be 2 or 3D"),shapeC=1,strideC=1),shapeX=shape[0],shapeY=shape[1],strideX=stride[0],strideY=stride[1],image.alignment=1,image.width=shapeX,image.height=shapeY,image.channels=shapeC,image.format=image.internalformat=CHANNELS_FORMAT[shapeC],image.needsFree=!0,transposeData(image,array,strideX,strideY,strideC,data.offset)}else if(isCanvasElement(data)||isOffscreenCanvas(data)||isContext2D(data))isCanvasElement(data)||isOffscreenCanvas(data)?image.element=data:image.element=data.canvas,image.width=image.element.width,image.height=image.element.height,image.channels=4;else if(isBitmap(data))image.element=data,image.width=data.width,image.height=data.height,image.channels=4;else if(isImageElement(data))image.element=data,image.width=data.naturalWidth,image.height=data.naturalHeight,image.channels=4;else if(isVideoElement(data))image.element=data,image.width=data.videoWidth,image.height=data.videoHeight,image.channels=4;else if(isRectArray(data)){var w=image.width||data[0].length,h=image.height||data.length,c=image.channels;c=isArrayLike(data[0][0])?c||data[0][0].length:c||1;for(var arrayShape=flattenUtils.shape(data),n=1,dd=0;dd=0,"oes_texture_float extension not enabled"):image.type===GL_HALF_FLOAT_OES$1&&check$1(limits.extensions.indexOf("oes_texture_half_float")>=0,"oes_texture_half_float extension not enabled")}function setImage(info,target,miplevel){var element=info.element,data=info.data,internalformat=info.internalformat,format=info.format,type=info.type,width=info.width,height=info.height;setFlags(info),element?gl.texImage2D(target,miplevel,format,format,type,element):info.compressed?gl.compressedTexImage2D(target,miplevel,internalformat,width,height,0,data):info.needsCopy?(reglPoll(),gl.copyTexImage2D(target,miplevel,format,info.xOffset,info.yOffset,width,height,0)):gl.texImage2D(target,miplevel,format,width,height,0,format,type,data||null)}function setSubImage(info,target,x,y,miplevel){var element=info.element,data=info.data,internalformat=info.internalformat,format=info.format,type=info.type,width=info.width,height=info.height;setFlags(info),element?gl.texSubImage2D(target,miplevel,x,y,format,type,element):info.compressed?gl.compressedTexSubImage2D(target,miplevel,x,y,internalformat,width,height,data):info.needsCopy?(reglPoll(),gl.copyTexSubImage2D(target,miplevel,x,y,info.xOffset,info.yOffset,width,height)):gl.texSubImage2D(target,miplevel,x,y,width,height,format,type,data)}var imagePool=[];function allocImage(){return imagePool.pop()||new TexImage}function freeImage(image){image.needsFree&&pool.freeType(image.data),TexImage.call(image),imagePool.push(image)}function MipMap(){TexFlags.call(this),this.genMipmaps=!1,this.mipmapHint=GL_DONT_CARE,this.mipmask=0,this.images=Array(16)}function parseMipMapFromShape(mipmap,width,height){var img=mipmap.images[0]=allocImage();mipmap.mipmask=1,img.width=mipmap.width=width,img.height=mipmap.height=height,img.channels=mipmap.channels=4}function parseMipMapFromObject(mipmap,options){var imgData=null;if(isPixelData(options))copyFlags(imgData=mipmap.images[0]=allocImage(),mipmap),parseImage(imgData,options),mipmap.mipmask=1;else if(parseFlags(mipmap,options),Array.isArray(options.mipmap))for(var mipData=options.mipmap,i=0;i>=i,imgData.height>>=i,parseImage(imgData,mipData[i]),mipmap.mipmask|=1<=0&&!("faces"in options)&&(info.genMipmaps=!0)}if("mag"in options){var magFilter=options.mag;check$1.parameter(magFilter,magFilters),info.magFilter=magFilters[magFilter]}var wrapS=info.wrapS,wrapT=info.wrapT;if("wrap"in options){var wrap=options.wrap;"string"==typeof wrap?(check$1.parameter(wrap,wrapModes),wrapS=wrapT=wrapModes[wrap]):Array.isArray(wrap)&&(check$1.parameter(wrap[0],wrapModes),check$1.parameter(wrap[1],wrapModes),wrapS=wrapModes[wrap[0]],wrapT=wrapModes[wrap[1]])}else{if("wrapS"in options){var optWrapS=options.wrapS;check$1.parameter(optWrapS,wrapModes),wrapS=wrapModes[optWrapS]}if("wrapT"in options){var optWrapT=options.wrapT;check$1.parameter(optWrapT,wrapModes),wrapT=wrapModes[optWrapT]}}if(info.wrapS=wrapS,info.wrapT=wrapT,"anisotropic"in options){var anisotropic=options.anisotropic;check$1("number"==typeof anisotropic&&anisotropic>=1&&anisotropic<=limits.maxAnisotropic,"aniso samples must be between 1 and "),info.anisotropic=options.anisotropic}if("mipmap"in options){var hasMipMap=!1;switch(typeof options.mipmap){case"string":check$1.parameter(options.mipmap,mipmapHint,"invalid mipmap hint"),info.mipmapHint=mipmapHint[options.mipmap],info.genMipmaps=!0,hasMipMap=!0;break;case"boolean":hasMipMap=info.genMipmaps=options.mipmap;break;case"object":check$1(Array.isArray(options.mipmap),"invalid mipmap type"),info.genMipmaps=!1,hasMipMap=!0;break;default:check$1.raise("invalid mipmap type")}hasMipMap&&!("min"in options)&&(info.minFilter=GL_NEAREST_MIPMAP_NEAREST$1)}}function setTexInfo(info,target){gl.texParameteri(target,GL_TEXTURE_MIN_FILTER,info.minFilter),gl.texParameteri(target,GL_TEXTURE_MAG_FILTER,info.magFilter),gl.texParameteri(target,GL_TEXTURE_WRAP_S,info.wrapS),gl.texParameteri(target,GL_TEXTURE_WRAP_T,info.wrapT),extensions.ext_texture_filter_anisotropic&&gl.texParameteri(target,GL_TEXTURE_MAX_ANISOTROPY_EXT,info.anisotropic),info.genMipmaps&&(gl.hint(GL_GENERATE_MIPMAP_HINT,info.mipmapHint),gl.generateMipmap(target))}var textureCount=0,textureSet={},numTexUnits=limits.maxTextureUnits,textureUnits=Array(numTexUnits).map((function(){return null}));function REGLTexture(target){TexFlags.call(this),this.mipmask=0,this.internalformat=GL_RGBA$1,this.id=textureCount++,this.refCount=1,this.target=target,this.texture=gl.createTexture(),this.unit=-1,this.bindCount=0,this.texInfo=new TexInfo,config.profile&&(this.stats={size:0})}function tempBind(texture){gl.activeTexture(GL_TEXTURE0$1),gl.bindTexture(texture.target,texture.texture)}function tempRestore(){var prev=textureUnits[0];prev?gl.bindTexture(prev.target,prev.texture):gl.bindTexture(GL_TEXTURE_2D$1,null)}function destroy(texture){var handle=texture.texture;check$1(handle,"must not double destroy texture");var unit=texture.unit,target=texture.target;unit>=0&&(gl.activeTexture(GL_TEXTURE0$1+unit),gl.bindTexture(target,null),textureUnits[unit]=null),gl.deleteTexture(handle),texture.texture=null,texture.params=null,texture.pixels=null,texture.refCount=0,delete textureSet[texture.id],stats.textureCount--}function createTexture2D(a,b){var texture=new REGLTexture(GL_TEXTURE_2D$1);function reglTexture2D(a,b){var texInfo=texture.texInfo;TexInfo.call(texInfo);var mipData=allocMipMap();return"number"==typeof a?parseMipMapFromShape(mipData,0|a,"number"==typeof b?0|b:0|a):a?(check$1.type(a,"object","invalid arguments to regl.texture"),parseTexInfo(texInfo,a),parseMipMapFromObject(mipData,a)):parseMipMapFromShape(mipData,1,1),texInfo.genMipmaps&&(mipData.mipmask=(mipData.width<<1)-1),texture.mipmask=mipData.mipmask,copyFlags(texture,mipData),check$1.texture2D(texInfo,mipData,limits),texture.internalformat=mipData.internalformat,reglTexture2D.width=mipData.width,reglTexture2D.height=mipData.height,tempBind(texture),setMipMap(mipData,GL_TEXTURE_2D$1),setTexInfo(texInfo,GL_TEXTURE_2D$1),tempRestore(),freeMipMap(mipData),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,mipData.width,mipData.height,texInfo.genMipmaps,!1)),reglTexture2D.format=textureFormatsInvert[texture.internalformat],reglTexture2D.type=textureTypesInvert[texture.type],reglTexture2D.mag=magFiltersInvert[texInfo.magFilter],reglTexture2D.min=minFiltersInvert[texInfo.minFilter],reglTexture2D.wrapS=wrapModesInvert[texInfo.wrapS],reglTexture2D.wrapT=wrapModesInvert[texInfo.wrapT],reglTexture2D}function subimage(image,x_,y_,level_){check$1(!!image,"must specify image data");var x=0|x_,y=0|y_,level=0|level_,imageData=allocImage();return copyFlags(imageData,texture),imageData.width=0,imageData.height=0,parseImage(imageData,image),imageData.width=imageData.width||(texture.width>>level)-x,imageData.height=imageData.height||(texture.height>>level)-y,check$1(texture.type===imageData.type&&texture.format===imageData.format&&texture.internalformat===imageData.internalformat,"incompatible format for texture.subimage"),check$1(x>=0&&y>=0&&x+imageData.width<=texture.width&&y+imageData.height<=texture.height,"texture.subimage write out of bounds"),check$1(texture.mipmask&1<>i;++i){var _w=w>>i,_h=h>>i;if(!_w||!_h)break;gl.texImage2D(GL_TEXTURE_2D$1,i,texture.format,_w,_h,0,texture.format,texture.type,null)}return tempRestore(),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,w,h,!1,!1)),reglTexture2D}return textureSet[texture.id]=texture,stats.textureCount++,reglTexture2D(a,b),reglTexture2D.subimage=subimage,reglTexture2D.resize=resize,reglTexture2D._reglType="texture2d",reglTexture2D._texture=texture,config.profile&&(reglTexture2D.stats=texture.stats),reglTexture2D.destroy=function(){texture.decRef()},reglTexture2D}function createTextureCube(a0,a1,a2,a3,a4,a5){var texture=new REGLTexture(GL_TEXTURE_CUBE_MAP$1);textureSet[texture.id]=texture,stats.cubeCount++;var faces=new Array(6);function reglTextureCube(a0,a1,a2,a3,a4,a5){var i,texInfo=texture.texInfo;for(TexInfo.call(texInfo),i=0;i<6;++i)faces[i]=allocMipMap();if("number"!=typeof a0&&a0)if("object"==typeof a0)if(a1)parseMipMapFromObject(faces[0],a0),parseMipMapFromObject(faces[1],a1),parseMipMapFromObject(faces[2],a2),parseMipMapFromObject(faces[3],a3),parseMipMapFromObject(faces[4],a4),parseMipMapFromObject(faces[5],a5);else if(parseTexInfo(texInfo,a0),parseFlags(texture,a0),"faces"in a0){var faceInput=a0.faces;for(check$1(Array.isArray(faceInput)&&6===faceInput.length,"cube faces must be a length 6 array"),i=0;i<6;++i)check$1("object"==typeof faceInput[i]&&!!faceInput[i],"invalid input for cube map face"),copyFlags(faces[i],texture),parseMipMapFromObject(faces[i],faceInput[i])}else for(i=0;i<6;++i)parseMipMapFromObject(faces[i],a0);else check$1.raise("invalid arguments to cube map");else{var s=0|a0||1;for(i=0;i<6;++i)parseMipMapFromShape(faces[i],s,s)}for(copyFlags(texture,faces[0]),check$1.optional((function(){limits.npotTextureCube||check$1(isPow2$1(texture.width)&&isPow2$1(texture.height),"your browser does not support non power or two texture dimensions")})),texInfo.genMipmaps?texture.mipmask=(faces[0].width<<1)-1:texture.mipmask=faces[0].mipmask,check$1.textureCube(texture,texInfo,faces,limits),texture.internalformat=faces[0].internalformat,reglTextureCube.width=faces[0].width,reglTextureCube.height=faces[0].height,tempBind(texture),i=0;i<6;++i)setMipMap(faces[i],GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+i);for(setTexInfo(texInfo,GL_TEXTURE_CUBE_MAP$1),tempRestore(),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,reglTextureCube.width,reglTextureCube.height,texInfo.genMipmaps,!0)),reglTextureCube.format=textureFormatsInvert[texture.internalformat],reglTextureCube.type=textureTypesInvert[texture.type],reglTextureCube.mag=magFiltersInvert[texInfo.magFilter],reglTextureCube.min=minFiltersInvert[texInfo.minFilter],reglTextureCube.wrapS=wrapModesInvert[texInfo.wrapS],reglTextureCube.wrapT=wrapModesInvert[texInfo.wrapT],i=0;i<6;++i)freeMipMap(faces[i]);return reglTextureCube}function subimage(face,image,x_,y_,level_){check$1(!!image,"must specify image data"),check$1("number"==typeof face&&face===(0|face)&&face>=0&&face<6,"invalid face");var x=0|x_,y=0|y_,level=0|level_,imageData=allocImage();return copyFlags(imageData,texture),imageData.width=0,imageData.height=0,parseImage(imageData,image),imageData.width=imageData.width||(texture.width>>level)-x,imageData.height=imageData.height||(texture.height>>level)-y,check$1(texture.type===imageData.type&&texture.format===imageData.format&&texture.internalformat===imageData.internalformat,"incompatible format for texture.subimage"),check$1(x>=0&&y>=0&&x+imageData.width<=texture.width&&y+imageData.height<=texture.height,"texture.subimage write out of bounds"),check$1(texture.mipmask&1<>j;++j)gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+i,j,texture.format,radius>>j,radius>>j,0,texture.format,texture.type,null);return tempRestore(),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,reglTextureCube.width,reglTextureCube.height,!1,!0)),reglTextureCube}}return reglTextureCube(a0,a1,a2,a3,a4,a5),reglTextureCube.subimage=subimage,reglTextureCube.resize=resize,reglTextureCube._reglType="textureCube",reglTextureCube._texture=texture,config.profile&&(reglTextureCube.stats=texture.stats),reglTextureCube.destroy=function(){texture.decRef()},reglTextureCube}function destroyTextures(){for(var i=0;i>i,texture.height>>i,0,texture.internalformat,texture.type,null);else for(var j=0;j<6;++j)gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+j,i,texture.internalformat,texture.width>>i,texture.height>>i,0,texture.internalformat,texture.type,null);setTexInfo(texture.texInfo,texture.target)}))}function refreshTextures(){for(var i=0;i0)continue;other.unit=-1}textureUnits[i]=texture,unit=i;break}unit>=numTexUnits&&check$1.raise("insufficient number of texture units"),config.profile&&stats.maxTextureUnits=2,"invalid renderbuffer shape"),w=0|shape[0],h=0|shape[1]}else"radius"in options&&(w=h=0|options.radius),"width"in options&&(w=0|options.width),"height"in options&&(h=0|options.height);"format"in options&&(check$1.parameter(options.format,formatTypes,"invalid renderbuffer format"),format=formatTypes[options.format])}else"number"==typeof a?(w=0|a,h="number"==typeof b?0|b:w):a?check$1.raise("invalid arguments to renderbuffer constructor"):w=h=1;if(check$1(w>0&&h>0&&w<=limits.maxRenderbufferSize&&h<=limits.maxRenderbufferSize,"invalid renderbuffer size"),w!==renderbuffer.width||h!==renderbuffer.height||format!==renderbuffer.format)return reglRenderbuffer.width=renderbuffer.width=w,reglRenderbuffer.height=renderbuffer.height=h,renderbuffer.format=format,gl.bindRenderbuffer(GL_RENDERBUFFER,renderbuffer.renderbuffer),gl.renderbufferStorage(GL_RENDERBUFFER,format,w,h),check$1(0===gl.getError(),"invalid render buffer format"),config.profile&&(renderbuffer.stats.size=getRenderbufferSize(renderbuffer.format,renderbuffer.width,renderbuffer.height)),reglRenderbuffer.format=formatTypesInvert[renderbuffer.format],reglRenderbuffer}function resize(w_,h_){var w=0|w_,h=0|h_||w;return w===renderbuffer.width&&h===renderbuffer.height||(check$1(w>0&&h>0&&w<=limits.maxRenderbufferSize&&h<=limits.maxRenderbufferSize,"invalid renderbuffer size"),reglRenderbuffer.width=renderbuffer.width=w,reglRenderbuffer.height=renderbuffer.height=h,gl.bindRenderbuffer(GL_RENDERBUFFER,renderbuffer.renderbuffer),gl.renderbufferStorage(GL_RENDERBUFFER,renderbuffer.format,w,h),check$1(0===gl.getError(),"invalid render buffer format"),config.profile&&(renderbuffer.stats.size=getRenderbufferSize(renderbuffer.format,renderbuffer.width,renderbuffer.height))),reglRenderbuffer}return renderbufferSet[renderbuffer.id]=renderbuffer,stats.renderbufferCount++,reglRenderbuffer(a,b),reglRenderbuffer.resize=resize,reglRenderbuffer._reglType="renderbuffer",reglRenderbuffer._renderbuffer=renderbuffer,config.profile&&(reglRenderbuffer.stats=renderbuffer.stats),reglRenderbuffer.destroy=function(){renderbuffer.decRef()},reglRenderbuffer}function restoreRenderbuffers(){values(renderbufferSet).forEach((function(rb){rb.renderbuffer=gl.createRenderbuffer(),gl.bindRenderbuffer(GL_RENDERBUFFER,rb.renderbuffer),gl.renderbufferStorage(GL_RENDERBUFFER,rb.format,rb.width,rb.height)})),gl.bindRenderbuffer(GL_RENDERBUFFER,null)}return REGLRenderbuffer.prototype.decRef=function(){--this.refCount<=0&&destroy(this)},config.profile&&(stats.getTotalRenderbufferSize=function(){var total=0;return Object.keys(renderbufferSet).forEach((function(key){total+=renderbufferSet[key].stats.size})),total}),{create:createRenderbuffer,clear:function(){values(renderbufferSet).forEach(destroy)},restore:restoreRenderbuffers}},GL_FRAMEBUFFER$1=36160,GL_RENDERBUFFER$1=36161,GL_TEXTURE_2D$2=3553,GL_TEXTURE_CUBE_MAP_POSITIVE_X$2=34069,GL_COLOR_ATTACHMENT0$1=36064,GL_DEPTH_ATTACHMENT=36096,GL_STENCIL_ATTACHMENT=36128,GL_DEPTH_STENCIL_ATTACHMENT=33306,GL_FRAMEBUFFER_COMPLETE$1=36053,GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT=36054,GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT=36055,GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS=36057,GL_FRAMEBUFFER_UNSUPPORTED=36061,GL_HALF_FLOAT_OES$2=36193,GL_UNSIGNED_BYTE$6=5121,GL_FLOAT$5=5126,GL_RGB$1=6407,GL_RGBA$2=6408,GL_DEPTH_COMPONENT$1=6402,colorTextureFormatEnums=[GL_RGB$1,GL_RGBA$2],textureFormatChannels=[];textureFormatChannels[GL_RGBA$2]=4,textureFormatChannels[GL_RGB$1]=3;var textureTypeSizes=[];textureTypeSizes[GL_UNSIGNED_BYTE$6]=1,textureTypeSizes[GL_FLOAT$5]=4,textureTypeSizes[GL_HALF_FLOAT_OES$2]=2;var GL_DEPTH_COMPONENT16$1=33189,GL_STENCIL_INDEX8$1=36168,GL_DEPTH_STENCIL$2=34041,colorRenderbufferFormatEnums=[32854,32855,36194,35907,34842,34843,34836],statusCode={};function wrapFBOState(gl,extensions,limits,textureState,renderbufferState,stats){var framebufferState={cur:null,next:null,dirty:!1,setFBO:null},colorTextureFormats=["rgba"],colorRenderbufferFormats=["rgba4","rgb565","rgb5 a1"];extensions.ext_srgb&&colorRenderbufferFormats.push("srgba"),extensions.ext_color_buffer_half_float&&colorRenderbufferFormats.push("rgba16f","rgb16f"),extensions.webgl_color_buffer_float&&colorRenderbufferFormats.push("rgba32f");var colorTypes=["uint8"];function FramebufferAttachment(target,texture,renderbuffer){this.target=target,this.texture=texture,this.renderbuffer=renderbuffer;var w=0,h=0;texture?(w=texture.width,h=texture.height):renderbuffer&&(w=renderbuffer.width,h=renderbuffer.height),this.width=w,this.height=h}function decRef(attachment){attachment&&(attachment.texture&&attachment.texture._texture.decRef(),attachment.renderbuffer&&attachment.renderbuffer._renderbuffer.decRef())}function incRefAndCheckShape(attachment,width,height){if(attachment)if(attachment.texture){var texture=attachment.texture._texture,tw=Math.max(1,texture.width),th=Math.max(1,texture.height);check$1(tw===width&&th===height,"inconsistent width/height for supplied texture"),texture.refCount+=1}else{var renderbuffer=attachment.renderbuffer._renderbuffer;check$1(renderbuffer.width===width&&renderbuffer.height===height,"inconsistent width/height for renderbuffer"),renderbuffer.refCount+=1}}function attach(location,attachment){attachment&&(attachment.texture?gl.framebufferTexture2D(GL_FRAMEBUFFER$1,location,attachment.target,attachment.texture._texture.texture,0):gl.framebufferRenderbuffer(GL_FRAMEBUFFER$1,location,GL_RENDERBUFFER$1,attachment.renderbuffer._renderbuffer.renderbuffer))}function parseAttachment(attachment){var target=GL_TEXTURE_2D$2,texture=null,renderbuffer=null,data=attachment;"object"==typeof attachment&&(data=attachment.data,"target"in attachment&&(target=0|attachment.target)),check$1.type(data,"function","invalid attachment data");var type=data._reglType;return"texture2d"===type?(texture=data,check$1(target===GL_TEXTURE_2D$2)):"textureCube"===type?(texture=data,check$1(target>=GL_TEXTURE_CUBE_MAP_POSITIVE_X$2&&target=2,"invalid shape for framebuffer"),width=shape[0],height=shape[1]}else"radius"in options&&(width=height=options.radius),"width"in options&&(width=options.width),"height"in options&&(height=options.height);("color"in options||"colors"in options)&&(colorBuffer=options.color||options.colors,Array.isArray(colorBuffer)&&check$1(1===colorBuffer.length||extensions.webgl_draw_buffers,"multiple render targets not supported")),colorBuffer||("colorCount"in options&&(colorCount=0|options.colorCount,check$1(colorCount>0,"invalid color buffer count")),"colorTexture"in options&&(colorTexture=!!options.colorTexture,colorFormat="rgba4"),"colorType"in options&&(colorType=options.colorType,colorTexture?(check$1(extensions.oes_texture_float||!("float"===colorType||"float32"===colorType),"you must enable OES_texture_float in order to use floating point framebuffer objects"),check$1(extensions.oes_texture_half_float||!("half float"===colorType||"float16"===colorType),"you must enable OES_texture_half_float in order to use 16-bit floating point framebuffer objects")):"half float"===colorType||"float16"===colorType?(check$1(extensions.ext_color_buffer_half_float,"you must enable EXT_color_buffer_half_float to use 16-bit render buffers"),colorFormat="rgba16f"):"float"!==colorType&&"float32"!==colorType||(check$1(extensions.webgl_color_buffer_float,"you must enable WEBGL_color_buffer_float in order to use 32-bit floating point renderbuffers"),colorFormat="rgba32f"),check$1.oneOf(colorType,colorTypes,"invalid color type")),"colorFormat"in options&&(colorFormat=options.colorFormat,colorTextureFormats.indexOf(colorFormat)>=0?colorTexture=!0:colorRenderbufferFormats.indexOf(colorFormat)>=0?colorTexture=!1:check$1.optional((function(){colorTexture?check$1.oneOf(options.colorFormat,colorTextureFormats,"invalid color format for texture"):check$1.oneOf(options.colorFormat,colorRenderbufferFormats,"invalid color format for renderbuffer")})))),("depthTexture"in options||"depthStencilTexture"in options)&&(depthStencilTexture=!(!options.depthTexture&&!options.depthStencilTexture),check$1(!depthStencilTexture||extensions.webgl_depth_texture,"webgl_depth_texture extension not supported")),"depth"in options&&("boolean"==typeof options.depth?needsDepth=options.depth:(depthBuffer=options.depth,needsStencil=!1)),"stencil"in options&&("boolean"==typeof options.stencil?needsStencil=options.stencil:(stencilBuffer=options.stencil,needsDepth=!1)),"depthStencil"in options&&("boolean"==typeof options.depthStencil?needsDepth=needsStencil=options.depthStencil:(depthStencilBuffer=options.depthStencil,needsDepth=!1,needsStencil=!1))}else width=height=1;var colorAttachments=null,depthAttachment=null,stencilAttachment=null,depthStencilAttachment=null;if(Array.isArray(colorBuffer))colorAttachments=colorBuffer.map(parseAttachment);else if(colorBuffer)colorAttachments=[parseAttachment(colorBuffer)];else for(colorAttachments=new Array(colorCount),i=0;i=0||colorAttachments[i].renderbuffer&&colorRenderbufferFormatEnums.indexOf(colorAttachments[i].renderbuffer._renderbuffer.format)>=0,"framebuffer color attachment "+i+" is invalid"),colorAttachments[i]&&colorAttachments[i].texture){var colorAttachmentSize=textureFormatChannels[colorAttachments[i].texture._texture.format]*textureTypeSizes[colorAttachments[i].texture._texture.type];null===commonColorAttachmentSize?commonColorAttachmentSize=colorAttachmentSize:check$1(commonColorAttachmentSize===colorAttachmentSize,"all color attachments much have the same number of bits per pixel.")}return incRefAndCheckShape(depthAttachment,width,height),check$1(!depthAttachment||depthAttachment.texture&&depthAttachment.texture._texture.format===GL_DEPTH_COMPONENT$1||depthAttachment.renderbuffer&&depthAttachment.renderbuffer._renderbuffer.format===GL_DEPTH_COMPONENT16$1,"invalid depth attachment for framebuffer object"),incRefAndCheckShape(stencilAttachment,width,height),check$1(!stencilAttachment||stencilAttachment.renderbuffer&&stencilAttachment.renderbuffer._renderbuffer.format===GL_STENCIL_INDEX8$1,"invalid stencil attachment for framebuffer object"),incRefAndCheckShape(depthStencilAttachment,width,height),check$1(!depthStencilAttachment||depthStencilAttachment.texture&&depthStencilAttachment.texture._texture.format===GL_DEPTH_STENCIL$2||depthStencilAttachment.renderbuffer&&depthStencilAttachment.renderbuffer._renderbuffer.format===GL_DEPTH_STENCIL$2,"invalid depth-stencil attachment for framebuffer object"),decFBORefs(framebuffer),framebuffer.width=width,framebuffer.height=height,framebuffer.colorAttachments=colorAttachments,framebuffer.depthAttachment=depthAttachment,framebuffer.stencilAttachment=stencilAttachment,framebuffer.depthStencilAttachment=depthStencilAttachment,reglFramebuffer.color=colorAttachments.map(unwrapAttachment),reglFramebuffer.depth=unwrapAttachment(depthAttachment),reglFramebuffer.stencil=unwrapAttachment(stencilAttachment),reglFramebuffer.depthStencil=unwrapAttachment(depthStencilAttachment),reglFramebuffer.width=framebuffer.width,reglFramebuffer.height=framebuffer.height,updateFramebuffer(framebuffer),reglFramebuffer}function resize(w_,h_){check$1(framebufferState.next!==framebuffer,"can not resize a framebuffer which is currently in use");var w=Math.max(0|w_,1),h=Math.max(0|h_||w,1);if(w===framebuffer.width&&h===framebuffer.height)return reglFramebuffer;for(var colorAttachments=framebuffer.colorAttachments,i=0;i=2,"invalid shape for framebuffer"),check$1(shape[0]===shape[1],"cube framebuffer must be square"),radius=shape[0]}else"radius"in options&&(radius=0|options.radius),"width"in options?(radius=0|options.width,"height"in options&&check$1(options.height===radius,"must be square")):"height"in options&&(radius=0|options.height);("color"in options||"colors"in options)&&(colorBuffer=options.color||options.colors,Array.isArray(colorBuffer)&&check$1(1===colorBuffer.length||extensions.webgl_draw_buffers,"multiple render targets not supported")),colorBuffer||("colorCount"in options&&(colorCount=0|options.colorCount,check$1(colorCount>0,"invalid color buffer count")),"colorType"in options&&(check$1.oneOf(options.colorType,colorTypes,"invalid color type"),colorType=options.colorType),"colorFormat"in options&&(colorFormat=options.colorFormat,check$1.oneOf(options.colorFormat,colorTextureFormats,"invalid color format for texture"))),"depth"in options&&(params.depth=options.depth),"stencil"in options&&(params.stencil=options.stencil),"depthStencil"in options&&(params.depthStencil=options.depthStencil)}else radius=1;if(colorBuffer)if(Array.isArray(colorBuffer))for(colorCubes=[],i=0;i0&&(params.depth=faces[0].depth,params.stencil=faces[0].stencil,params.depthStencil=faces[0].depthStencil),faces[i]?faces[i](params):faces[i]=createFBO(params)}return extend(reglFramebufferCube,{width:radius,height:radius,color:colorCubes})}function resize(radius_){var i,radius=0|radius_;if(check$1(radius>0&&radius<=limits.maxCubeMapSize,"invalid radius for cube fbo"),radius===reglFramebufferCube.width)return reglFramebufferCube;var colors=reglFramebufferCube.color;for(i=0;i{for(var keys=Object.keys(options),i=0;i=0,'invalid option for vao: "'+keys[i]+'" valid options are '+VAO_OPTIONS)})),check$1(Array.isArray(attributes),"attributes must be an array")}check$1(attributes.length0,"must specify at least one attribute");var bufUpdated={},nattributes=vao.attributes;nattributes.length=attributes.length;for(var i=0;i=data.byteLength?buf.subdata(data):(buf.destroy(),vao.buffers[i]=null)),vao.buffers[i]||(buf=vao.buffers[i]=bufferState.create(spec,GL_ARRAY_BUFFER$1,!1,!0)),rec.buffer=bufferState.getBuffer(buf),rec.size=0|rec.buffer.dimension,rec.normalized=!1,rec.type=rec.buffer.dtype,rec.offset=0,rec.stride=0,rec.divisor=0,rec.state=1,bufUpdated[i]=1):bufferState.getBuffer(spec)?(rec.buffer=bufferState.getBuffer(spec),rec.size=0|rec.buffer.dimension,rec.normalized=!1,rec.type=rec.buffer.dtype,rec.offset=0,rec.stride=0,rec.divisor=0,rec.state=1):bufferState.getBuffer(spec.buffer)?(rec.buffer=bufferState.getBuffer(spec.buffer),rec.size=0|(+spec.size||rec.buffer.dimension),rec.normalized=!!spec.normalized||!1,"type"in spec?(check$1.parameter(spec.type,glTypes,"invalid buffer type"),rec.type=glTypes[spec.type]):rec.type=rec.buffer.dtype,rec.offset=0|(spec.offset||0),rec.stride=0|(spec.stride||0),rec.divisor=0|(spec.divisor||0),rec.state=1,check$1(rec.size>=1&&rec.size<=4,"size must be between 1 and 4"),check$1(rec.offset>=0,"invalid offset"),check$1(rec.stride>=0&&rec.stride<=255,"stride must be between 0 and 255"),check$1(rec.divisor>=0,"divisor must be positive"),check$1(!rec.divisor||!!extensions.angle_instanced_arrays,"ANGLE_instanced_arrays must be enabled to use divisor")):"x"in spec?(check$1(i>0,"first attribute must not be a constant"),rec.x=+spec.x||0,rec.y=+spec.y||0,rec.z=+spec.z||0,rec.w=+spec.w||0,rec.state=2):check$1(!1,"invalid attribute spec for location "+i)}for(var j=0;j1)for(var j=0;j1&&(uniName=uniName.replace("[0]","")),insertActiveInfo(uniforms,new ActiveInfo(uniName,stringStore.id(uniName),gl.getUniformLocation(program,uniName),info))}var numAttributes=gl.getProgramParameter(program,GL_ACTIVE_ATTRIBUTES);config.profile&&(desc.stats.attributesCount=numAttributes);var attributes=desc.attributes;for(i=0;im&&(m=desc.stats.uniformsCount)})),m},stats.getMaxAttributesCount=function(){var m=0;return programList.forEach((function(desc){desc.stats.attributesCount>m&&(m=desc.stats.attributesCount)})),m}),{clear:function(){var deleteShader=gl.deleteShader.bind(gl);values(fragShaders).forEach(deleteShader),fragShaders={},values(vertShaders).forEach(deleteShader),vertShaders={},programList.forEach((function(desc){gl.deleteProgram(desc.program)})),programList.length=0,programCache={},stats.shaderCount=0},program:function(vertId,fragId,command,attribLocations){check$1.command(vertId>=0,"missing vertex shader",command),check$1.command(fragId>=0,"missing fragment shader",command);var cache=programCache[fragId];cache||(cache=programCache[fragId]={});var prevProgram=cache[vertId];if(prevProgram&&(prevProgram.refCount++,!attribLocations))return prevProgram;var program=new REGLProgram(fragId,vertId);return stats.shaderCount++,linkProgram(program,command,attribLocations),prevProgram||(cache[vertId]=program),programList.push(program),extend(program,{destroy:function(){if(program.refCount--,program.refCount<=0){gl.deleteProgram(program.program);var idx=programList.indexOf(program);programList.splice(idx,1),stats.shaderCount--}cache[program.vertId].refCount<=0&&(gl.deleteShader(vertShaders[program.vertId]),delete vertShaders[program.vertId],delete programCache[program.fragId][program.vertId]),Object.keys(programCache[program.fragId]).length||(gl.deleteShader(fragShaders[program.fragId]),delete fragShaders[program.fragId],delete programCache[program.fragId])}})},restore:restoreShaders,shader:getShader,frag:-1,vert:-1}}var GL_RGBA$3=6408,GL_UNSIGNED_BYTE$7=5121,GL_PACK_ALIGNMENT=3333,GL_FLOAT$7=5126;function wrapReadPixels(gl,framebufferState,reglPoll,context,glAttributes,extensions,limits){function readPixelsImpl(input){var type;null===framebufferState.next?(check$1(glAttributes.preserveDrawingBuffer,'you must create a webgl context with "preserveDrawingBuffer":true in order to read pixels from the drawing buffer'),type=GL_UNSIGNED_BYTE$7):(check$1(null!==framebufferState.next.colorAttachments[0].texture,"You cannot read from a renderbuffer"),type=framebufferState.next.colorAttachments[0].texture._texture.type,check$1.optional((function(){extensions.oes_texture_float?(check$1(type===GL_UNSIGNED_BYTE$7||type===GL_FLOAT$7,"Reading from a framebuffer is only allowed for the types 'uint8' and 'float'"),type===GL_FLOAT$7&&check$1(limits.readFloat,"Reading 'float' values is not permitted in your browser. For a fallback, please see: https://www.npmjs.com/package/glsl-read-float")):check$1(type===GL_UNSIGNED_BYTE$7,"Reading from a framebuffer is only allowed for the type 'uint8'")})));var x=0,y=0,width=context.framebufferWidth,height=context.framebufferHeight,data=null;isTypedArray(input)?data=input:input&&(check$1.type(input,"object","invalid arguments to regl.read()"),x=0|input.x,y=0|input.y,check$1(x>=0&&x=0&&y0&&width+x<=context.framebufferWidth,"invalid width for read pixels"),check$1(height>0&&height+y<=context.framebufferHeight,"invalid height for read pixels"),reglPoll();var size=width*height*4;return data||(type===GL_UNSIGNED_BYTE$7?data=new Uint8Array(size):type===GL_FLOAT$7&&(data=data||new Float32Array(size))),check$1.isTypedArray(data,"data buffer for regl.read() must be a typedarray"),check$1(data.byteLength>=size,"data buffer for regl.read() too small"),gl.pixelStorei(GL_PACK_ALIGNMENT,4),gl.readPixels(x,y,width,height,GL_RGBA$3,type,data),data}function readPixelsFBO(options){var result;return framebufferState.setFBO({framebuffer:options.framebuffer},(function(){result=readPixelsImpl(options)})),result}function readPixels(options){return options&&"framebuffer"in options?readPixelsFBO(options):readPixelsImpl(options)}return readPixels}function slice(x){return Array.prototype.slice.call(x)}function join(x){return slice(x).join("")}function createEnvironment(){var varCounter=0,linkedNames=[],linkedValues=[];function link(value){for(var i=0;i0&&(code.push(name,"="),code.push.apply(code,slice(arguments)),code.push(";")),name}return extend(push,{def:def,toString:function(){return join([vars.length>0?"var "+vars.join(",")+";":"",join(code)])}})}function scope(){var entry=block(),exit=block(),entryToString=entry.toString,exitToString=exit.toString;function save(object,prop){exit(object,prop,"=",entry.def(object,prop),";")}return extend((function(){entry.apply(entry,slice(arguments))}),{def:entry.def,entry:entry,exit:exit,save:save,set:function(object,prop,value){save(object,prop),entry(object,prop,"=",value,";")},toString:function(){return entryToString()+exitToString()}})}function conditional(){var pred=join(arguments),thenBlock=scope(),elseBlock=scope(),thenToString=thenBlock.toString,elseToString=elseBlock.toString;return extend(thenBlock,{then:function(){return thenBlock.apply(thenBlock,slice(arguments)),this},else:function(){return elseBlock.apply(elseBlock,slice(arguments)),this},toString:function(){var elseClause=elseToString();return elseClause&&(elseClause="else{"+elseClause+"}"),join(["if(",pred,"){",thenToString(),"}",elseClause])}})}var globalBlock=block(),procedures={};function proc(name,count){var args=[];function arg(){var name="a"+args.length;return args.push(name),name}count=count||0;for(var i=0;i":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},stencilOps={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},shaderType={frag:35632,vert:35633},orientationType={cw:GL_CW,ccw:GL_CCW};function isBufferArgs(x){return Array.isArray(x)||isTypedArray(x)||isNDArrayLike(x)}function sortState(state){return state.sort((function(a,b){return a===S_VIEWPORT?-1:b===S_VIEWPORT?1:a=1,numArgs>=2,append)}if(type===DYN_THUNK){var data=dyn.data;return new Declaration(data.thisDep,data.contextDep,data.propDep,append)}if(type===DYN_CONSTANT$1)return new Declaration(!1,!1,!1,append);if(type===DYN_ARRAY$1){for(var thisDep=!1,contextDep=!1,propDep=!1,i=0;i=1&&(contextDep=!0),subArgs>=2&&(propDep=!0)}else subDyn.type===DYN_THUNK&&(thisDep=thisDep||subDyn.data.thisDep,contextDep=contextDep||subDyn.data.contextDep,propDep=propDep||subDyn.data.propDep)}return new Declaration(thisDep,contextDep,propDep,append)}return new Declaration(type===DYN_STATE$1,type===DYN_CONTEXT$1,type===DYN_PROP$1,append)}var SCOPE_DECL=new Declaration(!1,!1,!1,(function(){}));function reglCore(gl,stringStore,extensions,limits,bufferState,elementState,textureState,framebufferState,uniformState,attributeState,shaderState,drawState,contextState,timer,config){var AttributeRecord=attributeState.Record,blendEquations={add:32774,subtract:32778,"reverse subtract":32779};extensions.ext_blend_minmax&&(blendEquations.min=GL_MIN_EXT,blendEquations.max=GL_MAX_EXT);var extInstancing=extensions.angle_instanced_arrays,extDrawBuffers=extensions.webgl_draw_buffers,extVertexArrays=extensions.oes_vertex_array_object,currentState={dirty:!0,profile:config.profile},nextState={},GL_STATE_NAMES=[],GL_FLAGS={},GL_VARIABLES={};function propName(name){return name.replace(".","_")}function stateFlag(sname,cap,init){var name=propName(sname);GL_STATE_NAMES.push(sname),nextState[name]=currentState[name]=!!init,GL_FLAGS[name]=cap}function stateVariable(sname,func,init){var name=propName(sname);GL_STATE_NAMES.push(sname),Array.isArray(init)?(currentState[name]=init.slice(),nextState[name]=init.slice()):currentState[name]=nextState[name]=init,GL_VARIABLES[name]=func}stateFlag(S_DITHER,GL_DITHER),stateFlag(S_BLEND_ENABLE,GL_BLEND),stateVariable(S_BLEND_COLOR,"blendColor",[0,0,0,0]),stateVariable(S_BLEND_EQUATION,"blendEquationSeparate",[GL_FUNC_ADD,GL_FUNC_ADD]),stateVariable(S_BLEND_FUNC,"blendFuncSeparate",[GL_ONE,GL_ZERO,GL_ONE,GL_ZERO]),stateFlag(S_DEPTH_ENABLE,GL_DEPTH_TEST,!0),stateVariable(S_DEPTH_FUNC,"depthFunc",GL_LESS),stateVariable(S_DEPTH_RANGE,"depthRange",[0,1]),stateVariable(S_DEPTH_MASK,"depthMask",!0),stateVariable(S_COLOR_MASK,S_COLOR_MASK,[!0,!0,!0,!0]),stateFlag(S_CULL_ENABLE,GL_CULL_FACE),stateVariable(S_CULL_FACE,"cullFace",GL_BACK),stateVariable(S_FRONT_FACE,S_FRONT_FACE,GL_CCW),stateVariable(S_LINE_WIDTH,S_LINE_WIDTH,1),stateFlag(S_POLYGON_OFFSET_ENABLE,GL_POLYGON_OFFSET_FILL),stateVariable(S_POLYGON_OFFSET_OFFSET,"polygonOffset",[0,0]),stateFlag(S_SAMPLE_ALPHA,GL_SAMPLE_ALPHA_TO_COVERAGE),stateFlag(S_SAMPLE_ENABLE,GL_SAMPLE_COVERAGE),stateVariable(S_SAMPLE_COVERAGE,"sampleCoverage",[1,!1]),stateFlag(S_STENCIL_ENABLE,GL_STENCIL_TEST),stateVariable(S_STENCIL_MASK,"stencilMask",-1),stateVariable(S_STENCIL_FUNC,"stencilFunc",[GL_ALWAYS,0,-1]),stateVariable(S_STENCIL_OPFRONT,"stencilOpSeparate",[GL_FRONT,GL_KEEP,GL_KEEP,GL_KEEP]),stateVariable(S_STENCIL_OPBACK,"stencilOpSeparate",[GL_BACK,GL_KEEP,GL_KEEP,GL_KEEP]),stateFlag(S_SCISSOR_ENABLE,GL_SCISSOR_TEST),stateVariable(S_SCISSOR_BOX,"scissor",[0,0,gl.drawingBufferWidth,gl.drawingBufferHeight]),stateVariable(S_VIEWPORT,S_VIEWPORT,[0,0,gl.drawingBufferWidth,gl.drawingBufferHeight]);var sharedState={gl:gl,context:contextState,strings:stringStore,next:nextState,current:currentState,draw:drawState,elements:elementState,buffer:bufferState,shader:shaderState,attributes:attributeState.state,vao:attributeState,uniforms:uniformState,framebuffer:framebufferState,extensions:extensions,timer:timer,isBufferArgs:isBufferArgs},sharedConstants={primTypes:primTypes,compareFuncs:compareFuncs,blendFuncs:blendFuncs,blendEquations:blendEquations,stencilOps:stencilOps,glTypes:glTypes,orientationType:orientationType};check$1.optional((function(){sharedState.isArrayLike=isArrayLike})),extDrawBuffers&&(sharedConstants.backBuffer=[GL_BACK],sharedConstants.drawBuffer=loop(limits.maxDrawbuffers,(function(i){return 0===i?[0]:loop(i,(function(j){return GL_COLOR_ATTACHMENT0$2+j}))})));var drawCallCounter=0;function createREGLEnvironment(){var env=createEnvironment(),link=env.link,global=env.global;env.id=drawCallCounter++,env.batchId="0";var SHARED=link(sharedState),shared=env.shared={props:"a0"};Object.keys(sharedState).forEach((function(prop){shared[prop]=global.def(SHARED,".",prop)})),check$1.optional((function(){env.CHECK=link(check$1),env.commandStr=check$1.guessCommand(),env.command=link(env.commandStr),env.assert=function(block,pred,message){block("if(!(",pred,"))",this.CHECK,".commandRaise(",link(message),",",this.command,");")},sharedConstants.invalidBlendCombinations=invalidBlendCombinations}));var nextVars=env.next={},currentVars=env.current={};Object.keys(GL_VARIABLES).forEach((function(variable){Array.isArray(currentState[variable])&&(nextVars[variable]=global.def(shared.next,".",variable),currentVars[variable]=global.def(shared.current,".",variable))}));var constants=env.constants={};Object.keys(sharedConstants).forEach((function(name){constants[name]=global.def(JSON.stringify(sharedConstants[name]))})),env.invoke=function(block,x){switch(x.type){case DYN_FUNC$1:var argList=["this",shared.context,shared.props,env.batchId];return block.def(link(x.data),".call(",argList.slice(0,Math.max(x.data.length+1,4)),")");case DYN_PROP$1:return block.def(shared.props,x.data);case DYN_CONTEXT$1:return block.def(shared.context,x.data);case DYN_STATE$1:return block.def("this",x.data);case DYN_THUNK:return x.data.append(env,block),x.data.ref;case DYN_CONSTANT$1:return x.data.toString();case DYN_ARRAY$1:return x.data.map((function(y){return env.invoke(block,y)}))}},env.attribCache={};var scopeAttribs={};return env.scopeAttrib=function(name){var id=stringStore.id(name);if(id in scopeAttribs)return scopeAttribs[id];var binding=attributeState.scope[id];return binding||(binding=attributeState.scope[id]=new AttributeRecord),scopeAttribs[id]=link(binding)},env}function parseProfile(options){var profileEnable,staticOptions=options.static,dynamicOptions=options.dynamic;if(S_PROFILE in staticOptions){var value=!!staticOptions[S_PROFILE];(profileEnable=createStaticDecl((function(env,scope){return value}))).enable=value}else if(S_PROFILE in dynamicOptions){var dyn=dynamicOptions[S_PROFILE];profileEnable=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))}return profileEnable}function parseFramebuffer(options,env){var staticOptions=options.static,dynamicOptions=options.dynamic;if(S_FRAMEBUFFER in staticOptions){var framebuffer=staticOptions[S_FRAMEBUFFER];return framebuffer?(framebuffer=framebufferState.getFramebuffer(framebuffer),check$1.command(framebuffer,"invalid framebuffer object"),createStaticDecl((function(env,block){var FRAMEBUFFER=env.link(framebuffer),shared=env.shared;block.set(shared.framebuffer,".next",FRAMEBUFFER);var CONTEXT=shared.context;return block.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,FRAMEBUFFER+".width"),block.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,FRAMEBUFFER+".height"),FRAMEBUFFER}))):createStaticDecl((function(env,scope){var shared=env.shared;scope.set(shared.framebuffer,".next","null");var CONTEXT=shared.context;return scope.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,CONTEXT+"."+S_DRAWINGBUFFER_WIDTH),scope.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,CONTEXT+"."+S_DRAWINGBUFFER_HEIGHT),"null"}))}if(S_FRAMEBUFFER in dynamicOptions){var dyn=dynamicOptions[S_FRAMEBUFFER];return createDynamicDecl(dyn,(function(env,scope){var FRAMEBUFFER_FUNC=env.invoke(scope,dyn),shared=env.shared,FRAMEBUFFER_STATE=shared.framebuffer,FRAMEBUFFER=scope.def(FRAMEBUFFER_STATE,".getFramebuffer(",FRAMEBUFFER_FUNC,")");check$1.optional((function(){env.assert(scope,"!"+FRAMEBUFFER_FUNC+"||"+FRAMEBUFFER,"invalid framebuffer object")})),scope.set(FRAMEBUFFER_STATE,".next",FRAMEBUFFER);var CONTEXT=shared.context;return scope.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,FRAMEBUFFER+"?"+FRAMEBUFFER+".width:"+CONTEXT+"."+S_DRAWINGBUFFER_WIDTH),scope.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,FRAMEBUFFER+"?"+FRAMEBUFFER+".height:"+CONTEXT+"."+S_DRAWINGBUFFER_HEIGHT),FRAMEBUFFER}))}return null}function parseViewportScissor(options,framebuffer,env){var staticOptions=options.static,dynamicOptions=options.dynamic;function parseBox(param){if(param in staticOptions){var box=staticOptions[param];check$1.commandType(box,"object","invalid "+param,env.commandStr);var w,h,isStatic=!0,x=0|box.x,y=0|box.y;return"width"in box?(w=0|box.width,check$1.command(w>=0,"invalid "+param,env.commandStr)):isStatic=!1,"height"in box?(h=0|box.height,check$1.command(h>=0,"invalid "+param,env.commandStr)):isStatic=!1,new Declaration(!isStatic&&framebuffer&&framebuffer.thisDep,!isStatic&&framebuffer&&framebuffer.contextDep,!isStatic&&framebuffer&&framebuffer.propDep,(function(env,scope){var CONTEXT=env.shared.context,BOX_W=w;"width"in box||(BOX_W=scope.def(CONTEXT,".",S_FRAMEBUFFER_WIDTH,"-",x));var BOX_H=h;return"height"in box||(BOX_H=scope.def(CONTEXT,".",S_FRAMEBUFFER_HEIGHT,"-",y)),[x,y,BOX_W,BOX_H]}))}if(param in dynamicOptions){var dynBox=dynamicOptions[param],result=createDynamicDecl(dynBox,(function(env,scope){var BOX=env.invoke(scope,dynBox);check$1.optional((function(){env.assert(scope,BOX+"&&typeof "+BOX+'==="object"',"invalid "+param)}));var CONTEXT=env.shared.context,BOX_X=scope.def(BOX,".x|0"),BOX_Y=scope.def(BOX,".y|0"),BOX_W=scope.def('"width" in ',BOX,"?",BOX,".width|0:","(",CONTEXT,".",S_FRAMEBUFFER_WIDTH,"-",BOX_X,")"),BOX_H=scope.def('"height" in ',BOX,"?",BOX,".height|0:","(",CONTEXT,".",S_FRAMEBUFFER_HEIGHT,"-",BOX_Y,")");return check$1.optional((function(){env.assert(scope,BOX_W+">=0&&"+BOX_H+">=0","invalid "+param)})),[BOX_X,BOX_Y,BOX_W,BOX_H]}));return framebuffer&&(result.thisDep=result.thisDep||framebuffer.thisDep,result.contextDep=result.contextDep||framebuffer.contextDep,result.propDep=result.propDep||framebuffer.propDep),result}return framebuffer?new Declaration(framebuffer.thisDep,framebuffer.contextDep,framebuffer.propDep,(function(env,scope){var CONTEXT=env.shared.context;return[0,0,scope.def(CONTEXT,".",S_FRAMEBUFFER_WIDTH),scope.def(CONTEXT,".",S_FRAMEBUFFER_HEIGHT)]})):null}var viewport=parseBox(S_VIEWPORT);if(viewport){var prevViewport=viewport;viewport=new Declaration(viewport.thisDep,viewport.contextDep,viewport.propDep,(function(env,scope){var VIEWPORT=prevViewport.append(env,scope),CONTEXT=env.shared.context;return scope.set(CONTEXT,"."+S_VIEWPORT_WIDTH,VIEWPORT[2]),scope.set(CONTEXT,"."+S_VIEWPORT_HEIGHT,VIEWPORT[3]),VIEWPORT}))}return{viewport:viewport,scissor_box:parseBox(S_SCISSOR_BOX)}}function parseAttribLocations(options,attributes){var staticOptions=options.static;if("string"==typeof staticOptions[S_FRAG]&&"string"==typeof staticOptions[S_VERT]){if(Object.keys(attributes.dynamic).length>0)return null;var staticAttributes=attributes.static,sAttributes=Object.keys(staticAttributes);if(sAttributes.length>0&&"number"==typeof staticAttributes[sAttributes[0]]){for(var bindings=[],i=0;i=0,"invalid "+param,env.commandStr),createStaticDecl((function(env,scope){return isOffset&&(env.OFFSET=value),value}))}if(param in dynamicOptions){var dynValue=dynamicOptions[param];return createDynamicDecl(dynValue,(function(env,scope){var result=env.invoke(scope,dynValue);return isOffset&&(env.OFFSET=result,check$1.optional((function(){env.assert(scope,result+">=0","invalid "+param)}))),result}))}if(isOffset){if(elementsActive)return createStaticDecl((function(env,scope){return env.OFFSET=0,0}));if(vaoActive)return new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao+".currentVAO?"+env.shared.vao+".currentVAO.offset:0")}))}else if(vaoActive)return new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao+".currentVAO?"+env.shared.vao+".currentVAO.instances:-1")}));return null}var OFFSET=parseParam(S_OFFSET,!0);function parseVertCount(){if(S_COUNT in staticOptions){var count=0|staticOptions[S_COUNT];return staticDraw.count=count,check$1.command("number"==typeof count&&count>=0,"invalid vertex count",env.commandStr),createStaticDecl((function(){return count}))}if(S_COUNT in dynamicOptions){var dynCount=dynamicOptions[S_COUNT];return createDynamicDecl(dynCount,(function(env,scope){var result=env.invoke(scope,dynCount);return check$1.optional((function(){env.assert(scope,"typeof "+result+'==="number"&&'+result+">=0&&"+result+"===("+result+"|0)","invalid vertex count")})),result}))}if(elementsActive){if(isStatic(elements)){if(elements)return OFFSET?new Declaration(OFFSET.thisDep,OFFSET.contextDep,OFFSET.propDep,(function(env,scope){var result=scope.def(env.ELEMENTS,".vertCount-",env.OFFSET);return check$1.optional((function(){env.assert(scope,result+">=0","invalid vertex offset/element buffer too small")})),result})):createStaticDecl((function(env,scope){return scope.def(env.ELEMENTS,".vertCount")}));var result=createStaticDecl((function(){return-1}));return check$1.optional((function(){result.MISSING=!0})),result}var variable=new Declaration(elements.thisDep||OFFSET.thisDep,elements.contextDep||OFFSET.contextDep,elements.propDep||OFFSET.propDep,(function(env,scope){var elements=env.ELEMENTS;return env.OFFSET?scope.def(elements,"?",elements,".vertCount-",env.OFFSET,":-1"):scope.def(elements,"?",elements,".vertCount:-1")}));return check$1.optional((function(){variable.DYNAMIC=!0})),variable}if(vaoActive){var countVariable=new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao,".currentVAO?",env.shared.vao,".currentVAO.count:-1")}));return countVariable}return null}var primitive=parsePrimitive(),count=parseVertCount(),instances=parseParam(S_INSTANCES,!1);return{elements:elements,primitive:primitive,count:count,instances:instances,offset:OFFSET,vao:vao,vaoActive:vaoActive,elementsActive:elementsActive,static:staticDraw}}function parseGLState(options,env){var staticOptions=options.static,dynamicOptions=options.dynamic,STATE={};return GL_STATE_NAMES.forEach((function(prop){var param=propName(prop);function parseParam(parseStatic,parseDynamic){if(prop in staticOptions){var value=parseStatic(staticOptions[prop]);STATE[param]=createStaticDecl((function(){return value}))}else if(prop in dynamicOptions){var dyn=dynamicOptions[prop];STATE[param]=createDynamicDecl(dyn,(function(env,scope){return parseDynamic(env,scope,env.invoke(scope,dyn))}))}}switch(prop){case S_CULL_ENABLE:case S_BLEND_ENABLE:case S_DITHER:case S_STENCIL_ENABLE:case S_DEPTH_ENABLE:case S_SCISSOR_ENABLE:case S_POLYGON_OFFSET_ENABLE:case S_SAMPLE_ALPHA:case S_SAMPLE_ENABLE:case S_DEPTH_MASK:return parseParam((function(value){return check$1.commandType(value,"boolean",prop,env.commandStr),value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,"typeof "+value+'==="boolean"',"invalid flag "+prop,env.commandStr)})),value}));case S_DEPTH_FUNC:return parseParam((function(value){return check$1.commandParameter(value,compareFuncs,"invalid "+prop,env.commandStr),compareFuncs[value]}),(function(env,scope,value){var COMPARE_FUNCS=env.constants.compareFuncs;return check$1.optional((function(){env.assert(scope,value+" in "+COMPARE_FUNCS,"invalid "+prop+", must be one of "+Object.keys(compareFuncs))})),scope.def(COMPARE_FUNCS,"[",value,"]")}));case S_DEPTH_RANGE:return parseParam((function(value){return check$1.command(isArrayLike(value)&&2===value.length&&"number"==typeof value[0]&&"number"==typeof value[1]&&value[0]<=value[1],"depth range is 2d array",env.commandStr),value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===2&&typeof "+value+'[0]==="number"&&typeof '+value+'[1]==="number"&&'+value+"[0]<="+value+"[1]","depth range must be a 2d array")})),[scope.def("+",value,"[0]"),scope.def("+",value,"[1]")]}));case S_BLEND_FUNC:return parseParam((function(value){check$1.commandType(value,"object","blend.func",env.commandStr);var srcRGB="srcRGB"in value?value.srcRGB:value.src,srcAlpha="srcAlpha"in value?value.srcAlpha:value.src,dstRGB="dstRGB"in value?value.dstRGB:value.dst,dstAlpha="dstAlpha"in value?value.dstAlpha:value.dst;return check$1.commandParameter(srcRGB,blendFuncs,param+".srcRGB",env.commandStr),check$1.commandParameter(srcAlpha,blendFuncs,param+".srcAlpha",env.commandStr),check$1.commandParameter(dstRGB,blendFuncs,param+".dstRGB",env.commandStr),check$1.commandParameter(dstAlpha,blendFuncs,param+".dstAlpha",env.commandStr),check$1.command(-1===invalidBlendCombinations.indexOf(srcRGB+", "+dstRGB),"unallowed blending combination (srcRGB, dstRGB) = ("+srcRGB+", "+dstRGB+")",env.commandStr),[blendFuncs[srcRGB],blendFuncs[dstRGB],blendFuncs[srcAlpha],blendFuncs[dstAlpha]]}),(function(env,scope,value){var BLEND_FUNCS=env.constants.blendFuncs;function read(prefix,suffix){var func=scope.def('"',prefix,suffix,'" in ',value,"?",value,".",prefix,suffix,":",value,".",prefix);return check$1.optional((function(){env.assert(scope,func+" in "+BLEND_FUNCS,"invalid "+prop+"."+prefix+suffix+", must be one of "+Object.keys(blendFuncs))})),func}check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid blend func, must be an object")}));var srcRGB=read("src","RGB"),dstRGB=read("dst","RGB");check$1.optional((function(){var INVALID_BLEND_COMBINATIONS=env.constants.invalidBlendCombinations;env.assert(scope,INVALID_BLEND_COMBINATIONS+".indexOf("+srcRGB+'+", "+'+dstRGB+") === -1 ","unallowed blending combination for (srcRGB, dstRGB)")}));var SRC_RGB=scope.def(BLEND_FUNCS,"[",srcRGB,"]"),SRC_ALPHA=scope.def(BLEND_FUNCS,"[",read("src","Alpha"),"]");return[SRC_RGB,scope.def(BLEND_FUNCS,"[",dstRGB,"]"),SRC_ALPHA,scope.def(BLEND_FUNCS,"[",read("dst","Alpha"),"]")]}));case S_BLEND_EQUATION:return parseParam((function(value){return"string"==typeof value?(check$1.commandParameter(value,blendEquations,"invalid "+prop,env.commandStr),[blendEquations[value],blendEquations[value]]):"object"==typeof value?(check$1.commandParameter(value.rgb,blendEquations,prop+".rgb",env.commandStr),check$1.commandParameter(value.alpha,blendEquations,prop+".alpha",env.commandStr),[blendEquations[value.rgb],blendEquations[value.alpha]]):void check$1.commandRaise("invalid blend.equation",env.commandStr)}),(function(env,scope,value){var BLEND_EQUATIONS=env.constants.blendEquations,RGB=scope.def(),ALPHA=scope.def(),ifte=env.cond("typeof ",value,'==="string"');return check$1.optional((function(){function checkProp(block,name,value){env.assert(block,value+" in "+BLEND_EQUATIONS,"invalid "+name+", must be one of "+Object.keys(blendEquations))}checkProp(ifte.then,prop,value),env.assert(ifte.else,value+"&&typeof "+value+'==="object"',"invalid "+prop),checkProp(ifte.else,prop+".rgb",value+".rgb"),checkProp(ifte.else,prop+".alpha",value+".alpha")})),ifte.then(RGB,"=",ALPHA,"=",BLEND_EQUATIONS,"[",value,"];"),ifte.else(RGB,"=",BLEND_EQUATIONS,"[",value,".rgb];",ALPHA,"=",BLEND_EQUATIONS,"[",value,".alpha];"),scope(ifte),[RGB,ALPHA]}));case S_BLEND_COLOR:return parseParam((function(value){return check$1.command(isArrayLike(value)&&4===value.length,"blend.color must be a 4d array",env.commandStr),loop(4,(function(i){return+value[i]}))}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===4","blend.color must be a 4d array")})),loop(4,(function(i){return scope.def("+",value,"[",i,"]")}))}));case S_STENCIL_MASK:return parseParam((function(value){return check$1.commandType(value,"number",param,env.commandStr),0|value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,"typeof "+value+'==="number"',"invalid stencil.mask")})),scope.def(value,"|0")}));case S_STENCIL_FUNC:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var cmp=value.cmp||"keep",ref=value.ref||0,mask="mask"in value?value.mask:-1;return check$1.commandParameter(cmp,compareFuncs,prop+".cmp",env.commandStr),check$1.commandType(ref,"number",prop+".ref",env.commandStr),check$1.commandType(mask,"number",prop+".mask",env.commandStr),[compareFuncs[cmp],ref,mask]}),(function(env,scope,value){var COMPARE_FUNCS=env.constants.compareFuncs;return check$1.optional((function(){function assert(){env.assert(scope,Array.prototype.join.call(arguments,""),"invalid stencil.func")}assert(value+"&&typeof ",value,'==="object"'),assert('!("cmp" in ',value,")||(",value,".cmp in ",COMPARE_FUNCS,")")})),[scope.def('"cmp" in ',value,"?",COMPARE_FUNCS,"[",value,".cmp]",":",GL_KEEP),scope.def(value,".ref|0"),scope.def('"mask" in ',value,"?",value,".mask|0:-1")]}));case S_STENCIL_OPFRONT:case S_STENCIL_OPBACK:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var fail=value.fail||"keep",zfail=value.zfail||"keep",zpass=value.zpass||"keep";return check$1.commandParameter(fail,stencilOps,prop+".fail",env.commandStr),check$1.commandParameter(zfail,stencilOps,prop+".zfail",env.commandStr),check$1.commandParameter(zpass,stencilOps,prop+".zpass",env.commandStr),[prop===S_STENCIL_OPBACK?GL_BACK:GL_FRONT,stencilOps[fail],stencilOps[zfail],stencilOps[zpass]]}),(function(env,scope,value){var STENCIL_OPS=env.constants.stencilOps;function read(name){return check$1.optional((function(){env.assert(scope,'!("'+name+'" in '+value+")||("+value+"."+name+" in "+STENCIL_OPS+")","invalid "+prop+"."+name+", must be one of "+Object.keys(stencilOps))})),scope.def('"',name,'" in ',value,"?",STENCIL_OPS,"[",value,".",name,"]:",GL_KEEP)}return check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid "+prop)})),[prop===S_STENCIL_OPBACK?GL_BACK:GL_FRONT,read("fail"),read("zfail"),read("zpass")]}));case S_POLYGON_OFFSET_OFFSET:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var factor=0|value.factor,units=0|value.units;return check$1.commandType(factor,"number",param+".factor",env.commandStr),check$1.commandType(units,"number",param+".units",env.commandStr),[factor,units]}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid "+prop)})),[scope.def(value,".factor|0"),scope.def(value,".units|0")]}));case S_CULL_FACE:return parseParam((function(value){var face=0;return"front"===value?face=GL_FRONT:"back"===value&&(face=GL_BACK),check$1.command(!!face,param,env.commandStr),face}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+'==="front"||'+value+'==="back"',"invalid cull.face")})),scope.def(value,'==="front"?',GL_FRONT,":",GL_BACK)}));case S_LINE_WIDTH:return parseParam((function(value){return check$1.command("number"==typeof value&&value>=limits.lineWidthDims[0]&&value<=limits.lineWidthDims[1],"invalid line width, must be a positive number between "+limits.lineWidthDims[0]+" and "+limits.lineWidthDims[1],env.commandStr),value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,"typeof "+value+'==="number"&&'+value+">="+limits.lineWidthDims[0]+"&&"+value+"<="+limits.lineWidthDims[1],"invalid line width")})),value}));case S_FRONT_FACE:return parseParam((function(value){return check$1.commandParameter(value,orientationType,param,env.commandStr),orientationType[value]}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+'==="cw"||'+value+'==="ccw"',"invalid frontFace, must be one of cw,ccw")})),scope.def(value+'==="cw"?'+GL_CW+":"+GL_CCW)}));case S_COLOR_MASK:return parseParam((function(value){return check$1.command(isArrayLike(value)&&4===value.length,"color.mask must be length 4 array",env.commandStr),value.map((function(v){return!!v}))}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===4","invalid color.mask")})),loop(4,(function(i){return"!!"+value+"["+i+"]"}))}));case S_SAMPLE_COVERAGE:return parseParam((function(value){check$1.command("object"==typeof value&&value,param,env.commandStr);var sampleValue="value"in value?value.value:1,sampleInvert=!!value.invert;return check$1.command("number"==typeof sampleValue&&sampleValue>=0&&sampleValue<=1,"sample.coverage.value must be a number between 0 and 1",env.commandStr),[sampleValue,sampleInvert]}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid sample.coverage")})),[scope.def('"value" in ',value,"?+",value,".value:1"),scope.def("!!",value,".invert")]}))}})),STATE}function parseUniforms(uniforms,env){var staticUniforms=uniforms.static,dynamicUniforms=uniforms.dynamic,UNIFORMS={};return Object.keys(staticUniforms).forEach((function(name){var result,value=staticUniforms[name];if("number"==typeof value||"boolean"==typeof value)result=createStaticDecl((function(){return value}));else if("function"==typeof value){var reglType=value._reglType;"texture2d"===reglType||"textureCube"===reglType?result=createStaticDecl((function(env){return env.link(value)})):"framebuffer"===reglType||"framebufferCube"===reglType?(check$1.command(value.color.length>0,'missing color attachment for framebuffer sent to uniform "'+name+'"',env.commandStr),result=createStaticDecl((function(env){return env.link(value.color[0])}))):check$1.commandRaise('invalid data for uniform "'+name+'"',env.commandStr)}else isArrayLike(value)?result=createStaticDecl((function(env){return env.global.def("[",loop(value.length,(function(i){return check$1.command("number"==typeof value[i]||"boolean"==typeof value[i],"invalid uniform "+name,env.commandStr),value[i]})),"]")})):check$1.commandRaise('invalid or missing data for uniform "'+name+'"',env.commandStr);result.value=value,UNIFORMS[name]=result})),Object.keys(dynamicUniforms).forEach((function(key){var dyn=dynamicUniforms[key];UNIFORMS[key]=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))})),UNIFORMS}function parseAttributes(attributes,env){var staticAttributes=attributes.static,dynamicAttributes=attributes.dynamic,attributeDefs={};return Object.keys(staticAttributes).forEach((function(attribute){var value=staticAttributes[attribute],id=stringStore.id(attribute),record=new AttributeRecord;if(isBufferArgs(value))record.state=ATTRIB_STATE_POINTER,record.buffer=bufferState.getBuffer(bufferState.create(value,GL_ARRAY_BUFFER$2,!1,!0)),record.type=0;else{var buffer=bufferState.getBuffer(value);if(buffer)record.state=ATTRIB_STATE_POINTER,record.buffer=buffer,record.type=0;else if(check$1.command("object"==typeof value&&value,"invalid data for attribute "+attribute,env.commandStr),"constant"in value){var constant=value.constant;record.buffer="null",record.state=ATTRIB_STATE_CONSTANT,"number"==typeof constant?record.x=constant:(check$1.command(isArrayLike(constant)&&constant.length>0&&constant.length<=4,"invalid constant for attribute "+attribute,env.commandStr),CUTE_COMPONENTS.forEach((function(c,i){i=0,'invalid offset for attribute "'+attribute+'"',env.commandStr);var stride=0|value.stride;check$1.command(stride>=0&&stride<256,'invalid stride for attribute "'+attribute+'", must be integer betweeen [0, 255]',env.commandStr);var size=0|value.size;check$1.command(!("size"in value)||size>0&&size<=4,'invalid size for attribute "'+attribute+'", must be 1,2,3,4',env.commandStr);var normalized=!!value.normalized,type=0;"type"in value&&(check$1.commandParameter(value.type,glTypes,"invalid type for attribute "+attribute,env.commandStr),type=glTypes[value.type]);var divisor=0|value.divisor;check$1.optional((function(){"divisor"in value&&(check$1.command(0===divisor||extInstancing,'cannot specify divisor for attribute "'+attribute+'", instancing not supported',env.commandStr),check$1.command(divisor>=0,'invalid divisor for attribute "'+attribute+'"',env.commandStr));var command=env.commandStr,VALID_KEYS=["buffer","offset","divisor","normalized","type","size","stride"];Object.keys(value).forEach((function(prop){check$1.command(VALID_KEYS.indexOf(prop)>=0,'unknown parameter "'+prop+'" for attribute pointer "'+attribute+'" (valid parameters are '+VALID_KEYS+")",command)}))})),record.buffer=buffer,record.state=ATTRIB_STATE_POINTER,record.size=size,record.normalized=normalized,record.type=type||buffer.dtype,record.offset=offset,record.stride=stride,record.divisor=divisor}}attributeDefs[attribute]=createStaticDecl((function(env,scope){var cache=env.attribCache;if(id in cache)return cache[id];var result={isStream:!1};return Object.keys(record).forEach((function(key){result[key]=record[key]})),record.buffer&&(result.buffer=env.link(record.buffer),result.type=result.type||result.buffer+".dtype"),cache[id]=result,result}))})),Object.keys(dynamicAttributes).forEach((function(attribute){var dyn=dynamicAttributes[attribute];function appendAttributeCode(env,block){var VALUE=env.invoke(block,dyn),shared=env.shared,constants=env.constants,IS_BUFFER_ARGS=shared.isBufferArgs,BUFFER_STATE=shared.buffer;check$1.optional((function(){env.assert(block,VALUE+"&&(typeof "+VALUE+'==="object"||typeof '+VALUE+'==="function")&&('+IS_BUFFER_ARGS+"("+VALUE+")||"+BUFFER_STATE+".getBuffer("+VALUE+")||"+BUFFER_STATE+".getBuffer("+VALUE+".buffer)||"+IS_BUFFER_ARGS+"("+VALUE+'.buffer)||("constant" in '+VALUE+"&&(typeof "+VALUE+'.constant==="number"||'+shared.isArrayLike+"("+VALUE+".constant))))",'invalid dynamic attribute "'+attribute+'"')}));var result={isStream:block.def(!1)},defaultRecord=new AttributeRecord;defaultRecord.state=ATTRIB_STATE_POINTER,Object.keys(defaultRecord).forEach((function(key){result[key]=block.def(""+defaultRecord[key])}));var BUFFER=result.buffer,TYPE=result.type;function emitReadRecord(name){block(result[name],"=",VALUE,".",name,"|0;")}return block("if(",IS_BUFFER_ARGS,"(",VALUE,")){",result.isStream,"=true;",BUFFER,"=",BUFFER_STATE,".createStream(",GL_ARRAY_BUFFER$2,",",VALUE,");",TYPE,"=",BUFFER,".dtype;","}else{",BUFFER,"=",BUFFER_STATE,".getBuffer(",VALUE,");","if(",BUFFER,"){",TYPE,"=",BUFFER,".dtype;",'}else if("constant" in ',VALUE,"){",result.state,"=",ATTRIB_STATE_CONSTANT,";","if(typeof "+VALUE+'.constant === "number"){',result[CUTE_COMPONENTS[0]],"=",VALUE,".constant;",CUTE_COMPONENTS.slice(1).map((function(n){return result[n]})).join("="),"=0;","}else{",CUTE_COMPONENTS.map((function(name,i){return result[name]+"="+VALUE+".constant.length>"+i+"?"+VALUE+".constant["+i+"]:0;"})).join(""),"}}else{","if(",IS_BUFFER_ARGS,"(",VALUE,".buffer)){",BUFFER,"=",BUFFER_STATE,".createStream(",GL_ARRAY_BUFFER$2,",",VALUE,".buffer);","}else{",BUFFER,"=",BUFFER_STATE,".getBuffer(",VALUE,".buffer);","}",TYPE,'="type" in ',VALUE,"?",constants.glTypes,"[",VALUE,".type]:",BUFFER,".dtype;",result.normalized,"=!!",VALUE,".normalized;"),emitReadRecord("size"),emitReadRecord("offset"),emitReadRecord("stride"),emitReadRecord("divisor"),block("}}"),block.exit("if(",result.isStream,"){",BUFFER_STATE,".destroyStream(",BUFFER,");","}"),result}attributeDefs[attribute]=createDynamicDecl(dyn,appendAttributeCode)})),attributeDefs}function parseContext(context){var staticContext=context.static,dynamicContext=context.dynamic,result={};return Object.keys(staticContext).forEach((function(name){var value=staticContext[name];result[name]=createStaticDecl((function(env,scope){return"number"==typeof value||"boolean"==typeof value?""+value:env.link(value)}))})),Object.keys(dynamicContext).forEach((function(name){var dyn=dynamicContext[name];result[name]=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))})),result}function parseArguments(options,attributes,uniforms,context,env){var staticOptions=options.static,dynamicOptions=options.dynamic;check$1.optional((function(){var KEY_NAMES=[S_FRAMEBUFFER,S_VERT,S_FRAG,S_ELEMENTS,S_PRIMITIVE,S_OFFSET,S_COUNT,S_INSTANCES,S_PROFILE,S_VAO].concat(GL_STATE_NAMES);function checkKeys(dict){Object.keys(dict).forEach((function(key){check$1.command(KEY_NAMES.indexOf(key)>=0,'unknown parameter "'+key+'"',env.commandStr)}))}checkKeys(staticOptions),checkKeys(dynamicOptions)}));var attribLocations=parseAttribLocations(options,attributes),framebuffer=parseFramebuffer(options),viewportAndScissor=parseViewportScissor(options,framebuffer,env),draw=parseDraw(options,env),state=parseGLState(options,env),shader=parseProgram(options,env,attribLocations);function copyBox(name){var defn=viewportAndScissor[name];defn&&(state[name]=defn)}copyBox(S_VIEWPORT),copyBox(propName(S_SCISSOR_BOX));var dirty=Object.keys(state).length>0,result={framebuffer:framebuffer,draw:draw,shader:shader,state:state,dirty:dirty,scopeVAO:null,drawVAO:null,useVAO:!1,attributes:{}};if(result.profile=parseProfile(options),result.uniforms=parseUniforms(uniforms,env),result.drawVAO=result.scopeVAO=draw.vao,!result.drawVAO&&shader.program&&!attribLocations&&extensions.angle_instanced_arrays&&draw.static.elements){var useVAO=!0,staticBindings=shader.program.attributes.map((function(attr){var binding=attributes.static[attr];return useVAO=useVAO&&!!binding,binding}));if(useVAO&&staticBindings.length>0){var vao=attributeState.getVAO(attributeState.createVAO({attributes:staticBindings,elements:draw.static.elements}));result.drawVAO=new Declaration(null,null,null,(function(env,scope){return env.link(vao)})),result.useVAO=!0}}return attribLocations?result.useVAO=!0:result.attributes=parseAttributes(attributes,env),result.context=parseContext(context),result}function emitContext(env,scope,context){var CONTEXT=env.shared.context,contextEnter=env.scope();Object.keys(context).forEach((function(name){scope.save(CONTEXT,"."+name);var value=context[name].append(env,scope);Array.isArray(value)?contextEnter(CONTEXT,".",name,"=[",value.join(),"];"):contextEnter(CONTEXT,".",name,"=",value,";")})),scope(contextEnter)}function emitPollFramebuffer(env,scope,framebuffer,skipCheck){var EXT_DRAW_BUFFERS,shared=env.shared,GL=shared.gl,FRAMEBUFFER_STATE=shared.framebuffer;extDrawBuffers&&(EXT_DRAW_BUFFERS=scope.def(shared.extensions,".webgl_draw_buffers"));var NEXT,constants=env.constants,DRAW_BUFFERS=constants.drawBuffer,BACK_BUFFER=constants.backBuffer;NEXT=framebuffer?framebuffer.append(env,scope):scope.def(FRAMEBUFFER_STATE,".next"),skipCheck||scope("if(",NEXT,"!==",FRAMEBUFFER_STATE,".cur){"),scope("if(",NEXT,"){",GL,".bindFramebuffer(",GL_FRAMEBUFFER$2,",",NEXT,".framebuffer);"),extDrawBuffers&&scope(EXT_DRAW_BUFFERS,".drawBuffersWEBGL(",DRAW_BUFFERS,"[",NEXT,".colorAttachments.length]);"),scope("}else{",GL,".bindFramebuffer(",GL_FRAMEBUFFER$2,",null);"),extDrawBuffers&&scope(EXT_DRAW_BUFFERS,".drawBuffersWEBGL(",BACK_BUFFER,");"),scope("}",FRAMEBUFFER_STATE,".cur=",NEXT,";"),skipCheck||scope("}")}function emitPollState(env,scope,args){var shared=env.shared,GL=shared.gl,CURRENT_VARS=env.current,NEXT_VARS=env.next,CURRENT_STATE=shared.current,NEXT_STATE=shared.next,block=env.cond(CURRENT_STATE,".dirty");GL_STATE_NAMES.forEach((function(prop){var NEXT,CURRENT,param=propName(prop);if(!(param in args.state))if(param in NEXT_VARS){NEXT=NEXT_VARS[param],CURRENT=CURRENT_VARS[param];var parts=loop(currentState[param].length,(function(i){return block.def(NEXT,"[",i,"]")}));block(env.cond(parts.map((function(p,i){return p+"!=="+CURRENT+"["+i+"]"})).join("||")).then(GL,".",GL_VARIABLES[param],"(",parts,");",parts.map((function(p,i){return CURRENT+"["+i+"]="+p})).join(";"),";"))}else{NEXT=block.def(NEXT_STATE,".",param);var ifte=env.cond(NEXT,"!==",CURRENT_STATE,".",param);block(ifte),param in GL_FLAGS?ifte(env.cond(NEXT).then(GL,".enable(",GL_FLAGS[param],");").else(GL,".disable(",GL_FLAGS[param],");"),CURRENT_STATE,".",param,"=",NEXT,";"):ifte(GL,".",GL_VARIABLES[param],"(",NEXT,");",CURRENT_STATE,".",param,"=",NEXT,";")}})),0===Object.keys(args.state).length&&block(CURRENT_STATE,".dirty=false;"),scope(block)}function emitSetOptions(env,scope,options,filter){var shared=env.shared,CURRENT_VARS=env.current,CURRENT_STATE=shared.current,GL=shared.gl;sortState(Object.keys(options)).forEach((function(param){var defn=options[param];if(!filter||filter(defn)){var variable=defn.append(env,scope);if(GL_FLAGS[param]){var flag=GL_FLAGS[param];isStatic(defn)?scope(GL,variable?".enable(":".disable(",flag,");"):scope(env.cond(variable).then(GL,".enable(",flag,");").else(GL,".disable(",flag,");")),scope(CURRENT_STATE,".",param,"=",variable,";")}else if(isArrayLike(variable)){var CURRENT=CURRENT_VARS[param];scope(GL,".",GL_VARIABLES[param],"(",variable,");",variable.map((function(v,i){return CURRENT+"["+i+"]="+v})).join(";"),";")}else scope(GL,".",GL_VARIABLES[param],"(",variable,");",CURRENT_STATE,".",param,"=",variable,";")}}))}function injectExtensions(env,scope){extInstancing&&(env.instancing=scope.def(env.shared.extensions,".angle_instanced_arrays"))}function emitProfile(env,scope,args,useScope,incrementCounter){var CPU_START,QUERY_COUNTER,USE_PROFILE,shared=env.shared,STATS=env.stats,CURRENT_STATE=shared.current,TIMER=shared.timer,profileArg=args.profile;function perfCounter(){return"undefined"==typeof performance?"Date.now()":"performance.now()"}function emitProfileStart(block){block(CPU_START=scope.def(),"=",perfCounter(),";"),"string"==typeof incrementCounter?block(STATS,".count+=",incrementCounter,";"):block(STATS,".count++;"),timer&&(useScope?block(QUERY_COUNTER=scope.def(),"=",TIMER,".getNumPendingQueries();"):block(TIMER,".beginQuery(",STATS,");"))}function emitProfileEnd(block){block(STATS,".cpuTime+=",perfCounter(),"-",CPU_START,";"),timer&&(useScope?block(TIMER,".pushScopeStats(",QUERY_COUNTER,",",TIMER,".getNumPendingQueries(),",STATS,");"):block(TIMER,".endQuery();"))}function scopeProfile(value){var prev=scope.def(CURRENT_STATE,".profile");scope(CURRENT_STATE,".profile=",value,";"),scope.exit(CURRENT_STATE,".profile=",prev,";")}if(profileArg){if(isStatic(profileArg))return void(profileArg.enable?(emitProfileStart(scope),emitProfileEnd(scope.exit),scopeProfile("true")):scopeProfile("false"));scopeProfile(USE_PROFILE=profileArg.append(env,scope))}else USE_PROFILE=scope.def(CURRENT_STATE,".profile");var start=env.block();emitProfileStart(start),scope("if(",USE_PROFILE,"){",start,"}");var end=env.block();emitProfileEnd(end),scope.exit("if(",USE_PROFILE,"){",end,"}")}function emitAttributes(env,scope,args,attributes,filter){var shared=env.shared;function typeLength(x){switch(x){case GL_FLOAT_VEC2:case GL_INT_VEC2:case GL_BOOL_VEC2:return 2;case GL_FLOAT_VEC3:case GL_INT_VEC3:case GL_BOOL_VEC3:return 3;case GL_FLOAT_VEC4:case GL_INT_VEC4:case GL_BOOL_VEC4:return 4;default:return 1}}function emitBindAttribute(ATTRIBUTE,size,record){var GL=shared.gl,LOCATION=scope.def(ATTRIBUTE,".location"),BINDING=scope.def(shared.attributes,"[",LOCATION,"]"),STATE=record.state,BUFFER=record.buffer,CONST_COMPONENTS=[record.x,record.y,record.z,record.w],COMMON_KEYS=["buffer","normalized","offset","stride"];function emitBuffer(){scope("if(!",BINDING,".buffer){",GL,".enableVertexAttribArray(",LOCATION,");}");var SIZE,TYPE=record.type;if(SIZE=record.size?scope.def(record.size,"||",size):size,scope("if(",BINDING,".type!==",TYPE,"||",BINDING,".size!==",SIZE,"||",COMMON_KEYS.map((function(key){return BINDING+"."+key+"!=="+record[key]})).join("||"),"){",GL,".bindBuffer(",GL_ARRAY_BUFFER$2,",",BUFFER,".buffer);",GL,".vertexAttribPointer(",[LOCATION,SIZE,TYPE,record.normalized,record.stride,record.offset],");",BINDING,".type=",TYPE,";",BINDING,".size=",SIZE,";",COMMON_KEYS.map((function(key){return BINDING+"."+key+"="+record[key]+";"})).join(""),"}"),extInstancing){var DIVISOR=record.divisor;scope("if(",BINDING,".divisor!==",DIVISOR,"){",env.instancing,".vertexAttribDivisorANGLE(",[LOCATION,DIVISOR],");",BINDING,".divisor=",DIVISOR,";}")}}function emitConstant(){scope("if(",BINDING,".buffer){",GL,".disableVertexAttribArray(",LOCATION,");",BINDING,".buffer=null;","}if(",CUTE_COMPONENTS.map((function(c,i){return BINDING+"."+c+"!=="+CONST_COMPONENTS[i]})).join("||"),"){",GL,".vertexAttrib4f(",LOCATION,",",CONST_COMPONENTS,");",CUTE_COMPONENTS.map((function(c,i){return BINDING+"."+c+"="+CONST_COMPONENTS[i]+";"})).join(""),"}")}STATE===ATTRIB_STATE_POINTER?emitBuffer():STATE===ATTRIB_STATE_CONSTANT?emitConstant():(scope("if(",STATE,"===",ATTRIB_STATE_POINTER,"){"),emitBuffer(),scope("}else{"),emitConstant(),scope("}"))}attributes.forEach((function(attribute){var record,name=attribute.name,arg=args.attributes[name];if(arg){if(!filter(arg))return;record=arg.append(env,scope)}else{if(!filter(SCOPE_DECL))return;var scopeAttrib=env.scopeAttrib(name);check$1.optional((function(){env.assert(scope,scopeAttrib+".state","missing attribute "+name)})),record={},Object.keys(new AttributeRecord).forEach((function(key){record[key]=scope.def(scopeAttrib,".",key)}))}emitBindAttribute(env.link(attribute),typeLength(attribute.info.type),record)}))}function emitUniforms(env,scope,args,uniforms,filter,isBatchInnerLoop){for(var infix,shared=env.shared,GL=shared.gl,definedArrUniforms={},i=0;i1){if(!arg)continue;var arrUniformName=name.replace("[0]","");if(definedArrUniforms[arrUniformName])continue;definedArrUniforms[arrUniformName]=1}var VALUE,LOCATION=env.link(uniform)+".location";if(arg){if(!filter(arg))continue;if(isStatic(arg)){var value=arg.value;if(check$1.command(null!=value,'missing uniform "'+name+'"',env.commandStr),type===GL_SAMPLER_2D||type===GL_SAMPLER_CUBE){check$1.command("function"==typeof value&&(type===GL_SAMPLER_2D&&("texture2d"===value._reglType||"framebuffer"===value._reglType)||type===GL_SAMPLER_CUBE&&("textureCube"===value._reglType||"framebufferCube"===value._reglType)),"invalid texture for uniform "+name,env.commandStr);var TEX_VALUE=env.link(value._texture||value.color[0]._texture);scope(GL,".uniform1i(",LOCATION,",",TEX_VALUE+".bind());"),scope.exit(TEX_VALUE,".unbind();")}else if(type===GL_FLOAT_MAT2||type===GL_FLOAT_MAT3||type===GL_FLOAT_MAT4){check$1.optional((function(){check$1.command(isArrayLike(value),"invalid matrix for uniform "+name,env.commandStr),check$1.command(type===GL_FLOAT_MAT2&&4===value.length||type===GL_FLOAT_MAT3&&9===value.length||type===GL_FLOAT_MAT4&&16===value.length,"invalid length for matrix uniform "+name,env.commandStr)}));var MAT_VALUE=env.global.def("new Float32Array(["+Array.prototype.slice.call(value)+"])"),dim=2;type===GL_FLOAT_MAT3?dim=3:type===GL_FLOAT_MAT4&&(dim=4),scope(GL,".uniformMatrix",dim,"fv(",LOCATION,",false,",MAT_VALUE,");")}else{switch(type){case GL_FLOAT$8:1===size?check$1.commandType(value,"number","uniform "+name,env.commandStr):check$1.command(isArrayLike(value)&&value.length===size,"uniform "+name,env.commandStr),infix="1f";break;case GL_FLOAT_VEC2:check$1.command(isArrayLike(value)&&value.length&&value.length%2==0&&value.length<=2*size,"uniform "+name,env.commandStr),infix="2f";break;case GL_FLOAT_VEC3:check$1.command(isArrayLike(value)&&value.length&&value.length%3==0&&value.length<=3*size,"uniform "+name,env.commandStr),infix="3f";break;case GL_FLOAT_VEC4:check$1.command(isArrayLike(value)&&value.length&&value.length%4==0&&value.length<=4*size,"uniform "+name,env.commandStr),infix="4f";break;case GL_BOOL:1===size?check$1.commandType(value,"boolean","uniform "+name,env.commandStr):check$1.command(isArrayLike(value)&&value.length===size,"uniform "+name,env.commandStr),infix="1i";break;case GL_INT$3:1===size?check$1.commandType(value,"number","uniform "+name,env.commandStr):check$1.command(isArrayLike(value)&&value.length===size,"uniform "+name,env.commandStr),infix="1i";break;case GL_BOOL_VEC2:case GL_INT_VEC2:check$1.command(isArrayLike(value)&&value.length&&value.length%2==0&&value.length<=2*size,"uniform "+name,env.commandStr),infix="2i";break;case GL_BOOL_VEC3:case GL_INT_VEC3:check$1.command(isArrayLike(value)&&value.length&&value.length%3==0&&value.length<=3*size,"uniform "+name,env.commandStr),infix="3i";break;case GL_BOOL_VEC4:case GL_INT_VEC4:check$1.command(isArrayLike(value)&&value.length&&value.length%4==0&&value.length<=4*size,"uniform "+name,env.commandStr),infix="4i"}size>1?(infix+="v",value=env.global.def("["+Array.prototype.slice.call(value)+"]")):value=isArrayLike(value)?Array.prototype.slice.call(value):value,scope(GL,".uniform",infix,"(",LOCATION,",",value,");")}continue}VALUE=arg.append(env,scope)}else{if(!filter(SCOPE_DECL))continue;VALUE=scope.def(shared.uniforms,"[",stringStore.id(name),"]")}type===GL_SAMPLER_2D?(check$1(!Array.isArray(VALUE),"must specify a scalar prop for textures"),scope("if(",VALUE,"&&",VALUE,'._reglType==="framebuffer"){',VALUE,"=",VALUE,".color[0];","}")):type===GL_SAMPLER_CUBE&&(check$1(!Array.isArray(VALUE),"must specify a scalar prop for cube maps"),scope("if(",VALUE,"&&",VALUE,'._reglType==="framebufferCube"){',VALUE,"=",VALUE,".color[0];","}")),check$1.optional((function(){function emitCheck(pred,message){env.assert(scope,pred,'bad data or missing for uniform "'+name+'". '+message)}function checkType(type,size){1===size&&check$1(!Array.isArray(VALUE),"must not specify an array type for uniform"),emitCheck("Array.isArray("+VALUE+") && typeof "+VALUE+'[0]===" '+type+'" || typeof '+VALUE+'==="'+type+'"',"invalid type, expected "+type)}function checkVector(n,type,size){Array.isArray(VALUE)?check$1(VALUE.length&&VALUE.length%n==0&&VALUE.length<=n*size,"must have length of "+(1===size?"":"n * ")+n):emitCheck(shared.isArrayLike+"("+VALUE+")&&"+VALUE+".length && "+VALUE+".length % "+n+" === 0 && "+VALUE+".length<="+n*size,"invalid vector, should have length of "+(1===size?"":"n * ")+n,env.commandStr)}function checkTexture(target){check$1(!Array.isArray(VALUE),"must not specify a value type"),emitCheck("typeof "+VALUE+'==="function"&&'+VALUE+'._reglType==="texture'+(target===GL_TEXTURE_2D$3?"2d":"Cube")+'"',"invalid texture type",env.commandStr)}switch(type){case GL_INT$3:checkType("number",size);break;case GL_INT_VEC2:checkVector(2,"number",size);break;case GL_INT_VEC3:checkVector(3,"number",size);break;case GL_INT_VEC4:checkVector(4,"number",size);break;case GL_FLOAT$8:checkType("number",size);break;case GL_FLOAT_VEC2:checkVector(2,"number",size);break;case GL_FLOAT_VEC3:checkVector(3,"number",size);break;case GL_FLOAT_VEC4:checkVector(4,"number",size);break;case GL_BOOL:checkType("boolean",size);break;case GL_BOOL_VEC2:checkVector(2,"boolean",size);break;case GL_BOOL_VEC3:checkVector(3,"boolean",size);break;case GL_BOOL_VEC4:checkVector(4,"boolean",size);break;case GL_FLOAT_MAT2:checkVector(4,"number",size);break;case GL_FLOAT_MAT3:checkVector(9,"number",size);break;case GL_FLOAT_MAT4:checkVector(16,"number",size);break;case GL_SAMPLER_2D:checkTexture(GL_TEXTURE_2D$3);break;case GL_SAMPLER_CUBE:checkTexture(GL_TEXTURE_CUBE_MAP$2)}}));var unroll=1;switch(type){case GL_SAMPLER_2D:case GL_SAMPLER_CUBE:var TEX=scope.def(VALUE,"._texture");scope(GL,".uniform1i(",LOCATION,",",TEX,".bind());"),scope.exit(TEX,".unbind();");continue;case GL_INT$3:case GL_BOOL:infix="1i";break;case GL_INT_VEC2:case GL_BOOL_VEC2:infix="2i",unroll=2;break;case GL_INT_VEC3:case GL_BOOL_VEC3:infix="3i",unroll=3;break;case GL_INT_VEC4:case GL_BOOL_VEC4:infix="4i",unroll=4;break;case GL_FLOAT$8:infix="1f";break;case GL_FLOAT_VEC2:infix="2f",unroll=2;break;case GL_FLOAT_VEC3:infix="3f",unroll=3;break;case GL_FLOAT_VEC4:infix="4f",unroll=4;break;case GL_FLOAT_MAT2:infix="Matrix2fv";break;case GL_FLOAT_MAT3:infix="Matrix3fv";break;case GL_FLOAT_MAT4:infix="Matrix4fv"}if(-1===infix.indexOf("Matrix")&&size>1&&(infix+="v",unroll=1),"M"===infix.charAt(0)){scope(GL,".uniform",infix,"(",LOCATION,",");var matSize=Math.pow(type-GL_FLOAT_MAT2+2,2),STORAGE=env.global.def("new Float32Array(",matSize,")");Array.isArray(VALUE)?scope("false,(",loop(matSize,(function(i){return STORAGE+"["+i+"]="+VALUE[i]})),",",STORAGE,")"):scope("false,(Array.isArray(",VALUE,")||",VALUE," instanceof Float32Array)?",VALUE,":(",loop(matSize,(function(i){return STORAGE+"["+i+"]="+VALUE+"["+i+"]"})),",",STORAGE,")"),scope(");")}else if(unroll>1){for(var prev=[],cur=[],j=0;j=0","missing vertex count")}))):(COUNT=scope.def(DRAW_STATE,".",S_COUNT),check$1.optional((function(){env.assert(scope,COUNT+">=0","missing vertex count")}))),COUNT}var ELEMENTS=emitElements();function emitValue(name){var defn=drawOptions[name];return defn?defn.contextDep&&args.contextDynamic||defn.propDep?defn.append(env,inner):defn.append(env,outer):outer.def(DRAW_STATE,".",name)}var INSTANCES,EXT_INSTANCING,PRIMITIVE=emitValue(S_PRIMITIVE),OFFSET=emitValue(S_OFFSET),COUNT=emitCount();if("number"==typeof COUNT){if(0===COUNT)return}else inner("if(",COUNT,"){"),inner.exit("}");extInstancing&&(INSTANCES=emitValue(S_INSTANCES),EXT_INSTANCING=env.instancing);var ELEMENT_TYPE=ELEMENTS+".type",elementsStatic=drawOptions.elements&&isStatic(drawOptions.elements)&&!drawOptions.vaoActive;function emitInstancing(){function drawElements(){inner(EXT_INSTANCING,".drawElementsInstancedANGLE(",[PRIMITIVE,COUNT,ELEMENT_TYPE,OFFSET+"<<(("+ELEMENT_TYPE+"-"+GL_UNSIGNED_BYTE$8+")>>1)",INSTANCES],");")}function drawArrays(){inner(EXT_INSTANCING,".drawArraysInstancedANGLE(",[PRIMITIVE,OFFSET,COUNT,INSTANCES],");")}ELEMENTS&&"null"!==ELEMENTS?elementsStatic?drawElements():(inner("if(",ELEMENTS,"){"),drawElements(),inner("}else{"),drawArrays(),inner("}")):drawArrays()}function emitRegular(){function drawElements(){inner(GL+".drawElements("+[PRIMITIVE,COUNT,ELEMENT_TYPE,OFFSET+"<<(("+ELEMENT_TYPE+"-"+GL_UNSIGNED_BYTE$8+")>>1)"]+");")}function drawArrays(){inner(GL+".drawArrays("+[PRIMITIVE,OFFSET,COUNT]+");")}ELEMENTS&&"null"!==ELEMENTS?elementsStatic?drawElements():(inner("if(",ELEMENTS,"){"),drawElements(),inner("}else{"),drawArrays(),inner("}")):drawArrays()}extInstancing&&("number"!=typeof INSTANCES||INSTANCES>=0)?"string"==typeof INSTANCES?(inner("if(",INSTANCES,">0){"),emitInstancing(),inner("}else if(",INSTANCES,"<0){"),emitRegular(),inner("}")):emitInstancing():emitRegular()}function createBody(emitBody,parentEnv,args,program,count){var env=createREGLEnvironment(),scope=env.proc("body",count);return check$1.optional((function(){env.commandStr=parentEnv.commandStr,env.command=env.link(parentEnv.commandStr)})),extInstancing&&(env.instancing=scope.def(env.shared.extensions,".angle_instanced_arrays")),emitBody(env,scope,args,program),env.compile().body}function emitDrawBody(env,draw,args,program){injectExtensions(env,draw),args.useVAO?args.drawVAO?draw(env.shared.vao,".setVAO(",args.drawVAO.append(env,draw),");"):draw(env.shared.vao,".setVAO(",env.shared.vao,".targetVAO);"):(draw(env.shared.vao,".setVAO(null);"),emitAttributes(env,draw,args,program.attributes,(function(){return!0}))),emitUniforms(env,draw,args,program.uniforms,(function(){return!0}),!1),emitDraw(env,draw,draw,args)}function emitDrawProc(env,args){var draw=env.proc("draw",1);injectExtensions(env,draw),emitContext(env,draw,args.context),emitPollFramebuffer(env,draw,args.framebuffer),emitPollState(env,draw,args),emitSetOptions(env,draw,args.state),emitProfile(env,draw,args,!1,!0);var program=args.shader.progVar.append(env,draw);if(draw(env.shared.gl,".useProgram(",program,".program);"),args.shader.program)emitDrawBody(env,draw,args,args.shader.program);else{draw(env.shared.vao,".setVAO(null);");var drawCache=env.global.def("{}"),PROG_ID=draw.def(program,".id"),CACHED_PROC=draw.def(drawCache,"[",PROG_ID,"]");draw(env.cond(CACHED_PROC).then(CACHED_PROC,".call(this,a0);").else(CACHED_PROC,"=",drawCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitDrawBody,env,args,program,1)})),"(",program,");",CACHED_PROC,".call(this,a0);"))}Object.keys(args.state).length>0&&draw(env.shared.current,".dirty=true;"),env.shared.vao&&draw(env.shared.vao,".setVAO(null);")}function emitBatchDynamicShaderBody(env,scope,args,program){function all(){return!0}env.batchId="a1",injectExtensions(env,scope),emitAttributes(env,scope,args,program.attributes,all),emitUniforms(env,scope,args,program.uniforms,all,!1),emitDraw(env,scope,scope,args)}function emitBatchBody(env,scope,args,program){injectExtensions(env,scope);var contextDynamic=args.contextDep,BATCH_ID=scope.def(),PROP_LIST="a0",NUM_PROPS="a1",PROPS=scope.def();env.shared.props=PROPS,env.batchId=BATCH_ID;var outer=env.scope(),inner=env.scope();function isInnerDefn(defn){return defn.contextDep&&contextDynamic||defn.propDep}function isOuterDefn(defn){return!isInnerDefn(defn)}if(scope(outer.entry,"for(",BATCH_ID,"=0;",BATCH_ID,"<",NUM_PROPS,";++",BATCH_ID,"){",PROPS,"=",PROP_LIST,"[",BATCH_ID,"];",inner,"}",outer.exit),args.needsContext&&emitContext(env,inner,args.context),args.needsFramebuffer&&emitPollFramebuffer(env,inner,args.framebuffer),emitSetOptions(env,inner,args.state,isInnerDefn),args.profile&&isInnerDefn(args.profile)&&emitProfile(env,inner,args,!1,!0),program)args.useVAO?args.drawVAO?isInnerDefn(args.drawVAO)?inner(env.shared.vao,".setVAO(",args.drawVAO.append(env,inner),");"):outer(env.shared.vao,".setVAO(",args.drawVAO.append(env,outer),");"):outer(env.shared.vao,".setVAO(",env.shared.vao,".targetVAO);"):(outer(env.shared.vao,".setVAO(null);"),emitAttributes(env,outer,args,program.attributes,isOuterDefn),emitAttributes(env,inner,args,program.attributes,isInnerDefn)),emitUniforms(env,outer,args,program.uniforms,isOuterDefn,!1),emitUniforms(env,inner,args,program.uniforms,isInnerDefn,!0),emitDraw(env,outer,inner,args);else{var progCache=env.global.def("{}"),PROGRAM=args.shader.progVar.append(env,inner),PROG_ID=inner.def(PROGRAM,".id"),CACHED_PROC=inner.def(progCache,"[",PROG_ID,"]");inner(env.shared.gl,".useProgram(",PROGRAM,".program);","if(!",CACHED_PROC,"){",CACHED_PROC,"=",progCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitBatchDynamicShaderBody,env,args,program,2)})),"(",PROGRAM,");}",CACHED_PROC,".call(this,a0[",BATCH_ID,"],",BATCH_ID,");")}}function emitBatchProc(env,args){var batch=env.proc("batch",2);env.batchId="0",injectExtensions(env,batch);var contextDynamic=!1,needsContext=!0;Object.keys(args.context).forEach((function(name){contextDynamic=contextDynamic||args.context[name].propDep})),contextDynamic||(emitContext(env,batch,args.context),needsContext=!1);var framebuffer=args.framebuffer,needsFramebuffer=!1;function isInnerDefn(defn){return defn.contextDep&&contextDynamic||defn.propDep}framebuffer?(framebuffer.propDep?contextDynamic=needsFramebuffer=!0:framebuffer.contextDep&&contextDynamic&&(needsFramebuffer=!0),needsFramebuffer||emitPollFramebuffer(env,batch,framebuffer)):emitPollFramebuffer(env,batch,null),args.state.viewport&&args.state.viewport.propDep&&(contextDynamic=!0),emitPollState(env,batch,args),emitSetOptions(env,batch,args.state,(function(defn){return!isInnerDefn(defn)})),args.profile&&isInnerDefn(args.profile)||emitProfile(env,batch,args,!1,"a1"),args.contextDep=contextDynamic,args.needsContext=needsContext,args.needsFramebuffer=needsFramebuffer;var progDefn=args.shader.progVar;if(progDefn.contextDep&&contextDynamic||progDefn.propDep)emitBatchBody(env,batch,args,null);else{var PROGRAM=progDefn.append(env,batch);if(batch(env.shared.gl,".useProgram(",PROGRAM,".program);"),args.shader.program)emitBatchBody(env,batch,args,args.shader.program);else{batch(env.shared.vao,".setVAO(null);");var batchCache=env.global.def("{}"),PROG_ID=batch.def(PROGRAM,".id"),CACHED_PROC=batch.def(batchCache,"[",PROG_ID,"]");batch(env.cond(CACHED_PROC).then(CACHED_PROC,".call(this,a0,a1);").else(CACHED_PROC,"=",batchCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitBatchBody,env,args,program,2)})),"(",PROGRAM,");",CACHED_PROC,".call(this,a0,a1);"))}}Object.keys(args.state).length>0&&batch(env.shared.current,".dirty=true;"),env.shared.vao&&batch(env.shared.vao,".setVAO(null);")}function emitScopeProc(env,args){var scope=env.proc("scope",3);env.batchId="a2";var shared=env.shared,CURRENT_STATE=shared.current;function saveShader(name){var shader=args.shader[name];shader&&scope.set(shared.shader,"."+name,shader.append(env,scope))}emitContext(env,scope,args.context),args.framebuffer&&args.framebuffer.append(env,scope),sortState(Object.keys(args.state)).forEach((function(name){var value=args.state[name].append(env,scope);isArrayLike(value)?value.forEach((function(v,i){scope.set(env.next[name],"["+i+"]",v)})):scope.set(shared.next,"."+name,value)})),emitProfile(env,scope,args,!0,!0),[S_ELEMENTS,S_OFFSET,S_COUNT,S_INSTANCES,S_PRIMITIVE].forEach((function(opt){var variable=args.draw[opt];variable&&scope.set(shared.draw,"."+opt,""+variable.append(env,scope))})),Object.keys(args.uniforms).forEach((function(opt){var value=args.uniforms[opt].append(env,scope);Array.isArray(value)&&(value="["+value.join()+"]"),scope.set(shared.uniforms,"["+stringStore.id(opt)+"]",value)})),Object.keys(args.attributes).forEach((function(name){var record=args.attributes[name].append(env,scope),scopeAttrib=env.scopeAttrib(name);Object.keys(new AttributeRecord).forEach((function(prop){scope.set(scopeAttrib,"."+prop,record[prop])}))})),args.scopeVAO&&scope.set(shared.vao,".targetVAO",args.scopeVAO.append(env,scope)),saveShader(S_VERT),saveShader(S_FRAG),Object.keys(args.state).length>0&&(scope(CURRENT_STATE,".dirty=true;"),scope.exit(CURRENT_STATE,".dirty=true;")),scope("a1(",env.shared.context,",a0,",env.batchId,");")}function isDynamicObject(object){if("object"==typeof object&&!isArrayLike(object)){for(var props=Object.keys(object),i=0;i=0;--i){var cb=rafCallbacks[i];cb&&cb(contextState,null,0)}gl.flush(),timer&&timer.update()}function startRAF(){!activeRAF&&rafCallbacks.length>0&&(activeRAF=raf.next(handleRAF))}function stopRAF(){activeRAF&&(raf.cancel(handleRAF),activeRAF=null)}function handleContextLoss(event){event.preventDefault(),contextLost=!0,stopRAF(),lossCallbacks.forEach((function(cb){cb()}))}function handleContextRestored(event){gl.getError(),contextLost=!1,extensionState.restore(),shaderState.restore(),bufferState.restore(),textureState.restore(),renderbufferState.restore(),framebufferState.restore(),attributeState.restore(),timer&&timer.restore(),core.procs.refresh(),startRAF(),restoreCallbacks.forEach((function(cb){cb()}))}function destroy(){rafCallbacks.length=0,stopRAF(),canvas&&(canvas.removeEventListener(CONTEXT_LOST_EVENT,handleContextLoss),canvas.removeEventListener(CONTEXT_RESTORED_EVENT,handleContextRestored)),shaderState.clear(),framebufferState.clear(),renderbufferState.clear(),attributeState.clear(),textureState.clear(),elementState.clear(),bufferState.clear(),timer&&timer.clear(),destroyCallbacks.forEach((function(cb){cb()}))}function compileProcedure(options){function flattenNestedOptions(options){var result=extend({},options);function merge(name){if(name in result){var child=result[name];delete result[name],Object.keys(child).forEach((function(prop){result[name+"."+prop]=child[prop]}))}}return delete result.uniforms,delete result.attributes,delete result.context,delete result.vao,"stencil"in result&&result.stencil.op&&(result.stencil.opBack=result.stencil.opFront=result.stencil.op,delete result.stencil.op),merge("blend"),merge("depth"),merge("cull"),merge("stencil"),merge("polygonOffset"),merge("scissor"),merge("sample"),"vao"in options&&(result.vao=options.vao),result}function separateDynamic(object,useArrays){var staticItems={},dynamicItems={};return Object.keys(object).forEach((function(option){var value=object[option];if(dynamic.isDynamic(value))dynamicItems[option]=dynamic.unbox(value,option);else{if(useArrays&&Array.isArray(value))for(var i=0;i0)return batch.call(this,reserve(0|args),0|args)}else{if(!Array.isArray(args))return draw.call(this,args);if(args.length)return batch.call(this,args,args.length)}}return extend(REGLCommand,{stats:stats$$1,destroy:function(){compiled.destroy()}})}canvas&&(canvas.addEventListener(CONTEXT_LOST_EVENT,handleContextLoss,!1),canvas.addEventListener(CONTEXT_RESTORED_EVENT,handleContextRestored,!1));var setFBO=framebufferState.setFBO=compileProcedure({framebuffer:dynamic.define.call(null,DYN_PROP,"framebuffer")});function clearImpl(_,options){var clearFlags=0;core.procs.poll();var c=options.color;c&&(gl.clearColor(+c[0]||0,+c[1]||0,+c[2]||0,+c[3]||0),clearFlags|=GL_COLOR_BUFFER_BIT),"depth"in options&&(gl.clearDepth(+options.depth),clearFlags|=GL_DEPTH_BUFFER_BIT),"stencil"in options&&(gl.clearStencil(0|options.stencil),clearFlags|=GL_STENCIL_BUFFER_BIT),check$1(!!clearFlags,"called regl.clear with no buffer specified"),gl.clear(clearFlags)}function clear(options){if(check$1("object"==typeof options&&options,"regl.clear() takes an object as input"),"framebuffer"in options)if(options.framebuffer&&"framebufferCube"===options.framebuffer_reglType)for(var i=0;i<6;++i)setFBO(extend({framebuffer:options.framebuffer.faces[i]},options),clearImpl);else setFBO(options,clearImpl);else clearImpl(null,options)}function frame(cb){function cancel(){var i=find(rafCallbacks,cb);function pendingCancel(){var index=find(rafCallbacks,pendingCancel);rafCallbacks[index]=rafCallbacks[rafCallbacks.length-1],rafCallbacks.length-=1,rafCallbacks.length<=0&&stopRAF()}check$1(i>=0,"cannot cancel a frame twice"),rafCallbacks[i]=pendingCancel}return check$1.type(cb,"function","regl.frame() callback must be a function"),rafCallbacks.push(cb),startRAF(),{cancel:cancel}}function pollViewport(){var viewport=nextState.viewport,scissorBox=nextState.scissor_box;viewport[0]=viewport[1]=scissorBox[0]=scissorBox[1]=0,contextState.viewportWidth=contextState.framebufferWidth=contextState.drawingBufferWidth=viewport[2]=scissorBox[2]=gl.drawingBufferWidth,contextState.viewportHeight=contextState.framebufferHeight=contextState.drawingBufferHeight=viewport[3]=scissorBox[3]=gl.drawingBufferHeight}function poll(){contextState.tick+=1,contextState.time=now(),pollViewport(),core.procs.poll()}function refresh(){textureState.refresh(),pollViewport(),core.procs.refresh(),timer&&timer.update()}function now(){return(clock()-START_TIME)/1e3}function addListener(event,callback){var callbacks;switch(check$1.type(callback,"function","listener callback must be a function"),event){case"frame":return frame(callback);case"lost":callbacks=lossCallbacks;break;case"restore":callbacks=restoreCallbacks;break;case"destroy":callbacks=destroyCallbacks;break;default:check$1.raise("invalid event, must be one of frame,lost,restore,destroy")}return callbacks.push(callback),{cancel:function(){for(var i=0;i=0},read:readPixels,destroy:destroy,_gl:gl,_refresh:refresh,poll:function(){poll(),timer&&timer.update()},now:now,stats:stats$$1});return config.onDone(null,regl),regl}return wrapREGL}()}({get exports(){return reglExports},set exports(v){reglExports=v}});var regl=reglExports;exports.cameras=index$2,exports.commands=index$1,exports.controls=index,exports.entitiesFromSolids=(options,...solids)=>{const defaults={color:meshColor,smoothNormals:!0},{color:color,smoothNormals:smoothNormals}=Object.assign({},defaults,options);var array;solids=(solids=flatten((array=solids,Array.isArray(array)?array:null==array?[]:[array]))).filter((solid=>solid&&solid instanceof Object));const entities=[];return solids.forEach((solid=>{let geometries=[];"outlines"in solid?geometries=((options,solid)=>{let{color:color}=options;const outlines=solid.outlines;if(0===outlines.length)return[];"color"in solid&&(color=solid.color);const isTransparent=color[3]<1,geometries=[];for(let i=0;inormal)),indices=positions.map(((x,i)=>i)),transforms=solid.transforms?glMat4.clone(solid.transforms):glMat4.create();geometries.push({type:"2d",positions:positions,normals:normals,indices:indices,transforms:transforms,color:color,isTransparent:isTransparent})}}return geometries})({color:color},solid):"points"in solid?geometries=((options,solid)=>{let{color:color}=options;const points=solid.points;if(0===points.length)return[];"color"in solid&&(color=solid.color);const isTransparent=color[3]<1,numgeometries=Math.floor(points.length/maxIndex)+1,geometries=[];for(let g=0;gnormal)),indices=positions.map(((x,i)=>i)),transforms=solid.transforms?glMat4.clone(solid.transforms):glMat4.create();geometries.push({type:"2d",positions:positions,normals:normals,indices:indices,transforms:transforms,color:color,isTransparent:isTransparent})}return geometries})({color:color},solid):"polygons"in solid&&(geometries=((options,solid)=>{let{color:color,smoothLighting:smoothLighting}=options;"color"in solid&&(color=solid.color);const polygons=solid.polygons,transforms=solid.transforms?glMat4.clone(solid.transforms):glMat4.create(),geometries=[];let setstart=0;for(;setstart65535));i++)setend++;const positions=[],normals=[],indices=[],colors=[],isTransparent=color[3]<1;for(let i=setstart;igeometries.map((geometry=>({geometry:geometry,visuals:{drawCmd:"2d"===geometry.type?"drawLines":"drawMesh",show:!0,transparent:geometry.isTransparent,useVertexColors:!0}}))))(geometries))})),entities},exports.prepareRender=params=>{const options=Object.assign({},{},params.glOptions,{onDone:(err,callback)=>{if(err)throw err}}),base=regl(options),drawCache2=new Map,command=props=>{props.rendering=Object.assign({},renderDefaults,props.rendering),((regl,params={})=>{const{fbo:fbo}=params,commandParams={cull:{enable:!0},context:{lightDirection:[.2,.2,1]},uniforms:{view:(context,props)=>props.camera.view,eye:(context,props)=>props.camera.position,projection:(context,props)=>props.camera.projection,camNear:(context,props)=>props.camera.near,camFar:(context,props)=>props.camera.far,invertedView:(context,props)=>glMat4.invert([],props.camera.view),lightPosition:(context,props)=>props&&props.rendering&&props.rendering.lightPosition?props.rendering.lightPosition:[100,200,100],lightDirection:(context,props)=>props&&props.rendering&&props.rendering.lightDirection?props.rendering.lightDirection:context.lightDirection||[0,0,0],lightView:context=>glMat4.lookAt([],context.lightDirection,[0,0,0],[0,0,1]),lightProjection:glMat4.ortho([],-25,-25,-20,20,-25,25),lightColor:(context,props)=>props&&props.rendering&&props.rendering.lightColor?props.rendering.lightColor:[1,.8,0],ambientLightAmount:(context,props)=>props&&props.rendering&&props.rendering.ambientLightAmount?props.rendering.ambientLightAmount:.3,diffuseLightAmount:(context,props)=>props&&props.rendering&&props.rendering.diffuseLightAmount?props&&props.rendering&&props.rendering.diffuseLightAmount:.89,specularLightAmount:(context,props)=>props&&props.rendering&&props.rendering.specularLightAmount?props.rendering.specularLightAmount:.16,uMaterialShininess:(context,props)=>props&&props.rendering&&props.rendering.materialShininess?props.rendering.materialShininess:8,materialAmbient:[.5,.8,.3],materialDiffuse:[.5,.8,.3],materialSpecular:[.5,.8,.3]},framebuffer:fbo};return regl(Object.assign({},commandParams,params.extras))})(base)(props,(context=>{base.clear({color:props.rendering.background,depth:1}),props.entities&&props.entities.sort(((a,b)=>{const aTransparent="transparent"in a.visuals&&a.visuals.transparent;return aTransparent===("transparent"in b.visuals&&b.visuals.transparent)?0:aTransparent?1:-1})).forEach((entity=>{const{visuals:visuals}=entity;if((!("show"in visuals)||visuals.show)&&visuals.drawCmd&&props.drawCommands[visuals.drawCmd]){let drawCmd;visuals.cacheId?drawCmd=drawCache2.get(visuals.cacheId):(visuals.cacheId=drawCache2.size,drawCmd=props.drawCommands[visuals.drawCmd](base,entity),drawCache2.set(visuals.cacheId,drawCmd));drawCmd({...entity,...visuals,camera:props.camera})}}))}))};return function(data){base.poll(),command(data)}},Object.defineProperty(exports,"__esModule",{value:!0})})); diff --git a/packages/utils/regl-renderer/package.json b/packages/utils/regl-renderer/package.json index 88b41f8e9..c11d103c1 100644 --- a/packages/utils/regl-renderer/package.json +++ b/packages/utils/regl-renderer/package.json @@ -1,6 +1,6 @@ { "name": "@jscad/regl-renderer", - "version": "3.0.0-alpha.0", + "version": "3.0.1-alpha.0", "description": "Renderer for JSCAD Geometries", "homepage": "https://openjscad.xyz/", "repository": "https://github.com/jscad/OpenJSCAD.org", @@ -50,7 +50,7 @@ "access": "public" }, "dependencies": { - "@jscad/array-utils": "workspace:3.0.0-alpha.0", + "@jscad/array-utils": "workspace:3.0.1-alpha.0", "camera-unproject": "1.0.1", "gl-mat4": "1.2.0", "gl-vec3": "1.1.3", @@ -58,7 +58,7 @@ }, "devDependencies": { "@jscad/img-utils": "workspace:2.0.5", - "@jscad/modeling": "workspace:3.0.0-alpha.0", + "@jscad/modeling": "workspace:3.0.1-alpha.0", "@rollup/plugin-commonjs": "^23.0.4", "@rollup/plugin-node-resolve": "^15.0.1", "@rollup/plugin-terser": "^0.4.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dccc07bb6..6501c75b7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -32,11 +32,11 @@ importers: packages/cli: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/core': workspace:3.0.0-alpha.0 - '@jscad/io': workspace:3.0.0-alpha.0 - '@jscad/io-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/core': workspace:3.0.1-alpha.0 + '@jscad/io': workspace:3.0.1-alpha.0 + '@jscad/io-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 ava: ^4.3.3 c8: ^8.0.0 jszip: ^3.10.1 @@ -53,10 +53,10 @@ importers: packages/core: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/io': workspace:3.0.0-alpha.0 - '@jscad/io-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/io': workspace:3.0.1-alpha.0 + '@jscad/io-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 ava: ^4.3.3 c8: ^8.0.0 json5: 2.2.3 @@ -74,8 +74,8 @@ importers: packages/io/3mf-deserializer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-commonjs': ^23.0.4 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 @@ -103,9 +103,9 @@ importers: packages/io/3mf-serializer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/io-utils': workspace:^3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/io-utils': workspace:^3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-commonjs': ^23.0.4 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 @@ -132,8 +132,8 @@ importers: packages/io/dxf-deserializer: specifiers: - '@jscad/io-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/io-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-node-resolve': ^15.2.1 '@rollup/plugin-terser': ^0.4.3 ava: ^4.3.3 @@ -155,8 +155,8 @@ importers: packages/io/dxf-serializer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 ava: ^4.3.3 @@ -176,23 +176,23 @@ importers: packages/io/io: specifiers: - '@jscad/3mf-deserializer': workspace:3.0.0-alpha.0 - '@jscad/3mf-serializer': workspace:3.0.0-alpha.0 - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/dxf-deserializer': workspace:3.0.0-alpha.0 - '@jscad/dxf-serializer': workspace:3.0.0-alpha.0 - '@jscad/io-utils': workspace:3.0.0-alpha.0 - '@jscad/json-deserializer': workspace:3.0.0-alpha.0 - '@jscad/json-serializer': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 - '@jscad/obj-deserializer': workspace:3.0.0-alpha.0 - '@jscad/obj-serializer': workspace:3.0.0-alpha.0 - '@jscad/stl-deserializer': workspace:3.0.0-alpha.0 - '@jscad/stl-serializer': workspace:3.0.0-alpha.0 - '@jscad/svg-deserializer': workspace:3.0.0-alpha.0 - '@jscad/svg-serializer': workspace:3.0.0-alpha.0 - '@jscad/x3d-deserializer': workspace:3.0.0-alpha.0 - '@jscad/x3d-serializer': workspace:3.0.0-alpha.0 + '@jscad/3mf-deserializer': workspace:3.0.1-alpha.0 + '@jscad/3mf-serializer': workspace:3.0.1-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/dxf-deserializer': workspace:3.0.1-alpha.0 + '@jscad/dxf-serializer': workspace:3.0.1-alpha.0 + '@jscad/io-utils': workspace:3.0.1-alpha.0 + '@jscad/json-deserializer': workspace:3.0.1-alpha.0 + '@jscad/json-serializer': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 + '@jscad/obj-deserializer': workspace:3.0.1-alpha.0 + '@jscad/obj-serializer': workspace:3.0.1-alpha.0 + '@jscad/stl-deserializer': workspace:3.0.1-alpha.0 + '@jscad/stl-serializer': workspace:3.0.1-alpha.0 + '@jscad/svg-deserializer': workspace:3.0.1-alpha.0 + '@jscad/svg-serializer': workspace:3.0.1-alpha.0 + '@jscad/x3d-deserializer': workspace:3.0.1-alpha.0 + '@jscad/x3d-serializer': workspace:3.0.1-alpha.0 ava: ^4.3.3 c8: ^8.0.0 dependencies: @@ -219,7 +219,7 @@ importers: packages/io/io-utils: specifiers: - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 ava: ^4.3.3 c8: ^8.0.0 devDependencies: @@ -229,9 +229,9 @@ importers: packages/io/json-deserializer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/io-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/io-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 ava: ^4.3.3 @@ -254,8 +254,8 @@ importers: packages/io/json-serializer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 ava: ^4.3.3 @@ -275,8 +275,8 @@ importers: packages/io/obj-deserializer: specifiers: - '@jscad/io-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/io-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-node-resolve': ^15.2.1 '@rollup/plugin-terser': ^0.4.3 ava: ^4.3.3 @@ -298,8 +298,8 @@ importers: packages/io/obj-serializer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 ava: ^4.3.3 @@ -319,8 +319,8 @@ importers: packages/io/stl-deserializer: specifiers: - '@jscad/io-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/io-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-node-resolve': ^15.2.1 '@rollup/plugin-terser': ^0.4.3 ava: ^4.3.3 @@ -342,8 +342,8 @@ importers: packages/io/stl-serializer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 ava: ^4.3.3 @@ -363,9 +363,9 @@ importers: packages/io/svg-deserializer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/io-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/io-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-commonjs': ^23.0.4 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 @@ -392,8 +392,8 @@ importers: packages/io/svg-serializer: specifiers: - '@jscad/io-utils': workspace:^3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/io-utils': workspace:^3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 ava: ^4.3.3 @@ -415,9 +415,9 @@ importers: packages/io/x3d-deserializer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/io-utils': workspace:3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/io-utils': workspace:3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-commonjs': ^23.0.4 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 @@ -444,9 +444,9 @@ importers: packages/io/x3d-serializer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 - '@jscad/io-utils': workspace:^3.0.0-alpha.0 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 + '@jscad/io-utils': workspace:^3.0.1-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3 ava: ^4.3.3 @@ -503,9 +503,9 @@ importers: packages/utils/regl-renderer: specifiers: - '@jscad/array-utils': workspace:3.0.0-alpha.0 + '@jscad/array-utils': workspace:3.0.1-alpha.0 '@jscad/img-utils': workspace:2.0.5 - '@jscad/modeling': workspace:3.0.0-alpha.0 + '@jscad/modeling': workspace:3.0.1-alpha.0 '@rollup/plugin-commonjs': ^23.0.4 '@rollup/plugin-node-resolve': ^15.0.1 '@rollup/plugin-terser': ^0.4.3