openstamanager/assets/src/js/wacom/sigCaptDialog/libs/will/digital-ink/workers/InkPathProvider.mjs

2 lines
116 KiB
JavaScript
Executable File

import"js-ext";import{vec2 as t,vec3 as e,vec4 as i,mat4 as s,quat2 as r,mat2d as n}from"gl-matrix";import a from"long";import*as o from"js-md5";import*as h from"poly2tri";import*as l from"clipper-lib";"function"==typeof Worker&&(Worker.prototype.on=function(t,e){this[`on${t}`]=i=>{let s="message"==t?i.data:i;e(s)}}),"function"==typeof DedicatedWorkerGlobalScope&&(DedicatedWorkerGlobalScope.prototype.on=function(t,e){this[`on${t}`]=i=>{let s="message"==t?i.data:i;e(s)}});class u{constructor(s,r,n,a){if(isNaN(s))throw new Error(`Invalid x found: ${s}`);if(isNaN(r))throw new Error(`Invalid y found: ${r}`);let o=[s,r];isFinite(n)&&(o.push(n),isFinite(a)&&o.push(a)),this.value=o.toFloat32Array(),Object.defineProperty(this,"x",{get:()=>this.value[0],set:t=>{this.value[0]=t},enumerable:!0}),Object.defineProperty(this,"y",{get:()=>this.value[1],set:t=>{this.value[1]=t},enumerable:!0}),2==o.length?this.vec=t:3==o.length?(this.vec=e,Object.defineProperty(this,"z",{get:()=>this.value[2],set:t=>{this.value[2]=t},enumerable:!0})):(this.vec=i,Object.defineProperty(this,"w",{get:()=>this.value[3],set:t=>{this.value[3]=t},enumerable:!0}))}add(t){t instanceof u||(t=u.fromPoint(t));let e=this.vec.create();return this.vec.add(e,this.value,t.value),u.fromPoint(e)}addSelf(t){return t instanceof u||(t=u.fromPoint(t)),this.vec.add(this.value,this.value,t.value),this}subtract(t){t instanceof u||(t=u.fromPoint(t));let e=this.vec.create();return this.vec.subtract(e,this.value,t.value),u.fromPoint(e)}subtractSelf(t){return t instanceof u||(t=u.fromPoint(t)),this.vec.subtract(this.value,this.value,t.value),this}multiply(t){t instanceof u||(t=u.fromPoint(t));let e=this.vec.create();return this.vec.multiply(e,this.value,t.value),u.fromPoint(e)}multiplySelf(t){return t instanceof u||(t=u.fromPoint(t)),this.vec.multiply(this.value,this.value,t.value),this}divide(t){t instanceof u||(t=u.fromPoint(t));let e=this.vec.create();return this.vec.divide(e,this.value,t.value),u.fromPoint(e)}divideSelf(t){return t instanceof u||(t=u.fromPoint(t)),this.vec.divide(this.value,this.value,t.value),this}scale(t){let e=this.vec.create();return this.vec.scale(e,this.value,t),u.fromPoint(e)}scaleSelf(t){return this.vec.scale(this.value,this.value,t),this}abs(){return new u(Math.abs(this.x),Math.abs(this.y),isFinite(this.z)?Math.abs(this.z):void 0,isFinite(this.w)?Math.abs(this.w):void 0)}absSelf(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),isFinite(this.z)&&(this.z=Math.abs(this.z)),isFinite(this.w)&&(this.w=Math.abs(this.w)),this}transform(t){if(!t)return this;let e=this.vec.create();return this.vec.transformMat4(e,this.value,t.toFloat32Array()),u.fromPoint(e)}transformSelf(t){return this.vec.transformMat4(this.value,this.value,t.toFloat32Array()),this}toFloat32Array(){return this.value}toJSON(){let t={x:this.x,y:this.y};return isFinite(this.z)&&(t.z=this.z,isFinite(this.w)&&(t.w=this.w)),t}toString(){return`point(${this.value.join(", ")})`}clone(){return u.fromPoint(this)}static fromPoint(t){return Array.isArray(t)||ArrayBuffer.isTypedArray(t)?new u(t[0],t[1],t[2],t[3]):new u(t.x,t.y,t.z,t.w)}}const c={m11:0,m12:1,m13:2,m14:3,m21:4,m22:5,m23:6,m24:7,m31:8,m32:9,m33:10,m34:11,m41:12,m42:13,m43:14,m44:15},p=c.m11,d=c.m12,f=c.m21,m=c.m22,g=c.m41,y=c.m42;class P{constructor(t=s.create(),e=P.MultiplicationType.PRE){Object.defineProperty(this,"value",{value:t,enumerable:!0}),Object.defineProperty(this,"multiplicationType",{value:e,enumerable:!0});let i=function(t,e){let i=c[t];this.value[i]=e};Object.defineProperty(this,"a",{get:()=>this.value[p],set:i.bind(this,"m11"),enumerable:!0}),Object.defineProperty(this,"b",{get:()=>this.value[d],set:i.bind(this,"m12"),enumerable:!0}),Object.defineProperty(this,"c",{get:()=>this.value[f],set:i.bind(this,"m21"),enumerable:!0}),Object.defineProperty(this,"d",{get:()=>this.value[m],set:i.bind(this,"m22"),enumerable:!0}),Object.defineProperty(this,"e",{get:()=>this.value[g],set:i.bind(this,"m41"),enumerable:!0}),Object.defineProperty(this,"f",{get:()=>this.value[y],set:i.bind(this,"m42"),enumerable:!0}),Object.defineProperty(this,"tx",{get:()=>this.value[g],set:i.bind(this,"m41"),enumerable:!0}),Object.defineProperty(this,"ty",{get:()=>this.value[y],set:i.bind(this,"m42"),enumerable:!0}),Object.defineProperty(this,"m11",{get:()=>this.value[0],set:i.bind(this,"m11"),enumerable:!0}),Object.defineProperty(this,"m12",{get:()=>this.value[1],set:i.bind(this,"m12"),enumerable:!0}),Object.defineProperty(this,"m13",{get:()=>this.value[2],set:i.bind(this,"m13"),enumerable:!0}),Object.defineProperty(this,"m14",{get:()=>this.value[3],set:i.bind(this,"m14"),enumerable:!0}),Object.defineProperty(this,"m21",{get:()=>this.value[4],set:i.bind(this,"m21"),enumerable:!0}),Object.defineProperty(this,"m22",{get:()=>this.value[5],set:i.bind(this,"m22"),enumerable:!0}),Object.defineProperty(this,"m23",{get:()=>this.value[6],set:i.bind(this,"m23"),enumerable:!0}),Object.defineProperty(this,"m24",{get:()=>this.value[7],set:i.bind(this,"m24"),enumerable:!0}),Object.defineProperty(this,"m31",{get:()=>this.value[8],set:i.bind(this,"m31"),enumerable:!0}),Object.defineProperty(this,"m32",{get:()=>this.value[9],set:i.bind(this,"m32"),enumerable:!0}),Object.defineProperty(this,"m33",{get:()=>this.value[10],set:i.bind(this,"m33"),enumerable:!0}),Object.defineProperty(this,"m34",{get:()=>this.value[11],set:i.bind(this,"m34"),enumerable:!0}),Object.defineProperty(this,"m41",{get:()=>this.value[12],set:i.bind(this,"m41"),enumerable:!0}),Object.defineProperty(this,"m42",{get:()=>this.value[13],set:i.bind(this,"m42"),enumerable:!0}),Object.defineProperty(this,"m43",{get:()=>this.value[14],set:i.bind(this,"m43"),enumerable:!0}),Object.defineProperty(this,"m44",{get:()=>this.value[15],set:i.bind(this,"m44"),enumerable:!0}),Object.defineProperty(this,"isIdentity",{get:()=>1==this.a&&0==this.b&&0==this.c&&1==this.d&&0==this.tx&&0==this.ty,enumerable:!0}),Object.defineProperty(this,"is2D",{get:()=>!(0!=this.m31||0!=this.m32||0!=this.m13||0!=this.m23||1!=this.m33||0!=this.m43||0!=this.m14||0!=this.m24||0!=this.m34||1!=this.m44),enumerable:!0}),Object.defineProperty(this,"translateX",{get:()=>this.tx}),Object.defineProperty(this,"translateY",{get:()=>this.ty}),Object.defineProperty(this,"skewX",{get:()=>Math.tan(this.c)}),Object.defineProperty(this,"skewY",{get:()=>Math.tan(this.b)}),Object.defineProperty(this,"scaleX",{get:()=>Math.sqrt(this.a*this.a+this.c*this.c)}),Object.defineProperty(this,"scaleY",{get:()=>Math.sqrt(this.d*this.d+this.b*this.b)}),Object.defineProperty(this,"rotation",{get:()=>Math.atan2(this.b,this.a)})}clone(){return new P(this.value.clone(),this.multiplicationType)}translate(t){return this.multiply(P.fromTranslate(t))}translateSelf(t){this.multiplySelf(P.fromTranslate(t))}rotate(t,e){return this.multiply(P.fromRotate(t,e))}rotateSelf(t,e){this.multiplySelf(P.fromRotate(t,e))}scale(t,e){return this.multiply(P.fromScale(t,e))}scaleSelf(t,e){this.multiplySelf(P.fromScale(t,e))}multiply(t){return this.multiplicationType==P.MultiplicationType.PRE?this.preMultiply(t):this.postMultiply(t)}preMultiply(t){let e=s.create();return s.multiply(e,t.toFloat32Array(),this.value),new P(e,this.multiplicationType)}postMultiply(t){let e=s.create();return s.multiply(e,this.value,t.toFloat32Array()),new P(e,this.multiplicationType)}multiplySelf(t){this.multiplicationType==P.MultiplicationType.PRE?this.preMultiplySelf(t):this.postMultiplySelf(t)}preMultiplySelf(t){s.multiply(this.value,t.toFloat32Array(),this.value)}postMultiplySelf(t){s.multiply(this.value,this.value,t.toFloat32Array())}invert(){let t=s.create();return s.invert(t,this.value),new P(t,this.multiplicationType)}invertSelf(){s.invert(this.value,this.value)}decompose(){return{translate:{x:this.tx,y:this.ty},rotate:{angle:Math.atan2(this.b,this.a)},skew:{angleX:Math.tan(this.c),angleY:Math.tan(this.b)},scale:{x:Math.sqrt(this.a*this.a+this.c*this.c),y:Math.sqrt(this.d*this.d+this.b*this.b)},matrix:this.toJSON()}}transformPoint(t){return u.fromPoint(t).transform(this)}toFloat32Array(){return this.value}toJSON(){return{a:this.a,b:this.b,c:this.c,d:this.d,tx:this.tx,ty:this.ty}}toString(t){if(t){let t=t=>((t<0?"":" ")+t.toPrecision(6)).substring(0,8);return" Matrix 4x4\n"+"-".repeat(39)+`\n${t(this.m11)}, ${t(this.m21)}, ${t(this.m31)}, ${t(this.m41)}`+`\n${t(this.m12)}, ${t(this.m22)}, ${t(this.m32)}, ${t(this.m42)}`+`\n${t(this.m13)}, ${t(this.m23)}, ${t(this.m33)}, ${t(this.m43)}`+`\n${t(this.m14)}, ${t(this.m24)}, ${t(this.m34)}, ${t(this.m44)}`}return this.is2D?`matrix(${this.a}, ${this.b}, ${this.c}, ${this.d}, ${this.tx}, ${this.ty})`:`matrix3d(${this.m11}, ${this.m12}, ${this.m13}, ${this.m14}, ${this.m21}, ${this.m22}, ${this.m23}, ${this.m24}, ${this.m31}, ${this.m32}, ${this.m33}, ${this.m34}, ${this.m41}, ${this.m42}, ${this.m43}, ${this.m44})`}static fromString(t,e){let i=s.create();if("none"!=t){let e=t.substring(0,t.indexOf("("));t=t.substring(t.indexOf("(")+1,t.indexOf(")")).split(/,\s*/g),"matrix3d"==e?(i[0]=parseFloat(t[0]),i[1]=parseFloat(t[1]),i[2]=parseFloat(t[2]),i[3]=parseFloat(t[3]),i[4]=parseFloat(t[4]),i[5]=parseFloat(t[5]),i[6]=parseFloat(t[6]),i[7]=parseFloat(t[7]),i[8]=parseFloat(t[8]),i[9]=parseFloat(t[9]),i[10]=parseFloat(t[10]),i[11]=parseFloat(t[11]),i[12]=parseFloat(t[12]),i[13]=parseFloat(t[13]),i[14]=parseFloat(t[14]),i[15]=parseFloat(t[15])):(i[p]=parseFloat(t[0]),i[d]=parseFloat(t[1]),i[f]=parseFloat(t[2]),i[m]=parseFloat(t[3]),i[g]=parseFloat(t[4]),i[y]=parseFloat(t[5]))}return new P(i,e)}static fromMatrix(t,e){if(!t)throw new Error("data not found, Matrix instance creation failed");if("function"==typeof t)throw new Error("data type function is not allowed");if(t instanceof P)return t;if(Array.isArray(t)&&(t=new Float32Array(t)),t instanceof Float32Array)return new P(t,e);if("string"==typeof t)return P.fromString(t,e);let i=s.create(),r=Object.assign({},t);return isFinite(t.a)&&(r.m11=t.a),isFinite(t.b)&&(r.m12=t.b),isFinite(t.c)&&(r.m21=t.c),isFinite(t.d)&&(r.m22=t.d),isFinite(t.tx)?r.m41=t.tx:isFinite(t.e)?r.m41=t.e:isFinite(t.dx)&&(r.m41=t.dx),isFinite(t.ty)?r.m42=t.ty:isFinite(t.f)?r.m42=t.f:isFinite(t.dy)&&(r.m42=t.dy),isFinite(r.m11)&&(i[0]=r.m11),isFinite(r.m12)&&(i[1]=r.m12),isFinite(r.m13)&&(i[2]=r.m13),isFinite(r.m14)&&(i[3]=r.m14),isFinite(r.m21)&&(i[4]=r.m21),isFinite(r.m22)&&(i[5]=r.m22),isFinite(r.m23)&&(i[6]=r.m23),isFinite(r.m24)&&(i[7]=r.m24),isFinite(r.m31)&&(i[8]=r.m31),isFinite(r.m32)&&(i[9]=r.m32),isFinite(r.m33)&&(i[10]=r.m33),isFinite(r.m34)&&(i[11]=r.m34),isFinite(r.m41)&&(i[12]=r.m41),isFinite(r.m42)&&(i[13]=r.m42),isFinite(r.m43)&&(i[14]=r.m43),isFinite(r.m44)&&(i[15]=r.m44),new P(i,e||t.multiplicationType)}static fromTranslate(t){let e=isFinite(t)?{tx:t,ty:t}:{tx:t.x,ty:t.y};return P.fromMatrix(e)}static fromRotate(t,e){let i=Math.sin(t),s=Math.cos(t),r={a:s,b:i,c:-i,d:s};return e&&(r.tx=e.x-e.x*s+e.y*i,r.ty=e.y-e.x*i-e.y*s),P.fromMatrix(r)}static fromScale(t,e){isFinite(t)&&(t={x:t,y:t});let i={a:t.x,d:t.y};return e&&(i.tx=e.x-e.x*t.x,i.ty=e.y-e.y*t.y),P.fromMatrix(i)}static fromPoints(t,e){if(!Array.isArray(t)||!Array.isArray(e))throw new Error("Expected input type Array requirement not satisfied");if(3!=t.length||3!=e.length)throw new Error("Expected input size 3 requirement not satisfied");let i=P.fromMatrix({m11:t[0].x,m21:t[1].x,m31:t[2].x,m12:t[0].y,m22:t[1].y,m32:t[2].y,m13:1,m23:1,m33:1}),s=P.fromMatrix({m11:e[0].x,m21:e[1].x,m31:e[2].x,m12:e[0].y,m22:e[1].y,m32:e[2].y,m13:1,m23:1,m33:1}),r=i.invert().preMultiply(s);return P.fromMatrix({a:r.m11,b:r.m12,c:r.m21,d:r.m22,tx:r.m31,ty:r.m32})}static multiply(t,e){let i=s.create();return s.multiply(i,t.value,e.value),new P(i)}}P.MultiplicationType=Object.freeze({PRE:"PRE",POST:"POST"});class b extends u{static defaults={size:1,rotation:0,scaleX:1,scaleY:1,scaleZ:1,offsetX:0,offsetY:0,offsetZ:0};constructor(t,e,i,s={}){super(t,e,i),this.red=s.red,this.green=s.green,this.blue=s.blue,this.alpha=s.alpha,this.size=s.size||b.defaults.size,this.rotation=s.rotation||b.defaults.rotation,this.scaleX=s.scaleX||b.defaults.scaleX,this.scaleY=s.scaleY||b.defaults.scaleY,this.scaleZ=isFinite(i)?s.scaleZ||b.defaults.scaleZ:void 0,this.offsetX=s.offsetX||b.defaults.offsetX,this.offsetY=s.offsetY||b.defaults.offsetY,this.offsetZ=isFinite(i)?s.offsetZ||b.defaults.offsetZ:void 0,this.dX,this.dY}static createInstance(t,e,i,s=0){let r=new b(0,0,t.includes(b.Property.Z)?0:void 0);return i&&r.fill(s,i,t,e),r}fill(t,e,i,s={}){let r={},n=t*i.length;i.forEach(((t,i)=>b.setProperty(r,t,e[n+i]))),this.x=r.x,this.y=r.y,this.z=r.z,this.red=isFinite(r.red)?r.red:s.red,this.green=isFinite(r.green)?r.green:s.green,this.blue=isFinite(r.blue)?r.blue:s.blue,this.alpha=isFinite(r.alpha)?r.alpha:s.alpha,this.size=r.size||s.size||b.defaults.size,this.rotation=r.rotation||s.rotation||b.defaults.rotation,this.scaleX=r.scaleX||s.scaleX||b.defaults.scaleX,this.scaleY=r.scaleY||s.scaleY||b.defaults.scaleY,this.scaleZ=isFinite(r.z)?r.scaleZ||s.scaleZ||b.defaults.scaleZ:void 0,this.offsetX=r.offsetX||s.offsetX||b.defaults.offsetX,this.offsetY=r.offsetY||s.offsetY||b.defaults.offsetY,this.offsetZ=isFinite(r.z)?r.offsetZ||s.offsetZ||b.defaults.offsetZ:void 0,this.dX=r.dX,this.dY=r.dY}getProperty(t){switch(t){case b.Property.X:return this.x;case b.Property.Y:return this.y;case b.Property.Z:return this.z;case b.Property.RED:return this.red;case b.Property.GREEN:return this.green;case b.Property.BLUE:return this.blue;case b.Property.ALPHA:return this.alpha;case b.Property.SIZE:return this.size;case b.Property.ROTATION:return this.rotation;case b.Property.SCALE_X:return this.scaleX;case b.Property.SCALE_Y:return this.scaleY;case b.Property.SCALE_Z:return this.scaleZ;case b.Property.OFFSET_X:return this.offsetX;case b.Property.OFFSET_Y:return this.offsetY;case b.Property.OFFSET_Z:return this.offsetZ;case b.Property.D_X:return this.dX;case b.Property.D_Y:return this.dY;default:throw console.warn(t),new Error("Invalid property found")}}setProperty(t,e){b.setProperty(this,t,e)}static setProperty(t,e,i){switch(e){case b.Property.X:t.x=i;break;case b.Property.Y:t.y=i;break;case b.Property.Z:t.z=i;break;case b.Property.RED:t.red=i;break;case b.Property.GREEN:t.green=i;break;case b.Property.BLUE:t.blue=i;break;case b.Property.ALPHA:t.alpha=i;break;case b.Property.SIZE:t.size=i;break;case b.Property.ROTATION:t.rotation=i;break;case b.Property.SCALE_X:t.scaleX=i;break;case b.Property.SCALE_Y:t.scaleY=i;break;case b.Property.SCALE_Z:t.scaleZ=i;break;case b.Property.OFFSET_X:t.offsetX=i;break;case b.Property.OFFSET_Y:t.offsetY=i;break;case b.Property.OFFSET_Z:t.offsetZ=i;break;case b.Property.D_X:t.dX=i;break;case b.Property.D_Y:t.dY=i;break;default:throw console.warn(e),new Error("Invalid property found")}}transform(t){if(!(t instanceof P))throw new Error(`matrix is instance of ${t.constructor.name} - it should be instance of Matrix. Use Matrix.fromMatrix method to convert.`);let e=t.scaleX,i=t.rotation;this.transformSelf(t),this.size*=e,this.rotation+=i}toArray(t){return t.map((t=>{let e=this.getProperty(t);if(null==e||isNaN(e))throw new Error(`Property ${t.name} has invalid value ${e}`);return e}))}toJSON(){let t={};return b.Property.values.forEach((e=>{let i=this.getProperty(e);null!=i&&isFinite(i)&&(t[e.name]=this.getProperty(e))})),t}}Object.defineEnum(b,"Property",["X","Y","Z","RED","GREEN","BLUE","ALPHA","SIZE","ROTATION","SCALE_X","SCALE_Y","SCALE_Z","OFFSET_X","OFFSET_Y","OFFSET_Z","D_X","D_Y"]);class E{constructor(t,e,i){Object.defineProperties(this,{path:{value:t,enumerable:!0},pointIndexStart:{value:e,enumerable:!0},pointIndexEnd:{value:i,enumerable:!0}}),this.validate()}validate(){if(this.pointIndexStart<0)throw new Error(`Invalid fragment pointIndexStart ${this.pointIndexStart} found. The value must be non-negative.`);if(this.pointIndexEnd>this.path.length-1)throw new Error(`Invalid fragment pointIndexEnd ${this.pointIndexEnd} found. Last point in path index is ${this.path.length-1}.`)}toPath(){return this.path.slice(this)}toString(){return`fragment(${this.pointIndexStart} - ${this.pointIndexEnd})`}}class S{constructor(t,e,i,s=1){if(this.red=t,this.green=e,this.blue=i,this.alpha=s,s<0||s>1)throw new Error(`Invalid alpha ${s} found. The value must be in the interval [0, 1].`);Object.defineProperty(this,"hex",{get:()=>`#${this.red.toString(16).pad(2,"0")}${this.green.toString(16).pad(2,"0")}${this.blue.toString(16).pad(2,"0")}${Math.round(255*this.alpha).toString(16).pad(2,"0")}`,enumerable:!0})}premultiply(){return{red:this.red/255*this.alpha,green:this.green/255*this.alpha,blue:this.blue/255*this.alpha,alpha:this.alpha}}static postdivide(t,e,i,s){let r=parseInt(255*t/s),n=parseInt(255*e/s),a=parseInt(255*i/s);return new S(r,n,a,s)}equals(t){return t&&this.red==t.red&&this.green==t.green&&this.blue==t.blue&&this.alpha==t.alpha}toRGB(){return 1==this.alpha?this:new S(this.red,this.green,this.blue)}toRGBA(t){return new S(this.red,this.green,this.blue,t)}toHSLA(){let t=this.red/255,e=this.green/255,i=this.blue/255,s=Math.min(t,e,i),r=Math.max(t,e,i),n=0,a=0,o=(r+s)/2;if(r!=s){let h=r-s;switch(a=h/(1-Math.abs(2*o-1)),r){case t:n=(e-i)/h%6;break;case e:n=(i-t)/h+2;break;case i:n=(t-e)/h+4}}return n*=60,n<0&&(n+=360),{hue:parseFloat(n.toFixed(0)),saturation:parseFloat((100*a).toFixed(2)),lightness:parseFloat((100*o).toFixed(2)),alpha:this.alpha}}toArray(){return[this.red,this.green,this.blue,this.alpha]}toJSON(){return{red:this.red,green:this.green,blue:this.blue,alpha:this.alpha}}toString(){return 1==this.alpha?`rgb(${this.red}, ${this.green}, ${this.blue})`:`rgba(${this.red}, ${this.green}, ${this.blue}, ${this.alpha})`}static isColor(t){return t&&isFinite(t.red)&&isFinite(t.green)&&isFinite(t.blue)}static fromColor(t){let e,i,s,r;if("string"==typeof t)if(t.startsWith("rgb"))t=t.substring(t.indexOf("(")+1,t.indexOf(")")).split(/,\s*/g),e=parseInt(t[0]),i=parseInt(t[1]),s=parseInt(t[2]),r=t[3]?parseInt(t[3]):1;else{if(!t.startsWith("#"))throw new Error(`Unknown input found: ${t}. Expected data starts with rgba, rgb or #.`);t=t.substring(1),e=parseInt(t.substring(0,2),16),i=parseInt(t.substring(2,4),16),s=parseInt(t.substring(4,6),16),r=8==t.length?parseInt(t.substring(6,8),16)/255:1}else Array.isArray(t)?(e=t[0],i=t[1],s=t[2],r=t[3]):(e=t.red,i=t.green,s=t.blue,r=t.alpha);return new S(e,i,s,r)}static fromHSLA(t=0,e=0,i=0,s){t/=60,e/=100,i/=100;let r=(1-Math.abs(2*i-1))*e,n=r*(1-Math.abs(t%2-1)),a=0,o=0,h=0;t>=0&&t<1?(a=r,o=n):t>=1&&t<2?(a=n,o=r):t>=2&&t<3?(o=r,h=n):t>=3&&t<4?(o=n,h=r):t>=4&&t<5?(a=n,h=r):(a=r,h=n);let l=i-r/2;return a+=l,o+=l,h+=l,new S(Math.round(255*a),Math.round(255*o),Math.round(255*h),s)}static random(t=!1){return new S(Math.randomInt(0,255),Math.randomInt(0,255),Math.randomInt(0,255),t?Math.random():1)}}S.TRANSPERENT=new S(0,0,0,0),S.BLACK=new S(0,0,0,1),S.WHITE=new S(255,255,255,1),S.RED=new S(255,0,0,1),S.GREEN=new S(0,255,0,1),S.BLUE=new S(0,0,255,1);let w={longToByteArray(t){let e=[0,0,0,0,0,0,0,0];for(let i=0;i<e.length;i++){let s=255&t;e[i]=s,t=(t-s)/256}return e},byteArrayToLong(t){let e=0;for(let i=t.length-1;i>=0;i--)e=256*e+t[i];return e},crc32:function(){let t=new Uint32Array(256);for(let e=256;e--;){let i=e;for(let t=8;t--;)i=1&i?3988292384^i>>>1:i>>>1;t[e]=i}return function(e){let i=-1;for(let s=0,r=e.length;s<r;s++)i=i>>>8^t[255&i^e[s]];return(-1^i)>>>0}}(),encodeBitMask(t=[]){if(0==t.length)return 0;let e="",i=Math.max(...t);for(let s=1;s<=i;s++)e+=t.includes(s)?"1":"0";return parseInt(e.split("").reverse().join(""),2)},decodeBitMask(t){let e=[],i=t.toString(2).split("").reverse();for(let t=0;t<i.length;t++)1==i[t]&&e.push(t+1);return e},mapTo:(t,e,i)=>i.min+(w.clamp(t,e)-e.min)/(e.max-e.min)*(i.max-i.min),clamp:(t,e)=>Math.min(Math.max(t,e.min),e.max),debounce(t,e){let i=null;return function(){let s=this,r=arguments;clearTimeout(i),i=setTimeout((function(){t.apply(s,r)}),e)}},comparator(){let t=Array.prototype.slice.call(arguments),e=function(t,e,i){return e.replace("[",".").replace("]","").split(".").forEach((e=>t=t[e])),i?t.toLowerCase():t};return function(i,s){return t.map((t=>function(t,e,i){let s="asc"===i?1:-1;return t>e?1*s:t<e?-1*s:0}(e(i,t.sortBy,t.ignoreCase),e(s,t.sortBy,t.ignoreCase),t.sortOrder))).reduceRight((function(t,e){return e||t}))}},isValidURL(t){if("string"!=typeof t)return!1;try{return new URL(t),!0}catch(t){return!1}},getPropName(t,e){let i=t.split("_"),s=i.first.toLowerCase();e&&(s=s.substring(0,1).toUpperCase()+s.substring(1));for(let t=1;t<i.length;t++)s+=i[t].substring(0,1),s+=i[t].substring(1).toLowerCase();return s},getEnumValueName(t){let e="";for(let i=0;i<t.length;i++)i>0&&t[i]!=t[i].toLowerCase()&&(e+="_"),e+=t[i];return e.toUpperCase()}};class I{constructor(t,e,i={}){this.layout=t,this.pointProps=e,this.sheet={};let s={};Object.defineProperties(s,{size:{get:this.getComputed.bind(this,"size"),set:this.setStyle.bind(this,"size"),enumerable:!0},red:{get:this.getComputed.bind(this,"red"),set:this.setStyle.bind(this,"red"),enumerable:!0},green:{get:this.getComputed.bind(this,"green"),set:this.setStyle.bind(this,"green"),enumerable:!0},blue:{get:this.getComputed.bind(this,"blue"),set:this.setStyle.bind(this,"blue"),enumerable:!0},alpha:{get:this.getComputed.bind(this,"alpha"),set:this.setStyle.bind(this,"alpha"),enumerable:!0},rotation:{get:this.getComputed.bind(this,"rotation"),set:this.setStyle.bind(this,"rotation"),enumerable:!0},scaleX:{get:this.getComputed.bind(this,"scaleX"),set:this.setStyle.bind(this,"scaleX"),enumerable:!0},scaleY:{get:this.getComputed.bind(this,"scaleY"),set:this.setStyle.bind(this,"scaleY"),enumerable:!0},scaleZ:{get:this.getComputed.bind(this,"scaleZ"),set:this.setStyle.bind(this,"scaleZ"),enumerable:!0},offsetX:{get:this.getComputed.bind(this,"offsetX"),set:this.setStyle.bind(this,"offsetX"),enumerable:!0},offsetY:{get:this.getComputed.bind(this,"offsetY"),set:this.setStyle.bind(this,"offsetY"),enumerable:!0},offsetZ:{get:this.getComputed.bind(this,"offsetZ"),set:this.setStyle.bind(this,"offsetZ"),enumerable:!0},color:{get:this.getComputed.bind(this,"color"),set:this.setStyle.bind(this,"color"),enumerable:!0},blendMode:{get:this.getComputed.bind(this,"blendMode"),set:this.setStyle.bind(this,"blendMode"),enumerable:!0},visibility:{get:this.getComputed.bind(this,"visibility"),set:this.setStyle.bind(this,"visibility"),enumerable:!0},reset:{value:t=>{t&&(i=t),this.clear(),Object.keys(i).forEach((t=>this.setStyle(t,i[t])))}},clear:{value:this.clear.bind(this)}}),this.style=Object.freeze(s),this.style.reset(i)}setStyle(t,e){if(null==e&&(e=void 0),I.validate(this.layout,t,e),"color"==t&&e)return this.sheet.red=e.red,this.sheet.green=e.green,this.sheet.blue=e.blue,void(this.sheet.alpha=e.alpha);null==e?delete this.sheet[t]:this.sheet[t]=e}getStyle(t){let e=this.sheet[t];return"visibility"==t?"boolean"!=typeof e&&(e=!0):"color"==t&&S.isColor(this.sheet)&&(e=S.fromColor(this.sheet)),e}getComputed(t){let e=this.getStyle(t);if(null==e)if("color"==t){let t={red:isFinite(this.sheet.red)?this.sheet.red:this.pointProps.red,green:isFinite(this.sheet.green)?this.sheet.green:this.pointProps.green,blue:isFinite(this.sheet.blue)?this.sheet.blue:this.pointProps.blue,alpha:isFinite(this.sheet.alpha)?this.sheet.alpha:this.pointProps.alpha};S.isColor(t)&&(e=S.fromColor(t))}else e=this.pointProps[t];return e}clear(){this.sheet={}}static validate(t,e,i,s){let r;if(i&&t.includes(b.Property[w.getEnumValueName(e)])){if(!s)throw new Error(`Property ${e} value ${i} is not applicable. This is a dynamic property and is part of the layout.`);console.warn(`Property ${e} value ${i} is not applicable. This is a dynamic property and is part of the layout.`),i=void 0}if("color"==e)!i||i instanceof S||(r=`Property ${e} is not an instance of Color`);else if("blendMode"==e)""==i&&(i=void 0);else if("number"==typeof i)if("size"==e)i<0?r=`Property ${e} with value ${i} is not allowed. Value should be a positive number.`:0==i&&(i=void 0);else if("red"==e||"green"==e||"blue"==e||"alpha"==e){let t="alpha"==e?{min:0,max:1}:{min:0,max:255};i>=t.min&&i<=t.max||(r=`Property ${e} with value ${i} is out of range. Allowd range: [${t.min}, ${t.max}].`)}else"rotation"==e?0==i&&(i=void 0):"scattering"==e&&i<0&&(i=void 0);if(r)throw new Error(r);return i}}class v{static encode(t,e=v.Encoding.AUTO){let i;if(e==v.Encoding.AUTO?e="undefined"==typeof Buffer?"undefined"!=typeof SharedArrayBuffer&&t.buffer instanceof SharedArrayBuffer?v.Encoding.NONE:v.Encoding.ARRAY:v.Encoding.BUFFER:e==v.Encoding.ARRAY&&t instanceof Array&&(e=v.Encoding.NONE),e==v.Encoding.NONE)i=t;else if(e==v.Encoding.ARRAY)i=t.toArray();else{if("undefined"==typeof Buffer)throw new Error("Buffer not found, unable to serialize. Please provide Buffer in global scope.");let s=Buffer.from(t.buffer);switch(e){case v.Encoding.BUFFER:i=s.toJSON();break;case v.Encoding.BASE64:i=s.toString("base64");break;default:throw new Error(`Invalid encoding provided: ${e.name}`)}}return{encoding:e.name,type:t.constructor.name,content:i}}static decode(t){let e,i=v.Encoding[t.encoding];if(i==v.Encoding.NONE)e=t.content;else if(i==v.Encoding.ARRAY)e=t.content.toFloat32Array();else{let s;switch(i){case v.Encoding.BUFFER:s="undefined"==typeof Buffer?t.content.data:Buffer.from(t.content);break;case v.Encoding.BASE64:s="undefined"==typeof Buffer?atob(t.content).toCharArray():Buffer.from(t.content,"base64");break;default:throw new Error(`Invalid encoding provided: ${i.name}`)}let r=new Uint8Array(s);e=new globalThis[t.type](r.buffer)}return e}static isTypedArrayData(t){return t&&t.encoding&&t.type&&t.type.endsWith("Array")}}Object.defineEnum(v,"Encoding",["AUTO","NONE","ARRAY","BUFFER","BASE64"]);const O=[b.Property.X,b.Property.Y];class x{#t;#e;constructor(t,e={},i=O){if(this.#t=t,Object.defineProperty(this,"points",{get:()=>this.#t,set:t=>{if(this.#t instanceof Float32Array)throw new Error("Points setter is not accessible wehn points type is Float32Array.");this.#t=t,this.validate()},enumerable:!0}),Object.defineProperty(this,"buffer",{get:()=>this.#t.buffer,set:t=>{if(Array.isArray(this.#t))throw new Error("Underlying points buffer is Array. This property is applicable for TypedArray only.");if("undefined"!=typeof SharedArrayBuffer&&this.#t.buffer instanceof SharedArrayBuffer)throw new Error("Underlying buffer is SharedArrayBuffer and cannot be restored");if(this.#t.buffer.byteLength>0)throw new Error("Cannot restore buffer when underlying buffer is not empty");if(t.byteLength/Float32Array.BYTES_PER_ELEMENT/this.stride!=this.length)throw new Error("Value exceeds expected memory length");this.#t=new Float32Array(t)}}),!Object.isSealed(e))for(let t in e)void 0!==e[t]&&(e[t]=I.validate(i,t,e[t],!0));i.includes(b.Property.ROTATION)||"rotation"in e||(e.rotation=void 0),i.includes(b.Property.SIZE)||e.size||(e.size=1),Object.defineProperties(this,{stride:{value:i.length,enumerable:!0},layout:{value:Object.freeze(i),enumerable:!0},pointProps:{value:Object.seal(e),enumerable:!0}}),t instanceof Float32Array?Object.defineProperty(this,"length",{value:this.#t.length/this.stride,enumerable:!0}):Object.defineProperty(this,"length",{get:()=>this.#t.length/this.stride,enumerable:!0}),i.forEach(((t,e)=>{let i=w.getPropName(t.name,!0);Object.defineProperty(this,`setPoint${i}`,{value:this.setPointPropertyValue.bind(this,e)}),Object.defineProperty(this,`getPoint${i}`,{value:this.getPointPropertyValue.bind(this,e)})}))}validate(){if(this.points.length%this.stride!=0)throw new Error("Path length doesn't match the stride provided via the layout")}setPointPropertyValue(t,e,i){if(isNaN(e))throw new Error("Point index is required");if(e>=this.length||e<0)throw new Error(`Index ${t} out of range - (0, ${this.length-1})`);if(isNaN(i))throw new Error("value is required");this.points[e*this.layout.length+t]=i}getPointPropertyValue(t,e){if(isNaN(e))throw new Error("Point index is required");if(e>=this.length||e<0)throw new Error(`Index ${t} out of range - (0, ${this.length-1})`);return this.points[e*this.layout.length+t]}setPoint(t,e){let i=t*this.stride;this.layout.forEach(((t,s)=>this.points[i+s]=e.getProperty(t)))}getPoint(t,e=this.pointProps){if(t>=this.length||t<0)throw new Error(`Index ${t} out of range - (0, ${this.length-1})`);return b.createInstance(this.layout,e,this.points,t)}getPointRef(t,e=this.pointProps){if(t>=this.length||t<0)throw new Error(`Index ${t} out of range - (0, ${this.length-1})`);return this.#e||(this.#e=b.createInstance(this.layout)),this.#e.fill(t,this.points,this.layout,this.pointProps),this.#e}getChannelData(t){let e=new([b.Property.RED,b.Property.GREEN,b.Property.BLUE].includes(t)?Uint8Array:Float32Array)(this.length),i=this.layout.indexOf(t);if(-1==i)throw new Error(`Property ${t.name} is not part from the spline layout ${this.layout.map((t=>t.name)).join(", ")}`);for(let t=0;t<this.length;t++)e[t]=this.points[t*this.stride+i];return e}transform(t){let e=t.scaleX,s=t.rotation;for(let r=0;r<this.length;r++){let n=r*this.stride,a=i.fromValues(this.getPointX(r),this.getPointY(r),0,1);i.transformMat4(a,a,t.value);for(let t=0;t<this.stride;t++){let i=n+t;switch(this.layout[t]){case b.Property.X:this.points[i]=a[0]/a[3];break;case b.Property.Y:this.points[i]=a[1]/a[3];break;case b.Property.Z:this.points[i]=a[2]/a[3];break;case b.Property.ROTATION:this.points[i]+=s;break;case b.Property.SIZE:this.points[i]*=e}}}this.layout.includes(b.Property.ROTATION)||(this.pointProps.rotation=0==s?void 0:s)}clone(){return new x(this.#t.clone(),Object.clone(this.pointProps),this.layout.slice())}getFragment(t=0,e=this.length-1){return new E(this,t,e)}slice(t){let e=this.slicePoints(t.pointIndexStart,t.pointIndexEnd);return new x(e,Object.clone(this.pointProps),this.layout.slice())}validateFragment(t,e){if(t<0)throw new Error(`Invalid fragment pointIndexStart ${t} found. The value must be non-negative.`);if(e>this.length-1)throw new Error(`Invalid fragment pointIndexEnd ${e} found. Last point in path index is ${this.length-1}.`)}slicePoints(t,e){let i;if(this.validateFragment(t,e),"undefined"!=typeof SharedArrayBuffer&&this.buffer instanceof SharedArrayBuffer){let s=this.points.subarray(t*this.stride,(e+1)*this.stride),r=new SharedArrayBuffer(s.length*Float32Array.BYTES_PER_ELEMENT);i=new Float32Array(r),i.set(s)}else i=this.points.slice(t*this.stride,(e+1)*this.stride);return i}toSVGPath(){let t=[];for(let e=0;e<this.length;e++)t.push(`${this.getPointX(e)},${this.getPointY(e)}`);return`M ${t.join(" L ")} Z`}toJSON(){return{type:"Path",points:v.encode(this.#t,this.encoding),pointProps:this.pointProps,layout:this.layout.map((t=>t.name))}}static fromJSON(t){if("Path"!=t.type)throw new Error(`Path deserialization failed. JSON type is ${t.type}, expected Path.`);return new x(v.decode(t.points),t.pointProps,t.layout.map((t=>b.Property[t])))}static fromRect(t,e){let i=[t.left,t.top,t.right,t.top,t.right,t.bottom,t.left,t.bottom,t.left,t.top];return new x(i,e)}static createInstance(t,e,i){return new x(t,e,i)}static createSharedInstance(t,e,i){return new x(Float32Array.createSharedInstance(t),e,i)}}class A{constructor(t,e){t>0&&0==e?(this.segmentIndex=t-1,this.t=1):(this.segmentIndex=t,this.t=e),Object.defineProperty(this,"index",{get:()=>(console.warn("SplineParameter index => segmentIndex"),this.segmentIndex)})}equals(t){return this.segmentIndex==t.segmentIndex&&this.t==t.t}toString(){return`spline-parameter(${this.segmentIndex}, ${this.t})`}toJSON(){return{segmentIndex:this.segmentIndex,t:this.t}}static fromJSON(t){return new A(t.segmentIndex,t.t)}static calcMiddleOfSegment(t,e){let i=.5*(t.t+e.t+(e.segmentIndex-t.segmentIndex)),s=Math.trunc(i),r=i-s;return new A(t.segmentIndex+s,r)}static areDistantEnough(t,e,i=.01){return e.t+(e.segmentIndex-t.segmentIndex)-t.t>i}}let R=o?o.default||globalThis.md5:{},T={mask:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",generate(){let t=Date.now();return this.mask.replace(/[xy]/g,(function(e){let i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)}))},validate:t=>"string"==typeof t&&!!t.match(/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/),format(t){let e=[],i=0;return this.mask.split("-").forEach((s=>{e.push(t.substring(i,i+s.length)),i+=s.length})),e.join("-")},fromString(t){return this.fromBytes(new Uint8Array(R.arrayBuffer(t)))},toBytes(t){let e=[];return t.split("-").map(((t,i)=>{(i<3?t.match(/.{1,2}/g).reverse():t.match(/.{1,2}/g)).map((t=>e.push(parseInt(t,16))))})),new Uint8Array(e)},fromBytes(t){let e=Array.from(t).map((t=>t.toString(16))).map((t=>(1==t.length?"0":"")+t));return e.slice(0,4).reverse().join("")+"-"+e.slice(4,6).reverse().join("")+"-"+e.slice(6,8).reverse().join("")+"-"+e.slice(8,10).join("")+"-"+e.slice(10).join("")},toUint32Array(t){let e=new Uint32Array(4),i=this.toBytes(t);return e[0]=new Uint32Array(i.slice(0,4).buffer)[0],e[1]=new Uint32Array(i.slice(4,8).buffer)[0],e[2]=new Uint32Array(i.slice(8,12).buffer)[0],e[3]=new Uint32Array(i.slice(12).buffer)[0],e},fromUint32Array(t){return this.fromBytes(new Uint8Array(t.buffer))},toUint64Array(t){let e=new BigUint64Array(2),i=this.toBytes(t);return e[0]=new BigUint64Array(i.slice(0,8).buffer)[0],e[1]=new BigUint64Array(i.slice(8).buffer)[0],e},fromUint64Array(t){return this.fromBytes(new Uint8Array(t.buffer))},toLongArray(t){let e=new Array(2),i=this.toBytes(t);return e[0]=a.fromBytes(i.slice(0,8)),e[1]=a.fromBytes(i.slice(8)),e},fromLongArray(t){let e=t[0].toBytes().concat(t[1].toBytes());return this.fromBytes(e)}};class N{#i;constructor(t,e,i,s,r){1==i&&(e++,i=0),0==r&&(s--,r=1),Object.defineProperties(this,{spline:{value:t,enumerable:!0},segmentIndexStart:{value:e,enumerable:!0},segmentIndexEnd:{value:s,enumerable:!0},ts:{value:i,enumerable:!0},tf:{value:r,enumerable:!0}}),Object.defineProperty(this,"pointIndexStart",{value:e,enumerable:!0}),Object.defineProperty(this,"pointIndexEnd",{value:s+3,enumerable:!0}),Object.defineProperty(this,"length",{value:this.pointIndexEnd-this.pointIndexStart+1,enumerable:!0}),Object.defineProperty(this,"id",{get:()=>(this.#i||(this.#i=T.generate()),this.#i),set:t=>{if(this.#i)throw new Error("id is immutable");this.#i=t}}),this.validate()}validate(){let t=this.length-3;if(this.pointIndexStart<0)throw new Error(`Invalid fragment pointIndexStart ${this.pointIndexStart} found. The value must be non-negative.`);if(this.pointIndexEnd>this.spline.length-1)throw new Error(`Invalid fragment pointIndexEnd ${this.pointIndexEnd} found. Last point in spline index is ${this.spline.length-1}.`);if(this.ts<0||this.ts>=1)throw new Error(`Invalid fragment ts ${this.ts} found. The value must be in the interval [0, 1).`);if(this.tf<=0||this.tf>1)throw new Error(`Invalid fragment tf ${this.tf} found. The value must be in the interval (0, 1].`);if(t<1)throw new Error(`Invalid fragment points range {${this.pointIndexStart}, ${this.pointIndexEnd}} found. At least 4 points are needed to define spline.`);if(1==t&&this.ts>this.tf)throw new Error(`Invalid fragment T range ${this.ts} - ${this.tf} found. Spline has only one segment and ts <= tf.`)}union(t){let e=[this,t];e.sort(N.compare);let i=e.first,s=e.last,r=i.segmentIndexEnd,n=i.tf;if(1==n&&(r++,n=0),r!=s.segmentIndexStart||n!=s.ts)throw new Error(`Fragments ${i} and ${s} are not adjacent.`);let a=new N(this.spline,i.segmentIndexStart,i.ts,s.segmentIndexEnd,s.tf);return a.#i=this.#i,this.inside&&(a.inside=this.inside),a}overlaps(t){if(t.spline!=this.spline)return!1;let e=t.segmentIndexStart<this.segmentIndexEnd||t.segmentIndexStart==this.segmentIndexEnd&&t.ts<=this.tf,i=t.segmentIndexEnd>this.segmentIndexStart||t.segmentIndexEnd==this.segmentIndexStart&&t.tf>=this.ts;return e&&i}toString(){return`fragment(${this.segmentIndexStart}, ${this.ts} - ${this.segmentIndexEnd}, ${this.tf})`}static compare(t,e){return t.segmentIndexStart<e.segmentIndexStart?-1:t.segmentIndexStart>e.segmentIndexStart?1:t.ts<e.ts?-1:t.ts>e.ts?1:0}static getInstance(t,e,i){return new N(t,e.segmentIndex,e.t,i.segmentIndex,i.t)}}class C{constructor(t,e,i,s){let r=t,n=e,a=t+i,o=e+s;Object.defineProperties(this,{left:{value:r,enumerable:!0},x:{value:t,enumerable:!0},bottom:{value:n,enumerable:!0},y:{value:e,enumerable:!0},right:{value:a,enumerable:!0},top:{value:o,enumerable:!0},width:{value:i,enumerable:!0},height:{value:s,enumerable:!0}})}union(t){if(t&&!(t instanceof C))throw new TypeError("rect must be instance of RectGL");return t?C.ofEdges(Math.min(this.left,t.left),Math.min(this.bottom,t.bottom),Math.max(this.right,t.right),Math.max(this.top,t.top)):this}intersect(t){if(t&&!(t instanceof C))throw new TypeError("rect must be instance of RectGL");if(!t)return null;let e=C.ofEdges(Math.max(this.left,t.left),Math.max(this.bottom,t.bottom),Math.min(this.right,t.right),Math.min(this.top,t.top));return e.width>0&&e.height>0?e:null}ceil(){return C.ofEdges(Math.floor(this.left),Math.floor(this.bottom),Math.ceil(this.right),Math.ceil(this.top))}floor(){return C.ofEdges(Math.ceil(this.left),Math.ceil(this.bottom),Math.floor(this.right),Math.floor(this.top))}transform(t){if(!t)return this;let e=u.fromPoint({x:this.left,y:this.bottom}).transform(t),i=u.fromPoint({x:this.right,y:this.bottom}).transform(t),s=u.fromPoint({x:this.left,y:this.top}).transform(t),r=u.fromPoint({x:this.right,y:this.top}).transform(t),n=Math.min(s.x,r.x,e.x,i.x),a=Math.min(s.y,r.y,e.y,i.y),o=Math.max(s.x,r.x,e.x,i.x),h=Math.max(s.y,r.y,e.y,i.y);return C.ofEdges(n,a,o,h)}toQuad(t){let e;if(t){let i=u.fromPoint({x:this.left,y:this.bottom}).transform(t),s=u.fromPoint({x:this.right,y:this.bottom}).transform(t),n=u.fromPoint({x:this.left,y:this.top}).transform(t),a=u.fromPoint({x:this.right,y:this.top}).transform(t);e=r.fromValues(i.x,i.y,s.x,s.y,n.x,n.y,a.x,a.y)}else e=r.fromValues(this.left,this.bottom,this.right,this.bottom,this.left,this.top,this.right,this.top);return e}toString(){return`gl-rect(${this.x}, ${this.y}, ${this.width}, ${this.height})`}static ofEdges(t,e,i,s){return new C(t,e,i-t,s-e)}static calculateBrushGLSegmentBounds(t,e=0,i){let s,r=.5*t.size,n=Math.abs(e*r);if(i){s=new u(t.x,t.y,t.x,t.z).transform(i)}else s=t;let a=s.x,o=s.y,h=t.scaleX*r,l=t.scaleY*r,c=t.offsetX,p=-t.offsetY,d=Math.cos(t.rotation),f=Math.sin(t.rotation),m=Number.MAX_SAFE_INTEGER,g=Number.MIN_SAFE_INTEGER,y=Number.MAX_SAFE_INTEGER,P=Number.MIN_SAFE_INTEGER;for(let t of C.SQURE){let e=t.x*h+c,i=t.y*l+p,s=d*e+f*i+a,r=-f*e+d*i+o,u=s-n;m=Math.min(m,u),g=Math.max(g,u),u=s+n,m=Math.min(m,u),g=Math.max(g,u);let b=r-n;y=Math.min(y,b),P=Math.max(P,b),b=r+n,y=Math.min(y,b),P=Math.max(P,b)}return C.ofEdges(m,y,g,P)}}Object.defineProperty(C,"SQURE",{value:Object.freeze([Object.freeze({x:-1,y:-1}),Object.freeze({x:1,y:-1}),Object.freeze({x:-1,y:1}),Object.freeze({x:1,y:1})]),enumerable:!0});class D{constructor(t,e,i,s){let r,n,a,o=t,h=e,l=t+i,u=e+s;Object.defineProperties(this,{left:{value:o,enumerable:!0},top:{value:h,enumerable:!0},right:{value:l,enumerable:!0},bottom:{value:u,enumerable:!0},x:{value:t,enumerable:!0},y:{value:e,enumerable:!0},width:{value:i,enumerable:!0},height:{value:s,enumerable:!0},size:{get:()=>(r||(r={width:i,height:s}),r),enumerable:!0},area:{get:()=>(n||(n=i*s),n),enumerable:!0},center:{get:()=>(a||(a={x:(o+l)/2,y:(h+u)/2}),a),enumerable:!0}})}union(t){return t?D.ofEdges(Math.min(this.left,t.left),Math.min(this.top,t.top),Math.max(this.right,t.right),Math.max(this.bottom,t.bottom)):this}intersect(t){if(!t)return null;let e=D.ofEdges(Math.max(this.left,t.left),Math.max(this.top,t.top),Math.min(this.right,t.right),Math.min(this.bottom,t.bottom));return e.width>0&&e.height>0?e:null}intersects(t){return this.left<=t.right&&this.right>=t.left&&this.top<=t.bottom&&this.bottom>=t.top}ceil(t){let e=Math.floor(this.left),i=Math.floor(this.top),s=Math.ceil(this.right),r=Math.ceil(this.bottom);if(t){let t=s-e,n=r-i;t+=t%2,n+=n%2,s=e+t,r=i+n}return D.ofEdges(e,i,s,r)}floor(t){let e=Math.ceil(this.left),i=Math.ceil(this.top),s=Math.floor(this.right),r=Math.floor(this.bottom);if(t){let t=s-e,n=r-i;t-=t%2,n-=n%2,s=e+t,r=i+n}return D.ofEdges(e,i,s,r)}contains(t){return this.left<=t.x&&this.right>=t.x&&this.top<=t.y&&this.bottom>=t.y}includes(t){return this.left<=t.left&&this.right>=t.right&&this.top<=t.top&&this.bottom>=t.bottom}transform(t){if(!t)return this;let e=u.fromPoint({x:this.left,y:this.top}).transform(t),i=u.fromPoint({x:this.right,y:this.top}).transform(t),s=u.fromPoint({x:this.left,y:this.bottom}).transform(t),r=u.fromPoint({x:this.right,y:this.bottom}).transform(t),n=Math.min(e.x,i.x,s.x,r.x),a=Math.min(e.y,i.y,s.y,r.y),o=Math.max(e.x,i.x,s.x,r.x),h=Math.max(e.y,i.y,s.y,r.y);return D.ofEdges(n,a,o,h)}toPath(t,e=1){throw new Error("Rect.toPath is deprecated. Path.fromRect(rect, [pointProps]) instead")}toGLRect(){return new C(this.x,this.y,this.width,this.height)}toString(){return`rect(${this.x}, ${this.y}, ${this.width}, ${this.height})`}toJSON(){return{x:this.left,y:this.top,width:this.width,height:this.height}}static fromGLRect(t){if(!t)return null;if(!(t instanceof C))throw new TypeError("rect must be instance of RectGL");return new D(t.left,t.bottom,t.width,t.height)}static isRect(t){return t&&isFinite(t.left)&&isFinite(t.top)&&isFinite(t.width)&&isFinite(t.height)}static fromString(t){return t=t.substring(t.indexOf("(")+1,t.indexOf(")")).split(/,\s*/g),new D(parseFloat(t[0]),parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]))}static fromRect(t){return"string"==typeof t?D.fromString(t):new D(t.x,t.y,t.width,t.height)}static ofPolygon(t){if(t.shape&&(t=t.shape),0==t.length)return null;let e=Number.MAX_SAFE_INTEGER,i=Number.MAX_SAFE_INTEGER,s=Number.MIN_SAFE_INTEGER,r=Number.MIN_SAFE_INTEGER;for(let n=0;n<t.length;n++){let a=t.getPointX(n),o=t.getPointY(n);e=Math.min(e,a),i=Math.min(i,o),s=Math.max(s,a),r=Math.max(r,o)}return D.ofEdges(e,i,s,r)}static ofSpline(t,e=0){let i;for(let s=0;s<t.length;s++)i=C.calculateBrushGLSegmentBounds(t.getPointRef(s),e).union(i);return D.fromGLRect(i)}static ofEdges(t,e,i,s){let r=Math.min(t,i),n=Math.min(e,s),a=Math.max(t,i),o=Math.max(e,s);return new D(r,n,a-r,o-n)}static union(t,e){return t?e?t.union(e):t:e}static intersect(t,e){return t&&e?t.intersect(e):null}}class M extends x{constructor(t,e,i,s=0,r=1){super(e,i,t),this.points instanceof Float32Array?Object.defineProperty(this,"segmentsCount",{value:this.length-3,configurable:!0}):Object.defineProperty(this,"segmentsCount",{get:()=>this.length-3,configurable:!0}),this.ts=s,this.tf=r,Object.defineProperty(this,"bounds",{get:()=>D.ofSpline(this,this.pointProps.scattering).ceil(),enumerable:!0}),Object.defineProperty(this,"color",{get:()=>S.isColor(this.pointProps)?S.fromColor(this.pointProps):void 0,set:t=>{if(!t)throw new Error("Spline color cannot be removed");if(!(t instanceof S))throw new Error("Expected value should be Color instance");"red"in this.pointProps&&(this.pointProps.red=t.red),"green"in this.pointProps&&(this.pointProps.green=t.green),"blue"in this.pointProps&&(this.pointProps.blue=t.blue),"alpha"in this.pointProps&&(this.pointProps.alpha=t.alpha)},enumerable:!0}),this.validate()}validate(){let t=this.points instanceof Float32Array;if(super.validate(),!this.layout.includes(b.Property.X))throw new Error("Layout doesn't contains required properties X");if(!this.layout.includes(b.Property.Y))throw new Error("Layout doesn't contains required properties Y");if(t&&0==this.points.length)throw new Error("Empty spline is not allowed");if(this.ts<0||this.ts>=1)throw new Error(`Invalid spline ts ${this.ts} found. The value must be in the interval [0, 1).`);if(this.tf<=0||this.tf>1)throw new Error(`Invalid spline tf ${this.tf} found. The value must be in the interval (0, 1].`);if(1==this.segmentsCount&&this.ts>this.tf)throw new Error(`Invalid spline t range ${this.ts} - ${this.tf} found. Spline has only one segment and ts <= tf.`);if(t&&this.segmentsCount<1)throw new Error("Incompleted spline found. Spline is defined with at least 4 control points.")}clone(){return new M(this.layout.slice(),this.points.clone(),Object.clone(this.pointProps),this.ts,this.tf)}slice(t){let e=this.slicePoints(t.pointIndexStart,t.pointIndexEnd),i=new M(this.layout.slice(),e,Object.clone(this.pointProps),t.ts,t.tf);return i.id=t.id,i}getSegment(t){let e=t,i=t+3,s=0==e?this.ts:0,r=i+1==this.length?this.tf:1;return this.slice({pointIndexStart:e,pointIndexEnd:i,ts:s,tf:r})}getFragment(t=0,e=this.ts,i=this.segmentsCount-1,s=this.tf,r=!1){return new N(this,t,e,r?i-3:i,s)}toPlainPath(){let t=new x([]);for(let e=0;e<this.length;e++)t.points.push(this.getPointX(),this.getPointY());return t}toJSON(){return{type:"Spline",id:this.id,layout:this.layout.map((t=>t.name)),points:v.encode(this.points,this.encoding),pointProps:this.pointProps,ts:this.ts,tf:this.tf}}static fromJSON(t){let e=v.decode(t.points),i=new M(t.layout.map((t=>b.Property[t])),e,t.pointProps,t.ts,t.tf);return i.id=t.id,i}static fromRect(t,e){let i=[t.left,t.top,t.left,t.top,t.right,t.top,t.right,t.bottom,t.left,t.bottom,t.left,t.top,t.left,t.top];return new M(void 0,i,e)}static createInstance(t,e,i=[],s,r){return new M(t,i,e,s,r)}static createSharedInstance(t,e,i,s,r){return new M(t,Float32Array.createSharedInstance(e),i,s,r)}}class L extends x{constructor(t,e,i,s=[]){super(e,i,t),s.length>0&&!Object.isFrozen(s.first)&&s.forEach((t=>Object.freeze(t))),Object.defineProperty(this,"splineParameters",{value:Object.freeze(s),enumerable:!0});let r=new I(t,i);Object.defineProperty(this,"style",{get:()=>r.style,set:t=>r.style.reset(t),enumerable:!0}),Object.defineProperty(this,"color",{get:()=>this.style.color,set:t=>{if(!t)throw new Error("Spline color cannot be removed");if(!(t instanceof S))throw new Error("Expected value should be Color instance");"red"in this.pointProps&&(this.pointProps.red=t.red),"green"in this.pointProps&&(this.pointProps.green=t.green),"blue"in this.pointProps&&(this.pointProps.blue=t.blue),"alpha"in this.pointProps&&(this.pointProps.alpha=t.alpha)},enumerable:!0}),Object.defineProperty(this,"bounds",{get:()=>D.ofSpline(this,this.pointProps.scattering).ceil(),enumerable:!0}),this.validate()}validate(){let t=this.points instanceof Float32Array;if(super.validate(),!this.layout.includes(b.Property.X))throw new Error("Layout doesn't contains required properties X");if(!this.layout.includes(b.Property.Y))throw new Error("Layout doesn't contains required properties Y");if(t&&0==this.points.length)throw new Error("Empty spline is not allowed")}clone(){return new L(this.layout.slice(),this.points.clone(),Object.clone(this.pointProps),this.splineParameters.slice())}slice(t){let e=this.slicePoints(t.pointIndexStart,t.pointIndexEnd);return new L(this.layout.slice(),e,Object.clone(this.pointProps),this.splineParameters.slice())}getPoint(t){return super.getPoint(t,this.style)}getPointRef(t){return super.getPointRef(t,this.style)}getPointSegmentIndex(t){return this.splineParameters[t]?this.splineParameters[t].index:void 0}getPointT(t){return this.splineParameters[t]?this.splineParameters[t].t:void 0}getPointParameter(t){return this.splineParameters[t]}toJSON(){return{type:"InterpolatedSpline",layout:this.layout.map((t=>t.name)),points:v.encode(this.points,this.encoding),pointProps:this.pointProps,splineParameters:this.splineParameters}}static fromJSON(t){let e=v.decode(t.points);return new L(t.layout.map((t=>b.Property[t])),e,t.pointProps,t.splineParameters.map(A.fromJSON))}static fromRect(t,e){throw new Error("InterpolatedSpline.fromRect is not supported. Try Spline.fromRect and interpolate with particular Spline interpolator.")}static createInstance(t,e,i=[]){return new L(t,i,e)}static createSharedInstance(t,e,i,s){return new L(t,Float32Array.createSharedInstance(e),i,s)}}class _{constructor(){this.phase=_.Phase.END}add(t,e,i){if(!this.move(t))throw new Error(`Cannot move from phase ${this.phase.name} to phase ${t.name}`);return this.debug&&(console.log("-------------------------------------"),console.log(this.constructor.name,t.name)),this.addImpl(e,i)}addImpl(t,e){throw new Error("Abstract method addImpl of DataProcessor should be implemented")}move(t){return(this.phase!=_.Phase.END||t==_.Phase.BEGIN)&&((this.phase!=_.Phase.BEGIN||t==_.Phase.UPDATE||t==_.Phase.END)&&((this.phase!=_.Phase.UPDATE||t==_.Phase.UPDATE||t==_.Phase.END)&&(t==_.Phase.BEGIN&&this.reset(),this.phase=t,!0)))}reset(){this.phase=_.Phase.END}}Object.defineEnum(_,"Phase",["BEGIN","UPDATE","END"]);let F=h?h.default||globalThis.poly2tri:{};const{SweepContext:k,Point:j}=F;let $=l?l.default||globalThis.ClipperLib:{};const{Clipper:U,Paths:B,Path:Y,ClipType:X,PolyType:z,PolyFillType:G}=$;class H{constructor(t,e){if(!Array.isArray(t))throw new Error("Unexpected polygons type found");let i=65534/(e.width+1e-16),s=65534/(e.height+1e-16),r=Math.floor(Math.min(i,s));if(0==r)throw new Error(`Insufficent clipper range - (-32767 - 32767), scale failed - scaleX: ${i}, scaleY: ${s}`);let n=e.left+32767/r,a=e.top+32767/r;this.solution=new B,this.bounds=e,this.transform={scale:r,offsetX:n,offsetY:a},this.subject=this.apply(t)}convertPoint(t){let e=(t.x-this.transform.offsetX)*this.transform.scale,i=(t.y-this.transform.offsetY)*this.transform.scale;return{X:e<0?Math.ceil(e):Math.floor(e),Y:i<0?Math.ceil(i):Math.floor(i)}}containsPoint(t){return U.PointInPolygon(this.convertPoint(t),this.solution)}apply(t){let e=new B;for(let i of t){let t=new Y,s=i.shape;for(let e=0;e<s.length;e++)t.push(this.convertPoint({x:s.getPointX(e),y:s.getPointY(e)}));e.push(t)}return e}toPaths(){let t=[];this.lastPoint={};for(let e of this.solution){if(0==e.length)continue;let i=this.flatPath(e);i.length>0&&t.push(i)}return t}flatPath(t){let e=[];for(let i of t)this.lastPoint.X==i.X&&this.lastPoint.Y==i.Y||(e.push(i.X/this.transform.scale+this.transform.offsetX,i.Y/this.transform.scale+this.transform.offsetY),this.lastPoint=i);return e.length<6&&(console.warn(`Invalid contour found: [${e.join(", ")}]`),e.clear()),e}}class J{constructor(t=2){this.stride=t}sort(t,e){return this.sortArrayPart(t,0,t.length-this.stride,e),t}partition(t,e,i,s){let r=t[i],n=t[i+1],a=e-this.stride;for(let o=e;o<i;o+=2)s?s(r,n,t[o],t[o+1])&&(a+=this.stride,this.swap(t,a,o)):(r>t[o]||r==t[o]&&n>t[o+1])&&(a+=this.stride,this.swap(t,a,o));return this.swap(t,a+this.stride,i),a+this.stride}swap(t,e,i){let s=t[e],r=t[e+1];return t[e]=t[i],t[e+1]=t[i+1],t[i]=s,t[i+1]=r,t}sortArrayPart(t,e,i,s){if(e<i){let r=this.partition(t,e,i,s);this.sortArrayPart(t,e,r-this.stride,s),this.sortArrayPart(t,r+this.stride,i,s)}}}function V(t,e,i,s,r,n){return(i-t)*(n-e)-(s-e)*(r-t)}function Z(t,e,i,s,r,n){let a=t-i,o=r-i,h=a*(n-s)-o*(e-s);h*=h,a=r-i,o=n-s;let l=a*a+o*o;return l>0?Math.sqrt(h/l):Math.sqrt((i-t)*(i-t)+(s-e)*(s-e))}class q{constructor(t=Float32Array){this.ArrayType=t,this.quickSort=new J}monotoneChain(t){if(t.length<=0)return new this.ArrayType;this.quickSort.sort(t);let e=new this.ArrayType(t.length),i=0;for(let s=0;s<t.length;s+=2){for(;i>=4&&V(e[i-4],e[i-3],e[i-2],e[i-1],t[s],t[s+1])<=0;)i-=2;e[i]=t[s],e[i+1]=t[s+1],i+=2}e=e.slice(0,i);let s,r=new this.ArrayType(t.length);i=0;for(let e=t.length-2;e>=0;e-=2){for(;i>=4&&V(r[i-4],r[i-3],r[i-2],r[i-1],t[e],t[e+1])<=0;)i-=2;r[i]=t[e],r[i+1]=t[e+1],i+=2}if(r=r.slice(0,i-2),this.ArrayType==Float32Array){let t=r.length+e.length;s=Float32Array.createSharedInstance(t),s.set(r),s.set(e,r.length)}else s=r.concat(e);return s}}class W{constructor(t,e=[]){if(!(t instanceof x))throw new Error("Expected shape type is Path. Use createInstance or createSharedInstance Polygon methods to allocate instance.");if(e.some((t=>!(t instanceof x))))throw new Error("Expected hole type is Path. Use createInstance or createSharedInstance Polygon methods to allocate instance.");let i;this.holesDirection=W.PointsDirection.CLOCKWISE,Object.defineProperty(this,"shape",{value:t,enumerable:!0}),Object.defineProperty(this,"holes",{value:e,enumerable:!0}),Object.defineProperty(this,"contours",{value:[t,...e],enumerable:!0}),Object.defineProperty(this,"ArrayType",{value:t.points instanceof Float32Array?Float32Array:Array}),Object.defineProperty(this,"bounds",{get:()=>D.ofPolygon(this),enumerable:!0}),Object.defineProperty(this,"vertices",{get:()=>(i||(i=this.triangulate()),i),set:t=>i=t,enumerable:!0}),Object.defineProperty(this,"verticesValue",{get:()=>i})}clone(t=!1){let e=this.shape.clone(t),i=this.holes.map((e=>e.clone(t))),s=new W(e,i);return this.verticesValue&&(s.vertices=this.vertices.slice()),s}fit(t){let e=this.bounds,i=t.width/e.width,s=t.height/e.height,r=i>0&&s>0?Math.min(i,s):Math.max(i,s);for(let t of this.contours)for(let e=0;e<t.length;e++)t.setPointX(e,t.getPointX(e)*r),t.setPointY(e,t.getPointY(e)*r)}center(){let t=this.bounds;for(let e of this.contours)for(let i=0;i<e.length;i++)e.setPointX(i,e.getPointX(i)-t.center.x),e.setPointY(i,e.getPointY(i)-t.center.y)}transform(t){this.contours.forEach((e=>e.transform(t)))}intersects(t){if(!(t instanceof W))throw new Error("Expected 'poly' type is Polygon");(this.holes.length>0||t.holes.length)&&console.warn("Polygon intersection is for contours only. Holes are ignored.");let e=this.shape,i=t.shape;for(let t=0;t<2;t++){let s=0==t?e:i;for(let t=0;t<s.length;t++){let r=t+1==s.length?0:t+1,n=s.getPointX(t),a=s.getPointY(t),o=s.getPointX(r),h=s.getPointY(r)-a,l=n-o,u=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY;for(let t=0;t<e.length;t++){let i=h*e.getPointX(t)+l*e.getPointY(t);i<u&&(u=i),i>c&&(c=i)}let p=Number.POSITIVE_INFINITY,d=Number.NEGATIVE_INFINITY;for(let t=0;t<i.length;t++){let e=h*i.getPointX(t)+l*i.getPointY(t);e<p&&(p=e),e>d&&(d=e)}if(c<p||d<u)return!1}}return!0}containsPoint(t){let e=!1,i=this.shape;this.holes.length>0&&console.warn("Polygon intersection is for contours only. Holes are ignored.");for(let s=0,r=i.length-1;s<i.length;r=s++)i.getPointY(s)>t.y!=i.getPointY(r)>t.y&&t.x<(i.getPointX(r)-i.getPointX(s))*(t.y-i.getPointY(s))/(i.getPointY(r)-i.getPointY(s))+i.getPointX(s)&&(e=!e);return e}triangulate(){let t,e=[];for(let t of this.contours){let i=[];for(let e=0;e<t.length;e++){let s=new j(t.getPointX(e),t.getPointY(e));if(e>0){if(i.last.x==s.x&&i.last.y==s.y)continue;if(e==t.length-1&&i.first.x==s.x&&i.first.y==s.y)continue}i.push(s)}e.push(i)}try{t=new k(e.shift())}catch(t){return console.error(t),new Float32Array}for(let i of e)try{t.addHole(i)}catch(t){return console.error(t),new Float32Array}try{t.triangulate()}catch(t){return console.warn(t),new Float32Array}let i=t.getTriangles(),s=Float32Array.createSharedInstance(6*i.length),r=0;for(let t of i){let e=t.getPoints();for(let t of e)s[r++]=t.x,s[r++]=t.y}return s}convex(){return this.buildConvex(this.shape.points)}union(t){let e=Array.of(...this.shape.points,...t.shape.points);return this.buildConvex(e)}buildConvex(t){this.convexHullProducer||(this.convexHullProducer=new q(this.ArrayType));let e=this.convexHullProducer.monotoneChain(t);return this.ArrayType==Float32Array?W.createSharedInstance(e):W.createInstance(e)}simplify(t=.1){let e=new H([this],this.bounds);return e.subject=U.SimplifyPolygons(e.subject,G.pftNonZero),e.solution=U.CleanPolygons(e.subject,t*e.transform.scale),1==e.subject.length&&0==e.solution.first.length&&(e.solution=e.subject),W.toPolygonArray(e.toPaths())}simplifyRamerDouglasPeucker(t=.1){if(t<=0)throw new Error("epsilon expected value > 0");this.epsilon=t;let e=this.simplifyPath(this.shape),i=[];for(let t of this.holes){let e=this.simplifyPath(t);e.length>0&&i.push(e)}return this.ArrayType==Float32Array?W.createSharedInstance(e,i):W.createInstance(e,i)}simplifyPath(t){if(t.length<3)return t.points;let e=Array.of(...t.points,t.getPointX(0),t.getPointY(0)),i=this.simplifyPolyline(e);return i.length<8?e.slice(0,e.length-2):i.slice(0,i.length-2)}simplifyPolyline(t){if(t.length<4)return t;let e=0,i=0;for(let s=2;s<t.length-2;s+=2){let r=Z(t[s],t[s+1],t[0],t[1],t[t.length-2],t[t.length-1]);r>e&&(i=s,e=r)}if(e>this.epsilon){let e=this.simplifyPolyline(t.slice(0,i+2)),s=this.simplifyPolyline(t.slice(i,t.length));return e.concat(s.slice(2,s.length))}return[t[0],t[1],t[t.length-2],t[t.length-1]]}toSVGPath(){return this.contours.map((t=>t.toSVGPath())).join(" ")}toJSON(){return{type:"Polygon",shape:this.shape.toJSON(),holes:this.holes.map((t=>t.toJSON())),holesDirection:this.holesDirection.name,vertices:this.verticesValue}}static fromJSON(t){if("Polygon"!=t.type)throw new Error(`Polygon deserialization failed. JSON type is ${t.type}, expected Polygon.`);let e=x.fromJSON(t.shape),i=t.holes.map((t=>x.fromJSON(t))),s=new W(e,i);return s.holesDirection=W.PointsDirection[t.holesDirection],s.vertices=t.vertices,s}static fromRect(t){return W.createInstance([t.left,t.top,t.right,t.top,t.right,t.bottom,t.left,t.bottom,t.left,t.top])}static createInstance(t,e=[]){return new W(x.createInstance(t),e.map((t=>x.createInstance(t))))}static createSharedInstance(t,e=[]){let i=new W(x.createSharedInstance(t),e.map((t=>x.createSharedInstance(t))));return Object.defineProperty(i,"encoding",{get:()=>i.shape.encoding,set:t=>{i.contours.forEach((e=>e.encoding=t))},enumerable:!0}),i}}Object.defineEnum(W,"PointsDirection",["CLOCKWISE","COUNTERCLOCKWISE"]);class K{static ARRAY_TYPE=Array;#s;constructor(){this.keepAllData=!1,Object.defineProperty(this,"allData",{get:()=>{if(!this.keepAllData)throw new Error("All data is not accumulated. By default keepAllData property is false.");return this.#s||(this.#s=new this.constructor.ARRAY_TYPE),this.getOutput(this.#s,K.OutputType.ALL_DATA)},enumerable:!0})}build(t,e=K.OutputType.PROCESSOR,i=!0){return console.warn("use process instead"),this.process(t,e,i)}process(t,e=K.OutputType.PROCESSOR,i=!0){let s;switch(e){case K.OutputType.ADDITION:s=this.add(t,i);break;case K.OutputType.PREDICTION:s=this.predict(t);break;case K.OutputType.PROCESSOR:this.reset(),s=this.processImpl(t,e);break;default:throw new Error("Unexpected OutputType found. Allowed type is oneof(ADDITION, PREDICTION, PROCESSOR)")}return e!=K.OutputType.PREDICTION&&this.keepAllData&&(this.#s||(this.#s=new this.constructor.ARRAY_TYPE),s instanceof W?this.#s.push(s):e==K.OutputType.PROCESSOR?this.#s=s:this.#s.push(...s)),this.debug&&console.log(this.constructor.name,e.name,i,s),this.getOutput(s,e)}add(t,e=!1){return this.processImpl(t,K.OutputType.ADDITION)}predict(t){return this.processImpl(t,K.OutputType.PREDICTION)}processImpl(t,e){throw new Error("Abstract method processImpl(input, type) of DataSequenceProcessor should be implemented")}getOutput(t,e){return t}reset(){this.#s&&(this.#s=new this.constructor.ARRAY_TYPE)}}Object.defineEnum(K,"OutputType",["ADDITION","PREDICTION","ALL_DATA","PROCESSOR"]);class Q extends _{constructor(t,e){super(),this.layout=t,this.pathPointCalculator=e,this.inputBuffer=[],this.prediction=!0}togglePrediction(t){console.warn("PathProducer togglePrediction method is deprecated. Use InkBuilder instance prediction property to configure prediction behaviour."),this.prediction=t}addImpl(t,e){if(t.phase!=this.phase)throw new Error(`The phase of the addition (${t.phase.name}) doesn't match the phase of the PathProducer (${this.phase.name})`);let i=[],s=[];t&&this.inputBuffer.push(t);let r=this.inputBuffer.length>=3?this.inputBuffer[this.inputBuffer.length-3]:null,n=this.inputBuffer.length>=2?this.inputBuffer[this.inputBuffer.length-2]:null,a=this.inputBuffer.length>=1?this.inputBuffer[this.inputBuffer.length-1]:null,o=this.calculate(r,n,a);return t&&o&&i.push(...o.toArray(this.layout)),this.phase==_.Phase.END?(o=this.calculate(n,a,null),o&&i.push(...o.toArray(this.layout))):this.prediction&&(this.phase==_.Phase.UPDATE||e)&&(o=this.calculate(n,a,e),o&&(s.push(...o.toArray(this.layout)),o=this.calculate(a,e,null),o&&s.push(...o.toArray(this.layout)))),{added:i,predicted:s}}calculate(t,e,i){return e?this.pathPointCalculator(t,e,i):null}reset(){super.reset(),this.inputBuffer.clear()}}const tt=[-6e-6,-139e-6,-185e-6,414e-6,.002357,.003357,-.003135,-.023928,-.042909,-.017858,.096525,.254692,.347072,.26881,.114933];class et extends K{#r=[];#n=0;constructor(t,e=15){super(),this.filter=tt.slice(),Object.defineProperty(this,"movingAverageWindowSize",{get:function(){return e},set:function(t){e=t,this.filter.length!=t&&(this.filter=et.resample(tt,t)),this.predictionPointsCount=4*t/15,this.windowSize=this.filter.length},enumerable:!0}),this.dimsCount=t,this.movingAverageWindowSize=e}add(t,e){return e?this.project(t):this.addSequence(t)}processImpl(t){return this.project(t)}project(t){if(t.length%this.dimsCount!=0)throw new Error(`Points size ('${t.length}') must be multiple of the dimensions count ('${this.dimsCount}').`);if(0==t.length)return[];let e=[],i=this.#r.slice(),s=t.slice(0,t.length-this.dimsCount),r=this.addSequence(s);e.push(...r);let n=t.slice(t.length-this.dimsCount,t.length),a=this.predictionPointsCount;for(let t=0;t<a;t++){let i=this.addPoint(n);a-t<=this.#n&&e.push(...i)}return this.#r=i,e}addSequence(t){if(t.length%this.dimsCount!=0)throw new Error(`Points size ('${t.length}') must be multiple of the dimensions count ('${this.dimsCount}').`);let e=[],i=t.length/this.dimsCount;for(let s=0;s<i;s++){let i=this.addPoint(t.slice(s*this.dimsCount,(s+1)*this.dimsCount));e.push(...i)}return this.#n+=i,e}addPoint(t){for(this.#r.push(...t);this.#r.length<this.windowSize*this.dimsCount;)this.#r.unshift(...this.#r.slice(0,this.dimsCount));for(;this.#r.length>this.windowSize*this.dimsCount;)this.#r=this.#r.slice(this.dimsCount);return this.filterBuffer()}filterBuffer(){let t=[];for(let e=0;e<this.windowSize;e++)for(let i=0;i<this.dimsCount;i++)isNaN(t[i])&&(t[i]=0),t[i]+=this.#r[e*this.dimsCount+i]*this.filter[e];return t}reset(){super.reset(),this.#n=0,this.#r.clear()}static resample(t,e){let i=new Float32Array(e),s=t.length/e,r=0;for(let n=0;n<e;n++){let a=(t.length-1)*n/(e-1),o=Math.floor(a),h=Math.ceil(a),l=a-o,u=s*(t[o]*(1-l)+t[h]*l);r+=u,i[n]=u}let n=1/r;for(let t=0;t<e;t++)i[t]*=n;return i}}class it extends K{#a;#o;constructor(t){super(),this.layout=t,this.pathPointProps={}}add(t,e){this.#a||(this.#a=M.createInstance(this.layout,this.pathPointProps)),0==this.#a.points.length&&t.length>0&&t.unshift(...t.slice(0,this.layout.length)),e&&(t.length>=this.layout.length?t.push(...t.slice(t.length-this.layout.length,t.length)):t.push(...this.getLastPart()));let i=this.getFirstPart();return this.#a.points=i.concat(t),t}predict(t=[]){if(0==t.length)return t;this.#o?this.#o.points.clear():this.#o=M.createInstance(this.layout,this.pathPointProps);let e=this.#o.points,i=this.getFirstPart();for(e.push(...i),e.push(...t),e.push(...e.slice(e.length-this.layout.length,e.length));e.length<4*this.layout.length;)e.unshift(e.slice(0,this.layout.length));return e}processImpl(t){let e=[];return t.length>0&&(e.push(...t.slice(0,this.layout.length)),e.push(...t),t.length>=this.layout.length&&e.push(...t.slice(t.length-this.layout.length,t.length))),t}getOutput(t,e){if(e==it.OutputType.ADDITION){if(this.#a.points.length>=4*this.layout.length)return this.#a}else if(e==it.OutputType.PREDICTION){if(this.#o.points.length>0)return this.#o}else if(t.length>0)return M.createSharedInstance(this.layout,t,this.pathPointProps)}getFirstPart(){return this.#a.points.slice(Math.max(0,this.#a.points.length-3*this.layout.length),this.#a.points.length)}getLastPart(){return this.#a.points.slice(this.#a.points.length-this.layout.length,this.#a.points.length)}reset(){super.reset(),this.#a=null,this.#o=null}}const st=s.fromValues(0,-.5,1,-.5,1,0,-2.5,1.5,0,.5,2,-1.5,0,0,-.5,.5);class rt extends K{#a;#o;#h;constructor(t=!1,e=!1){super(),this.calculateDerivates=t,this.keepSplineParameters=e,this.state={segmentIndex:-1,lastPointPosition:void 0,lastPointSize:0}}initState(t){this.state.layout={},t.layout.forEach(((t,e)=>{this.state.layout[t.name]={index:e,polynomials:i.create()}})),this.keepSplineParameters?this.state.splineParameters?this.state.splineParameters.clear():this.state.splineParameters=[]:delete this.state.splineParameters,this.splineLayout=t.layout,this.pathPointProps=Object.clone(t.pointProps),this.scattering&&(this.pathPointProps.scattering=this.scattering),this.layout=this.calculateDerivates?t.layout.concat([b.Property.D_X,b.Property.D_Y]):t.layout,this.state.ready=!0}predict(t){if(!t)return[];this.state.ready||this.initState(t),this.#o?this.#o.points.clear():this.#o=L.createInstance(this.layout,this.pathPointProps),this.path=this.#o;let e=Object.clone(this.state);return delete this.state.splineParameters,this.resetState(),this.discretize(t),this.state=e,this.path.points}processImpl(t,e){if(!t)return[];let i;return t instanceof N&&(i=t,t=i.spline),this.state.ready||this.initState(t),e==rt.OutputType.ADDITION?(this.#a?this.#a.points.clear():this.#a=L.createInstance(this.layout,this.pathPointProps),this.path=this.#a):(this.#h=L.createInstance(this.layout,this.pathPointProps),this.path=this.#h),this.discretize(t,i),this.path.points}getOutput(t,e){if(0!=t.length){if(e==rt.OutputType.PROCESSOR||e==rt.OutputType.ALL_DATA){let e=this.state.splineParameters;return e&&(e=e.slice()),L.createSharedInstance(this.layout,t,this.pathPointProps,e)}return this.path}}calculateInterpolatedPoint(t,e,s){this.initState(t);let r=new b(0,0,this.splineLayout.includes(b.Property.Z)?0:void 0),n=i.fromValues(1,s,s*s,s*s*s);return this.calculatePolynomials(t,e),this.splineLayout.forEach((t=>{let e=i.dot(this.state.layout[t.name].polynomials,n);r[w.getPropName(t.name)]=e})),r}discretize(t,e){throw new Error("This method is abstract and should be implemented")}storeLastPoint(t,e=0){this.state.lastPointPosition=new u(this.getPropValue(b.Property.X,t,e),this.getPropValue(b.Property.Y,t,e),this.getPropValue(b.Property.Z,t,e)),this.state.lastPointSize=this.getPropValue(b.Property.SIZE,t,e)}getPropValue(t,e,i=0){return this.state.layout[t.name]?e[i+this.state.layout[t.name].index]:void 0}calculatePolynomials(t,e){let s=t.points,r=this.splineLayout.length*(e+0),n=this.splineLayout.length*(e+1),a=this.splineLayout.length*(e+2),o=this.splineLayout.length*(e+3);this.splineLayout.forEach(((t,e)=>{let h=i.fromValues(s[r+e],s[n+e],s[a+e],s[o+e]);i.transformMat4(this.state.layout[t.name].polynomials,h,st)}))}samplePoint(t){let e=[],s=i.fromValues(1,t,t*t,t*t*t);return this.splineLayout.forEach((t=>{let r=i.dot(this.state.layout[t.name].polynomials,s);e.push(r)})),this.calculateDerivates&&(e.push(this.getDerivativeOf(this.state.layout.X.polynomials,s)),e.push(this.getDerivativeOf(this.state.layout.Y.polynomials,s))),e}getDerivativeOf(t,e){let s=i.fromValues(t[1],2*t[2],3*t[3],0);return i.dot(s,e)}keepSegmentT(t){this.state.splineParameters&&this.state.splineParameters.push(new A(this.state.segmentIndex,t))}resetState(){this.state.segmentIndex=-1}reset(){super.reset(),this.state.ready=!1,this.state.lastPointPosition=void 0,this.state.lastPointSize=0,this.resetState(),this.#a=null,this.#o=null,this.#h=null}}class nt extends rt{constructor(t=.1,e,i){super(e,i),this.spacing=t}split(t,e=8){let i=this.spacing;this.spacing=1,this.splitCount=e;let s=this.process(t);return this.spacing=i,delete this.splitCount,s}discretize(e,i){let s,r,n=this.path.points,a=this.splitCount,o=Math.max(1,10*(this.spacing>1?1:this.spacing)),h=0,l=e.segmentsCount-1,c=e.ts,p=e.tf;i&&(h=i.segmentIndexStart,l=i.segmentIndexEnd,c=i.ts,p=i.tf,this.state.segmentIndex=h-1);for(let i=h;i<l+1;i++){if(this.state.segmentIndex++,this.calculatePolynomials(e,i),isNaN(this.splitCount)){s||(s=b.createInstance(e.layout),r=b.createInstance(e.layout)),s.fill(i+1,e.points,e.layout,e.pointProps),r.fill(i+2,e.points,e.layout,e.pointProps);let n=t.distance(s.value,r.value),h=this.pathPointProps.size;this.state.layout.SIZE&&(h=Math.min(s.size,r.size)),a=Math.floor(o*(n/h)/this.spacing)+1}let h=1/a;for(let t=0;t<=a;t++){let e=!this.state.lastPointPosition,s=t/a;if(0==i&&s<c){if(!(s+h>=c))continue;s=c,e=this.spacing<=1}if(i==l&&s>=p){if(!(s<p+h))continue;s=p,e=this.lastSegment&&this.spacing<=1}if(i>0&&0==s)continue;let r=this.samplePoint(s);if(!e&&this.state.lastPointPosition){let t=new u(this.getPropValue(b.Property.X,r),this.getPropValue(b.Property.Y,r),this.getPropValue(b.Property.Z,r)),i=this.state.lastPointPosition.vec.squaredDistance(this.state.lastPointPosition.value,t.value),s=(this.state.layout.SIZE?(this.state.lastPointSize+r[this.state.layout.SIZE.index])/2:this.pathPointProps.size)*this.spacing;e=i>=s*s}e&&(n.push(...r),this.storeLastPoint(r),this.keepSegmentT(s))}}}}class at{constructor(t){this.key=t,this.height=1}leftRotate(){let t=this.right,e=t.left;return t.left=this,this.right=e,this.height=Math.max(at.height(this.left),at.height(this.right))+1,t.height=Math.max(at.height(t.left),at.height(t.right))+1,t}rightRotate(){let t=this.left,e=t.right;return t.right=this,this.left=e,this.height=Math.max(at.height(this.left),at.height(this.right))+1,t.height=Math.max(at.height(t.left),at.height(t.right))+1,t}getBalanceFactor(){return at.height(this.left)-at.height(this.right)}static height(t){return t?t.height:0}static minValue(t){if(!t)return;let e=t;for(;e.left;)e=e.left;return e.key}static maxValue(t){if(!t)return;let e=t;for(;e.right;)e=e.right;return e.key}}class ot{constructor(){this.count=0,this.hasKey=!1,this.root}min(){return at.minValue(this.root)}max(){return at.maxValue(this.root)}add(t){return this.hasKey=!1,this.root=this.insertNode(this.root,t),this.hasKey||this.count++,!this.hasKey}insertNode(t,e){if(!t)return new at(e);if(e<t.key)t.left=this.insertNode(t.left,e);else{if(!(e>t.key))return this.hasKey=!0,t;t.right=this.insertNode(t.right,e)}if(!this.hasKey){t.height=1+Math.max(at.height(t.left),at.height(t.right));let i=t.getBalanceFactor();if(i>1){if(e<t.left.key)return t.rightRotate();if(e>t.left.key)return t.left=t.left.leftRotate(),t.rightRotate()}else if(i<-1){if(e>t.right.key)return t.leftRotate();if(e<t.right.key)return t.right=t.right.rightRotate(),t.leftRotate()}}return t}contains(t){return this.containsNode(this.root,t)}containsNode(t,e){return!!t&&(e<t.key?this.containsNode(t.left,e):!(e>t.key)||this.containsNode(t.right,e))}printTree(){if(!this.root)return;let t=[this.root],e=this.root.height;for(;t.length>0;){let i=t.shift();e!=i.height&&console.log("-"),console.log(`${i.key} with height: ${i.height}, balance: ${i.getBalanceFactor()}`),e=i.height;let s=i.left,r=i.right;s&&t.push(s),r&&t.push(r)}}toArray(){let t=[];return ot.fillArray(t,this.root),t}static fillArray(t,e){e&&(this.fillArray(t,e.left),t.push(e.key),this.fillArray(t,e.right))}}class ht{constructor(){this.tree=new ot,Object.defineProperty(this,"length",{get:()=>this.tree.count,enumerable:!0})}clear(){this.tree=new ot}add(t){return this.tree.add(t)}includes(t){return this.tree.contains(t)}min(){return this.tree.min()}max(){return this.tree.max()}toArray(){return this.tree.toArray()}}class lt extends rt{constructor(t,e){super(t,e),this.state.lastSegmentIndex=-1,this.state.lastPointRotation=0,this.state.lastPointT=0,this.state.absAccumulatedErrorPos=0,this.state.absAccumulatedErrorS=0,this.setT=new ht,this.samples=[],Object.defineProperty(this,"errorThreshold",{get:()=>this.error,set:t=>{this.error=t,this.errorDistSq=this.error*this.error,this.error10=10*this.error},enumerable:!0}),this.errorThreshold=.15}discretize(t,e){let i=this.path.points,s=0,r=t.segmentsCount-1,n=t.ts,a=t.tf;e&&(s=e.segmentIndexStart,r=e.segmentIndexEnd,n=e.ts,a=e.tf,this.state.segmentIndex=s-1);for(let e=s;e<r+1;e++){this.state.segmentIndex++,this.calculatePolynomials(t,e);let s=this.calculateTValues(e==r,n,a);i.push(...this.samplePoints(s)),s.length>0&&(this.resetAccumulatedErrors(),this.storeLastPoint(i))}}samplePoints(t){return this.samples.clear(),t.toArray().forEach((t=>{this.keepSegmentT(t),this.samples.push(...this.samplePoint(t))})),this.samples}storeLastPoint(t){let e=t.length-this.layout.length;super.storeLastPoint(t,e),this.state.lastPointRotation=this.getPropValue(b.Property.ROTATION,t,e),this.state.lastPointT=this.setT.max(),this.state.lastSegmentIndex=this.state.segmentIndex}calculateTValues(t,e,i){let s=0==this.state.segmentIndex?e:0,r=t?i:1;return this.setT.clear(),this.getTForPos(s,r),this.state.layout.SIZE&&this.getTForCubic(s,r,this.state.layout.SIZE.polynomials,this.error),this.mustAddStartT()&&this.setT.add(s),t&&this.setT.add(r),this.state.layout.ROTATION&&this.getTForRotation(s,r),this.setT}mustAddStartT(){if(this.state.lastSegmentIndex<0)return!0;let t=this.state.lastPointT-(this.state.segmentIndex-this.state.lastSegmentIndex),e=this.setT.length>0?this.setT.min():1,i=this.getPosErrorAtT0(e,this.state.lastPointPosition);if(this.state.absAccumulatedErrorPos+=Math.abs(i),this.state.layout.SIZE){let i=this.getErrorAtT0(this.state.layout.SIZE.polynomials,e,t,this.state.lastPointSize);this.state.absAccumulatedErrorS+=Math.abs(i)}return this.state.absAccumulatedErrorPos>this.errorDistSq||this.state.absAccumulatedErrorS>this.error}getPosErrorAtT0(t,e){let i=this.getTPoint(t),s=this.getTPoint(0);return this.minDistanceSq(e,i,s)}getErrorAtT0(t,e,i,s){let r=i,n=s,a=e,o=this.cubicCalc(t,a),h=this.cubicCalc(t,0),l=n+(0-r)*(o-n)/(a-r);return Math.abs(h-l)}getTForPos(t,e){let i=this.getTPoint(t),s=this.getTPoint(e),r=this.subdividePos(i,s);if(r.split)this.subdivideRecursivePos(i,r),this.setT.add(r.t),this.subdivideRecursivePos(r,s);else{let t=this.subdividePos(i,r),e=this.subdividePos(r,s);t.split&&(this.subdivideRecursivePos(i,t),this.setT.add(t.t),this.subdivideRecursivePos(t,r)),(t.split||e.split)&&this.setT.add(r.t),e.split&&(this.subdivideRecursivePos(r,e),this.setT.add(e.t),this.subdivideRecursivePos(e,s))}}subdivideRecursivePos(t,e){let i=this.subdividePos(t,e);i.split&&(this.subdivideRecursivePos(t,i),this.setT.add(i.t),this.subdivideRecursivePos(i,e))}subdividePos(t,e){let i=.5*(t.t+e.t),s=this.getTPoint(i),r=this.minDistanceSq(t,e,s),n=t.add(e).scaleSelf(.5),a=s.subtract(n).absSelf();return s.split=r>this.errorDistSq||a.x>this.error10||a.y>this.error10,this.state.layout.Z&&(s.split=s.split||a.z>this.error10),s}getTForCubic(t,e,i,s){let r={v:this.cubicCalc(i,t),t:t},n={v:this.cubicCalc(i,e),t:e},a=this.subdivide(r,n,i);if(a.diff>s)this.subdivideRecursive(r,a,i,s),this.setT.add(a.t),this.subdivideRecursive(a,n,i,s);else{let t=this.subdivide(r,a,i),e=this.subdivide(a,n,i);t.diff>s&&(this.subdivideRecursive(r,t,i,s),this.setT.add(t.t),this.subdivideRecursive(t,a,i,s)),(t.diff>s||e.diff>s)&&this.setT.add(a.t),e.diff>s&&(this.subdivideRecursive(a,e,i,s),this.setT.add(e.t),this.subdivideRecursive(e,n,i,s))}}subdivideRecursive(t,e,i,s){let r=this.subdivide(t,e,i);r.diff>s&&(this.subdivideRecursive(t,r,i,s),this.setT.add(r.t),this.subdivideRecursive(r,e,i,s))}subdivide(t,e,i){let s=.5*(t.t+e.t),r=this.cubicCalc(i,s),n=.5*(t.v+e.v);return{v:r,t:s,diff:Math.abs(r-n)}}getTForRotation(t,e){let i=this.state.layout.ROTATION.polynomials,s=this.state.lastPointRotation;this.state.lastSegmentIndex<0&&(s=this.cubicCalc(i,t));let r=.25*(e-t);for(let e=0;e<4;e++){let n=t+e*r,a=this.cubicCalc(i,n);Math.abs(a-s)>.06&&(this.setT.add(n),s=a)}}minDistanceSq(t,e,i){let s=i.vec,r=s.squaredDistance(t.value,e.value);if(0==r)return s.squaredDistance(i.value,t.value);let n=Math.max(0,Math.min(1,s.dot(i.subtract(t).value,e.subtract(t).value)/r)),a=e.subtract(t).scale(n).add(t);return s.squaredDistance(i.value,a.value)}getTPoint(t){let e=new u(this.cubicCalc(this.state.layout.X.polynomials,t),this.cubicCalc(this.state.layout.Y.polynomials,t),this.state.layout.Z?this.cubicCalc(this.state.layout.Z.polynomials,t):void 0);return e.t=t,e}cubicCalc(t,e){return t[0]+t[1]*e+t[2]*e*e+t[3]*e*e*e}resetAccumulatedErrors(){this.state.absAccumulatedErrorPos=0,this.state.absAccumulatedErrorS=0}resetState(){super.resetState(),this.state.lastSegmentIndex=-1,this.state.lastPointT=0,this.state.lastPointRotation=0,this.resetAccumulatedErrors()}}class ut extends Array{static get[Symbol.species](){return Array}constructor(...t){if(super(...t),t.some((t=>!(t instanceof W))))throw new Error("Expected data item type is Polygon");Object.defineProperty(this,"bounds",{get:()=>{let t;return this.length>0&&(this.forEach((e=>t=e.bounds.union(t))),t=t.ceil()),t},enumerable:!0}),Object.defineProperty(this,"vertices",{get:()=>this.triangulate(),enumerable:!0})}clone(){return new this.constructor(...this.map((t=>t.clone())))}push(...t){if(t.some((t=>!(t instanceof W))))throw new Error("Expected data item type is Polygon");super.push(...t)}triangulate(){return Float32Array.createSharedInstance().concat(...this.map((t=>t.vertices)))}transform(t){this.forEach((e=>e.transform(t)))}toJSON(){return{type:"PolygonArray",polygons:this.map((t=>t.toJSON()))}}static fromJSON(t){if("PolygonArray"!=t.type)throw new Error(`PolygonArray deserialization failed. JSON type is ${t.type}, expected PolygonArray.`);return new ut(...t.polygons.map((t=>W.fromJSON(t))))}static fromPathsData(t){return new ut(...t.map((t=>W.createInstance(t))))}}W.toPolygonArray=ut.fromPathsData;class ct extends ut{constructor(...t){let e;super(...t),Object.defineProperty(this,"encoding",{get:()=>e,set:t=>{e=t,this.forEach((e=>e.encoding=t))},enumerable:!0})}union(t=!1,e=.1){let i=new H(this,this.bounds);i.subject=U.SimplifyPolygons(i.subject,G.pftNonZero),i.solution=U.CleanPolygons(i.subject,e*i.transform.scale),1==i.subject.length&&0==i.solution.first.length&&(i.solution=i.subject);let s=i.toPaths();return t?W.createSharedInstance(s.first,s.slice(1)):W.createInstance(s.first,s.slice(1))}intersects(t){t instanceof W&&(t=[t]);for(let e of this)for(let i of t)if(e.intersects(i))return{poly1:e,poly2:i};return null}toJSON(){let t=super.toJSON();return t.type="InkPath2D",t}static fromJSON(t){if("InkPath2D"!=t.type)throw new Error(`InkPath2D deserialization failed. JSON type is ${t.type}, expected InkPath2D.`);return new ct(...t.polygons.map((t=>W.fromJSON(t))))}}class pt extends K{static ARRAY_TYPE=ct;#a;#o;#h;#s;constructor(t){super(),this.brush=t}processImpl(t,e){return e==pt.OutputType.ADDITION?(this.#a||(this.#a=new ct),this.#s=this.#a):e==pt.OutputType.PREDICTION?(this.#o||(this.#o=new ct),this.#s=this.#o):(this.#h||(this.#h=new ct),this.#s=this.#h),this.#s.clear(),this.generatePolygons(t),this.#s}generatePolygons(t){if(!t)return this.#s;for(let e=0;e<t.length;e++){let i=t.getPointRef(e),s=this.applyBrush(i);this.#s.push(s)}}applyBrush(e){let i=this.createTransform(e),s=this.brush.selectShape(i.maxScale).shape,r=Float32Array.createSharedInstance(2*s.length);for(let e=0;e<s.length;e++){let n=e*s.stride,a=t.fromValues(s.getPointX(e),s.getPointY(e));t.transformMat2d(a,a,i),r[n]=a[0],r[n+1]=a[1]}return W.createSharedInstance(r)}createTransform(e){if(isNaN(e.size))throw new Error("Size information not found");let i=n.create(),s=e.size*e.scaleX,r=e.size*e.scaleY,a=Math.max(s,r);return n.translate(i,i,t.fromValues(e.x,e.y)),n.rotate(i,i,e.rotation),n.translate(i,i,t.fromValues(e.offsetX,e.offsetY)),n.scale(i,i,t.fromValues(s,r)),i.maxScale=a,i}reset(){super.reset(),this.#a&&this.#a.clear(),this.#o&&this.#o.clear(),this.#h&&(this.#h=new ct)}}class dt extends K{static ARRAY_TYPE=ct;#a;#o;#h;#s;#l;constructor(){super()}add(t,e){return this.#a||(this.#a=new ct),this.#s=this.#a,this.#s.clear(),this.buildConvexHulls(t,!0),this.#s}processImpl(t,e){if(!(t instanceof ct)){if(!(t instanceof W))throw new Error("ConvexHullChainProducer build 'input' type missmatch, expected type is oneof(Polygon, InkPath2D)");t=[t]}return e==dt.OutputType.PREDICTION?(this.#o||(this.#o=new ct),this.#s=this.#o):(this.#h||(this.#h=new ct),this.#s=this.#h),this.#s.clear(),this.buildConvexHulls(t),this.#s}buildConvexHulls(t,e=!1){let i=this.#l;for(let e of t){if(i||1==t.length){let t=i?i.union(e):e.convex();this.#s.push(t)}i=e}e&&t.length>0&&(this.#l=t.last)}reset(){super.reset(),this.#l=null,this.#a&&this.#a.clear(),this.#o&&this.#o.clear(),this.#h&&this.#h.clear()}}let ft=!1;class mt{constructor(t,e,i=mt.WorkerType.CLASSIC){if(!ft)throw new Error("Constructor is private, use static method getInstance instead.");this.name=t,this.type=i,e&&e.startsWith("file://")&&(e=e.replace("file://","")),this.src=e,this.workers=[],this.transferables=[],this.status=mt.Status.CLOSED,this.resolver={};let s=0;Object.defineProperty(this,"nextID",{get:()=>String(s++),enumerable:!0,configurable:!0})}async open(t=this.src){if(this.status!=mt.Status.CLOSED)throw new Error(`${this.name} worker cannot be opened. Current status is ${this.status.name}.`);if(!t)throw new Error(`${this.name} worker location is not defined.`);let e,i;if("function"==typeof Worker)e=Worker,i=navigator.hardwareConcurrency||1;else{const t=await import("os"),s=await import("worker_threads"),{Worker:r}=s;e=r,i=t.cpus().length}this.ready=0;for(let s=0;s<i;s++){let i=this.name+s,r=new e(t,{type:this.type,name:i,workerData:{name:i}});r.name=s,r.on("message",(t=>"INIT"==t.action?this.confirmWorkerReady():this.recieve(t))),r.on("error",(t=>this.recieveError(t,s))),this.workers.push(r)}return this.status=mt.Status.OPEN_IN_PROGRESS,new Promise(((t,e)=>{this.workers.forEach(((t,e)=>t.postMessage({action:"INIT",worker:e}))),this.resolve=t}))}confirmWorkerReady(){this.ready++,this.ready==this.workers.length&&(this.resolve(),delete this.ready,delete this.resolve,this.status=mt.Status.OPEN)}close(){this.workers.forEach((t=>t.terminate())),this.workers.clear(),this.status=mt.Status.CLOSED}async broadcast(t,e){if(this.status!=mt.Status.OPEN)throw new Error(`ThreadBridge is not opened yet. Current status is ${this.status.name}. Use open first.`);return new Promise(((i,s)=>{this.resolver[e]=i;for(let i of this.workers){let s=this.buildRequestMessage(t,e);if(!s)break;this.send(i.name,s)}}))}async broadcastMessage(t){if(this.status!=mt.Status.OPEN)throw new Error(`ThreadBridge is not opened yet. Current status is ${this.status.name}. Use open first.`);if(!t.actionID)throw new Error("message actionID is required");return new Promise(((e,i)=>{this.resolver[t.actionID]=e;for(let e of this.workers)this.send(e.name,t)}))}send(t,e){if(this.status!=mt.Status.OPEN)throw new Error(`ThreadBridge is not opened yet. Current status is ${this.status.name}. Use open first.`);if(!e)throw new Error("message is required");this.workers[t].postMessage(e,this.transferables),this.transferables.clear()}buildRequestMessage(t,e){throw new Error("ThreadBridge.buildRequestMessage(action, actionID) is abstract and should be implemented")}recieve(t){throw new Error("ThreadBridge.recieve(message) is abstract and should be implemented")}resolve(t,e){this.resolver[t](e),delete this.resolver[t]}recieveError(t,e){console.warn(`${this.name} worker ${e}: ${t.message}`),t.filename||console.error(t)}static getInstance(){return this.instance||(ft=!0,this.instance=new this,ft=!1),this.instance}}Object.defineEnum(mt,"Status",["OPEN","OPEN_IN_PROGRESS","CLOSED"]),mt.WorkerType={CLASSIC:"classic",MODULE:"module"};class gt extends K{static ARRAY_TYPE=ct;predict(t){return console.warn("Prediction merge is not recommended"),t}processImpl(t,e){return this.merge(t,e==gt.OutputType.PROCESSOR)}merge(t,e){if(0!=t.length)return t.union(e)}}class yt extends K{static ARRAY_TYPE=ct;constructor(t=.1){super(),this.epsilon=t}predict(t){return console.warn("Prediction simplify is not recommended"),t}processImpl(t){return t instanceof W?t.simplifyRamerDouglasPeucker(this.epsilon):new t.constructor(...t.map((t=>t.simplify(this.epsilon))))}}function Pt(){}Object.defineEnum(Pt,"Stage",["PATH_PRODUCER","SMOOTHER","SPLINE_PRODUCER","SPLINE_INTERPOLATOR","BRUSH_APPLIER","CONVEX_HULL_CHAIN_PRODUCER","POLYGON_MERGER","POLYGON_SIMPLIFIER"]);const bt=Pt.Stage,Et=_.Phase,St=K.OutputType;Object.defineProperty(globalThis,"DIGITAL_INK_ENV",{value:"AUTO",enumerable:!0,configurable:!0});let wt={version:"1.5.0"};Object.defineEnum(wt,"Type",["WEB","WORKER","NODE","SHELL"]),Object.defineEnum(wt,"Type2D",["SCREEN","OFFSCREEN"]),Object.defineEnum(wt,"TypeGL",["WEB","STACK"]),function(t){let e,i="BROWSER"!=DIGITAL_INK_ENV&&"object"==typeof process&&"function"==typeof require;e="object"==typeof window?"WEB":"function"==typeof importScripts?"WORKER":i?"NODE":"SHELL";let s="undefined"==typeof Screen?"OFFSCREEN":"SCREEN",r="undefined"==typeof WebGLRenderingContext?"STACK":"WEB";Object.defineProperty(wt,"commonJS",{value:i,enumerable:!0}),Object.defineProperty(wt,"type",{value:wt.Type[e],enumerable:!0}),Object.defineProperty(wt,"type2D",{value:wt.Type2D[s],enumerable:!0}),Object.defineProperty(wt,"typeGL",{value:wt.TypeGL[r],enumerable:!0})}();let It={};if(wt.type==wt.Type.WEB)It.Image=globalThis.Image,It.ImageData=globalThis.ImageData,It.CanvasRenderingContext2D=globalThis.CanvasRenderingContext2D,void 0===globalThis.OffscreenCanvas?(It.OffscreenCanvas=function(t,e){let i=document.createElement("canvas");return i.width=t,i.height=e,i},It.OffscreenCanvasRenderingContext2D=globalThis.CanvasRenderingContext2D):(It.OffscreenCanvas=globalThis.OffscreenCanvas,It.OffscreenCanvasRenderingContext2D=globalThis.OffscreenCanvasRenderingContext2D);else if(void 0!==globalThis.OffscreenCanvas)It.Image=globalThis.Image,It.ImageData=globalThis.ImageData,It.OffscreenCanvas=globalThis.OffscreenCanvas,It.OffscreenCanvasRenderingContext2D=globalThis.OffscreenCanvasRenderingContext2D;else if(wt.commonJS){const{Canvas:t,CanvasRenderingContext2D:e,Image:i,ImageData:s}=require("canvas");It.Image=i,It.ImageData=s,It.OffscreenCanvas=t,It.OffscreenCanvasRenderingContext2D=e}else console.warn(`Current env - ${wt.type.name}, do not provides OffscreenCanvas support`);function vt(t){this.clearRect(0,0,this.canvas.width,this.canvas.height),t&&(this.fillStyle=t,this.fillRect(0,0,this.canvas.width,this.canvas.height))}It.CanvasRenderingContext2D&&(It.CanvasRenderingContext2D.prototype.clearCanvas=vt),It.OffscreenCanvasRenderingContext2D&&(It.OffscreenCanvasRenderingContext2D.prototype.clearCanvas=vt);const{Image:Ot,ImageData:xt,OffscreenCanvas:At,CanvasRenderingContext2D:Rt,OffscreenCanvasRenderingContext2D:Tt}=It;let Nt;class Ct{#u={};constructor(...t){if(Nt)throw new Error("URIResolver instance already available");Nt=this,Object.defineProperty(this,"items",{get:()=>Object.values(this.#u),enumerable:!0}),this.init(...t)}init(...t){throw new Error("URIResolver.init(...args) is abstract and should be implemented")}get(t){return this.#u[t]}register(t,e){this.#u[t]=e}resolve(t){let e;if(t.includes("?")){let i=t.split("?")[0],s=this.#u[i];if(s){let i=t.split("?")[1],r=[];i.split("&").forEach((t=>{let e=t.split("=")[1],i=parseFloat(e);isFinite(i)?e=i:"true"==e?e=!0:"false"==e&&(e=!1),r.push(e)})),e=function(){return s(...Array.from(arguments).concat(r))}}}else e=this.#u[t];if(!e)throw new Error(`Failed to resolve ${t}`);return e}}Object.defineProperty(Ct,"instance",{get:()=>Nt});class Dt{static repetitionsCache=new Set;constructor(t,e){this.name=t,!t||w.isValidURL(t)||Dt.repetitionsCache.has(t)||(Dt.repetitionsCache.add(t),console.warn(`The string ${t} is not a well formed URI`)),Object.defineProperty(this,"value",{get:function(){if(!e){if(!this.name)throw new Error("Resource descriptor identifier not found. Cannot resolve resource content.");if("function"==typeof this.resolve&&(e=this.resolve(this.name)),!e){if(!Ct.instance)throw new Error(`Resource URI ${this.name} cannot be resolved. URIResolver not implemented yet. Please implement and instantiate.`);e=Ct.instance.resolve(this.name)}if(!e)throw new Error(`Resource URI ${this.name} cannot be resolved. Please provide resource definition in URIResolver init implementation.`)}return e},set:function(t){e=t},enumerable:!0})}toJSON(){let t=this.value;return ArrayBuffer.isTypedArray(t)?t=v.encode(t,this.encoding):"function"==typeof t&&(t=t()),{name:this.name,value:t}}static fromJSON(t){let e=t.value;return v.isTypedArrayData(e)&&(e=v.decode(e)),new Dt(t.name,e)}static getInstance(t,e){return new Dt(e,t)}}class Mt{constructor(t){w.isValidURL(t)||(Dt.repetitionsCache.has(t)||(Dt.repetitionsCache.add(t),console.warn(`Brush URI ${t} is not a well formed URI`)),t=this.constructor.onInvalidName(t)),Object.defineProperty(this,"id",{value:t}),Object.defineProperty(this,"uri",{value:t}),Object.defineProperty(this,"name",{value:t,enumerable:!0})}toJSON(){throw new Error("Brush.toJSON() should be implemented")}static fromJSON(t){throw new Error("static Brush.fromJSON() should be implemented")}static onInvalidName(t){return t}}class Lt{static defaults={CIRCLE_PRECISION:20,CIRCLE_RADIUS:.5,ELLIPSE_PRECISION:20,ELLIPSE_RADIUS_X:.5,ELLIPSE_RADIUS_Y:.25,STAR_POINTS:5,STAR_RADIUS:.5,STAR_INTERNAL_RADIUS:.25};static createCircle(t=Lt.defaults.CIRCLE_PRECISION,e=Lt.defaults.CIRCLE_RADIUS,i={x:0,y:0}){return Lt.createEllipse(t,e,e,i)}static createEllipse(t=Lt.defaults.ELLIPSE_PRECISION,e=Lt.defaults.ELLIPSE_RADIUS_X,i=Lt.defaults.ELLIPSE_RADIUS_Y,s={x:0,y:0}){let r=[],n=2*Math.PI/t;if(e<=0)throw new Error(`Invalid radius x found ${e} > 0`);if(i<=0)throw new Error(`Invalid radius y found ${i} > 0`);for(let a=0;a<t;a++){let t=a*n,o=e*Math.cos(t),h=i*Math.sin(t);r.push(s.x+o,s.y+h)}return Float32Array.createSharedInstance(r)}static createStar(t=Lt.defaults.STAR_POINTS,e=Lt.defaults.STAR_INTERNAL_RADIUS,i=Lt.defaults.STAR_RADIUS){let s=[];if(i<=0)throw new Error(`Invalid radius found ${i} > 0`);if(e<=0)throw new Error(`Invalid internal radius found ${e} > 0`);if(e>i)throw new Error(`Invalid internal radius found 0 < ${e} < ${i}`);let r=2*Math.PI/t;for(let n=0;n<t;n++){let t=n*r,a=i*Math.cos(t),o=i*Math.sin(t),h=e*Math.cos(t+r/2),l=e*Math.sin(t+r/2);s.push(a,o,h,l)}return Float32Array.createSharedInstance(s)}}class _t{static SHAPE_FRAME=new D(-.5,-.5,1,1);constructor(t,e=1){this.size=e,Object.defineProperty(this,"descriptor",{value:{shape:void 0},enumerable:!0}),Object.defineProperty(this,"shape",{get:function(){if(!t){if("function"==typeof(t=this.descriptor.shape.value)&&(t=t()),(Array.isArray(t)||t instanceof Float32Array)&&(t=W.createSharedInstance(t)),!(t instanceof W))throw new Error("Expected shape type is Polygon");_t.fitShape(t)}return t},set:function(e){if(!e)throw new Error("BrushPrototype: shape not found");"string"==typeof e?e=new Dt(e):e instanceof W||e instanceof Float32Array||Array.isArray(e)?e=Dt.getInstance(e):e instanceof Dt||(e=new Dt(e.name,e.value)),t=null,this.descriptor.shape=e,this.descriptor.shape.resolve=_t.resolve},enumerable:!0}),this.shape=t}toJSON(){return this.shape.encoding=this.encoding,{shape:{name:this.descriptor.shape.name,value:this.shape.toJSON()},size:this.size}}static fromJSON(t){return new _t({name:t.shape.name,value:W.fromJSON(t.shape.value)},t.size)}static create(t,e=0,...i){let s,r=t;switch(t){case _t.Type.CIRCLE:s=Lt.createCircle(...i),r+=`?precision=${i[0]||Lt.defaults.CIRCLE_PRECISION}&radius=${i[1]||Lt.defaults.CIRCLE_RADIUS}`;break;case _t.Type.ELLIPSE:s=Lt.createEllipse(...i),r+=`?precision=${i[0]||Lt.defaults.ELLIPSE_PRECISION}&radiusX=${i[1]||Lt.defaults.ELLIPSE_RADIUS_X}&radiusY=${i[2]||Lt.defaults.ELLIPSE_RADIUS_Y}`;break;case _t.Type.STAR:s=Lt.createStar(...i),r+=`?points=${i[0]||Lt.defaults.STAR_POINTS}&internalRadius=${i[1]||Lt.defaults.STAR_INTERNAL_RADIUS}&radius=${i[2]||Lt.defaults.STAR_RADIUS}`;break;default:console.error(`Brush2D: createShape fails with ${t} type`)}return new _t({name:r,shape:s},e)}static resolve(t){let e,i=t.split("?"),s=i.first;if(Object.values(_t.Type).includes(s)){let t=i.last.split("&"),r={};switch(t.forEach((t=>{r[t.substring(0,t.indexOf("="))]=t.substring(t.indexOf("=")+1)})),s){case _t.Type.CIRCLE:{let t=r.precision?parseInt(r.precision):void 0,i=r.radius?parseFloat(r.radius):1;e=Lt.createCircle(t,i);break}case _t.Type.ELLIPSE:{let t=r.precision?parseInt(r.precision):void 0,i=r.radiusX?parseFloat(r.radiusX):void 0,s=r.radiusY?parseFloat(r.radiusY):void 0;e=Lt.createEllipse(t,i,s);break}case _t.Type.STAR:{let t=r.points?parseInt(r.points):void 0,i=r.radius?parseFloat(r.radius):void 0,s=r.internalRadius?parseFloat(r.internalRadius):void 0;e=Lt.createStar(t,s,i);break}default:console.error(`Brush2D: createShape fails with ${s} type`)}}return e}static fitShape(t){if(!(t instanceof W))throw new Error("Expected shape type is Polygon");t.center(),t.fit(_t.SHAPE_FRAME)}}async function Ft(t,e="binary",i={}){if(t instanceof Uint8Array)return t;let s,r=await fetch(t,Object.assign({mode:"no-cors"},i));if("json"==e)s=await r.json();else if("text"==e)s=await r.text();else if("binary"==e){let t=await r.arrayBuffer();s=new Uint8Array(t)}else{let t=await r.blob();s="base64"==e?await function(t){return new Promise(((e,i)=>{let s=new FileReader;s.onloadend=()=>e("data:"==s.result?"":s.result),s.onerror=i,s.readAsDataURL(t)}))}(t):t}return s}async function kt(t,e="binary",i={}){return Ft(t,e,i)}async function jt(t){let e;return e="string"==typeof t||"undefined"==typeof createImageBitmap?await function(t){return new Promise(((e,i)=>{let s,r=new Ot;r.crossOrigin="anonymous",r.onload=()=>{if(wt.type2D==wt.Type2D.OFFSCREEN){const t=new At(r.width,r.height);t.getContext("2d").drawImage(r,0,0),e(t)}else s&&URL.revokeObjectURL(s),e(r)},r.onerror=i,"string"==typeof t?r.src=t:wt.type2D==wt.Type2D.OFFSCREEN?t instanceof Uint8Array?r.src=Buffer.from(t):t instanceof At?e(t):r.src=t:(t instanceof Uint8Array&&(t.byteLength!=t.buffer.byteLength&&(t=t.slice()),t=t.buffer),t instanceof ArrayBuffer&&(t=new Blob([t],{type:"image/png"})),s=URL.createObjectURL(t),r.src=s)}))}(t):t instanceof ArrayBuffer||t instanceof Uint8Array?await createImageBitmap(new Blob([t],{type:"image/png"})):await createImageBitmap(t),e}_t.Type={ELLIPSE:"will://brush/3.0/shape/Ellipse",CIRCLE:"will://brush/3.0/shape/Circle",STAR:"will://brush/3.0/shape/Star"};class $t extends Mt{constructor(t,e,i,s=1){super(t),isFinite(i)&&(s=i,i=void 0),s<=0&&(console.warn(`Invalid spacing found ${s}. It should be positive number.`),s=1),Object.defineProperty(this,"shape",{get:()=>e,set:t=>{if(t instanceof Float32Array&&(t=new _t(t)),t instanceof _t&&(t=[t]),t.some((t=>!(t instanceof _t))))throw console.warn(t),new Error("Brush2D: Invalid shape found");t.sort(w.comparator({sortBy:"size",sortOrder:"asc"})),e=t},enumerable:!0}),this.shape=e,this.fill=i,this.spacing=s}async configure(t){if(this.pattern||!this.fill)return;if(!(t instanceof Rt||t instanceof Tt))throw new Error("ctx is not instance of CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D");let e=await jt(this.fill);this.pattern=t.createPattern(e,"repeat")}selectShape(t){let e;for(let i=1;i<this.shape.length;i++)if(this.shape[i].size>t){e=this.shape[i-1];break}return e||(e=this.shape.last),e.shape}toJSON(){return{type:"Brush2D",name:this.name,spacing:this.spacing,shape:this.shape.map((t=>(t.encoding=this.encoding,t.toJSON())))}}static fromJSON(t){let e=1==t.shape.length?_t.fromJSON(t.shape[0]):t.shape.map((t=>_t.fromJSON(t)));return new $t(t.name,e,t.spacing)}}function Ut(){}Ut.BlendMode={SOURCE_OVER:"source-over",DESTINATION_OVER:"destination-over",DESTINATION_IN:"destination-in",DESTINATION_OUT:"destination-out",LIGHTER:"lighter",COPY:"copy",MIN:"MIN",MAX:"MAX",DIRECT_SOURCE_OUT:"DIRECT_SOURCE_OUT",DIRECT_DESTINATION_OUT:"DIRECT_DESTINATION_OUT"};const Bt=Ut.BlendMode;class Yt{constructor(t,e){Object.defineProperty(this,"ctx",{value:t,enumerable:!0}),Object.defineProperty(this,"value",{value:e,enumerable:!0}),Object.defineProperty(this,"texture",{value:e,enumerable:!0})}async update(t,e){if(Array.isArray(t)){let i=[],s=t;for(let t of s){let e=await jt(t);i.push(e)}this.completeMipMap(i),this.fill(i,e)}else{let e=t,i=await jt(e);this.fill(i)}}completeMipMap(t){if(t.sort(((t,e)=>e.width-t.width)),1==t.last.width)return;let e=t.last.width;for(;e>1;){e/=2;let i=new At(t.last.width/2,t.last.height/2);i.getContext("2d").drawImage(t.last,0,0,i.width,i.height),t.push(i)}}fill(t,e){let i=this.ctx,s=this.value;if(i.bindTexture(i.TEXTURE_2D,s),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),Array.isArray(t)){let s=t;this.size=[],s.forEach(((t,e)=>{i.texImage2D(i.TEXTURE_2D,e,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,t),this.size.push({width:t.width,height:t.height}),t.close&&t.close()})),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,e?i.LINEAR_MIPMAP_LINEAR:i.LINEAR_MIPMAP_NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR)}else i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,t),this.size={width:t.width,height:t.height},t.close&&t.close();i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),i.bindTexture(i.TEXTURE_2D,null),this.logError(this.ctx,s.name)}readPixels(){let t=this.ctx,e=this.value,i=(i,s)=>{let r=new Uint8Array(i.width*i.height*4);return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,s),t.readPixels(0,0,i.width,i.height,t.RGBA,t.UNSIGNED_BYTE,r),r},s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s);let r=Array.isArray(this.size)?this.size.map(i):i(this.size,0);return t.deleteFramebuffer(s),r}logError(){let t=this.ctx.getError();if(t>0){let e=Object.keys(this.ctx.constructor.prototype).filter((e=>this.ctx[e]===t)).join(" | ");console.error(`WebGL error - ${this.texture.name}: ${t} - ${e}`)}}static createInstance(t,e=t.CLAMP_TO_EDGE,i=t.NEAREST){let s=t.createTexture();return t.bindTexture(t.TEXTURE_2D,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,i),t.bindTexture(t.TEXTURE_2D,null),new Yt(t,s)}}class Xt extends Mt{constructor(t,e,i,s={},r={}){super(t),this.spacing=s.spacing||.15,this.scattering=s.scattering||0,this.rotationMode=s.rotationMode||Xt.RotationMode.RANDOM;let n,a=s.blendMode||Bt.SOURCE_OVER;Object.defineProperty(this,"blendMode",{get:()=>a,set:t=>{if(!t)throw new Error("BrushGL blendMode is required");a=t}}),Object.defineProperty(this,"particleSettings",{get:()=>({spacing:this.spacing,scattering:this.scattering,blendMode:this.blendMode,rotationMode:this.rotationMode}),enumerable:!0}),Object.defineProperty(this,"fillTextureSettings",{get:()=>({randomize:this.randomizeFill,size:this.fillTextureSize,offset:this.fillTextureOffset}),enumerable:!0}),Object.defineProperty(this,"descriptor",{value:{shape:void 0,fill:void 0},enumerable:!0}),Object.defineProperty(this,"shape",{get:()=>Array.isArray(this.descriptor.shape)?this.descriptor.shape.map((t=>t.value)):this.descriptor.shape.value,enumerable:!0}),Object.defineProperty(this,"fill",{get:()=>this.descriptor.fill.value,enumerable:!0}),Object.defineProperty(this,"encoding",{get:()=>n,set:t=>{n=t,Array.isArray(this.descriptor.shape)?this.descriptor.shape.forEach((e=>e.encoding=t)):this.descriptor.shape.encoding=t,this.descriptor.fill.encoding=t},enumerable:!0}),this.updateShape(e),this.updateFill(i,r)}async updateShape(t){Array.isArray(t)?t=t.map((t=>"string"==typeof t?Dt.getInstance(t):t instanceof Dt?t:new Dt(t.name,t.value))):"string"==typeof t?t=Dt.getInstance(t):t instanceof Dt||(t=new Dt(t.name,t.value)),this.descriptor.shape=t,this.ctx&&await this.configureShape()}async updateFill(t,e={}){if(this.randomizeFill=!("randomize"in e)||e.randomize,this.fillTextureSize=e.size,this.fillTextureOffset=e.offset||{x:0,y:0},Array.isArray(t))throw new Error("Mipmap is not compatible whith fill texture");"string"==typeof t?t=Dt.getInstance(t):t instanceof Dt||(t=new Dt(t.name,t.value)),this.descriptor.fill=t,this.ctx&&await this.configureFill()}async configure(t){this.ctx=t,await this.configureShape(),await this.configureFill()}async configureShape(){this.shapeTexture||(this.shapeTexture=Yt.createInstance(this.ctx,this.ctx.CLAMP_TO_EDGE,this.ctx.LINEAR)),await this.shapeTexture.update(this.shape,this.spacing<=1)}async configureFill(){this.fillTexture||(this.fillTexture=Yt.createInstance(this.ctx,this.ctx.REPEAT,this.ctx.NEAREST)),await this.fillTexture.update(this.fill),this.fillTextureSize||(this.fillTextureSize=this.fillTexture.size)}async getShapeBinary(){let t;if(Array.isArray(this.shape)){let e=[];for(let t of this.shape){let i=await kt(t);e.push(i)}t=e}else t=await kt(this.shape);return t}async getFillBinary(){return await kt(this.fill)}toJSON(){return{type:"BrushGL",name:this.name,shape:Array.isArray(this.descriptor.shape)?this.descriptor.shape.map((t=>t.toJSON())):this.descriptor.shape.toJSON(),fill:this.descriptor.fill.toJSON(),particleSettings:{spacing:this.spacing,scattering:this.scattering,blendMode:this.blendMode.name,rotationMode:this.rotationMode.name},fillTextureSettings:{randomize:this.randomizeFill,size:this.fillTextureSize,offset:this.fillTextureOffset}}}static fromJSON(t){t.particleSettings.blendMode=Bt[t.particleSettings.blendMode],t.particleSettings.rotationMode=Xt.RotationMode[t.particleSettings.rotationMode];let e=Array.isArray(t.shape)?t.shape.map((t=>Dt.fromJSON(t))):Dt.fromJSON(t.shape),i=Dt.fromJSON(t.fill);return new Xt(t.name,e,i,t.particleSettings,t.fillTextureSettings)}equals(t){return t==this&&t.shapeTexture==this.shapeTexture&&t.fillTexture==this.fillTexture}delete(){this.deleteShape(),this.deleteFill(),delete this.ctx}deleteShape(){this.shapeTexture&&(this.ctx.deleteTexture(this.shapeTexture.texture),delete this.shapeTexture)}deleteFill(){this.fillTexture&&(this.ctx.deleteTexture(this.fillTexture.texture),delete this.fillTexture)}}Object.defineEnum(Xt,"RotationMode",["NONE","RANDOM","TRAJECTORY"]);class zt{constructor(t){this.phase=t.phase;let e=isNaN(t.altitude)||isNaN(t.azimuth)?void 0:{altitude:t.altitude,azimuth:t.azimuth};Object.defineProperty(this,"x",{value:t.x,enumerable:!0}),Object.defineProperty(this,"y",{value:t.y,enumerable:!0}),Object.defineProperty(this,"z",{value:t.z,enumerable:!0}),Object.defineProperty(this,"timestamp",{value:t.timestamp,enumerable:!0,writable:!0}),Object.defineProperty(this,"force",{value:t.pressure,enumerable:!0}),Object.defineProperty(this,"pressure",{value:t.pressure,enumerable:!0}),Object.defineProperty(this,"rotation",{value:t.rotation,enumerable:!0}),Object.defineProperty(this,"radiusX",{value:t.radiusX,enumerable:!0}),Object.defineProperty(this,"radiusY",{value:t.radiusY,enumerable:!0}),Object.defineProperty(this,"altitude",{get:()=>(e||(e=this.computeTilt(t)||{}),e.altitude),enumerable:!0}),Object.defineProperty(this,"azimuth",{get:()=>(e||(e=this.computeTilt(t)||{}),e.azimuth),enumerable:!0}),t.pointer&&Object.defineProperty(this,"pointer",{value:t.pointer,enumerable:!0}),this.computedAzimuth=void 0}createPathPoint(t){return new b(this.x,this.y,this.z,t)}computeTilt(t){if(isNaN(t.tiltX)||isNaN(t.tiltY))return;let{tiltX:e,tiltY:i}=t,s=Math.tan(Math.toRadians(e)),r=Math.tan(Math.toRadians(i)),n=Math.sqrt(s*s+r*r);return{altitude:Math.atan2(1,n),azimuth:Math.atan2(r,s)}}speed(t,e){let i={x:0,y:0,time:0};return i=t&&!e?this.minus(t):e&&!t?e.minus(this):e.minus(t),i.time>0?zt.getMagnitude(i.x,i.y)/(i.time/1e3):(0==i.time||console.warn(`Speed out of range: ${i.time}ms`),0)}computeNearestAzimuthAngle(t){let e;if(isNaN(this.azimuth))return 0;if(t){if(isNaN(t.azimuth))return 0;let i=2*Math.PI,s=t.computedAzimuth||t.azimuth,r=parseInt(s/i);e=this.azimuth+r*i;let n=e-s;n>=Math.PI?e-=i:n<-Math.PI&&(e+=i)}else e=this.azimuth;return this.computedAzimuth=e,e}minus(t){return{x:this.x-t.x,y:this.y-t.y,time:this.timestamp-t.timestamp}}static getMagnitude(t,e){return Math.sqrt(t*t+e*e)}}Object.defineEnum(zt,"Property",["X","Y","Z","PHASE","TIMESTAMP","PRESSURE","RADIUS_X","RADIUS_Y","ALTITUDE","AZIMUTH","ROTATION"]);class Gt{constructor(t=[],e=[]){this.accumulatedAddition=t,this.lastPrediction=e,this.first=!1,this.last=!1}add(t,e,i=[]){t==_.Phase.BEGIN?this.reset(!0):t==_.Phase.END&&(this.last=!0),e&&this.accumulatedAddition.push(...e),this.lastPrediction=i}clone(){let t=new Gt(this.accumulatedAddition.slice(),this.lastPrediction.slice());return t.first=this.first,t.last=this.last,t}reset(t=!1){this.first=t,this.last=!1,this.accumulatedAddition.clear(),this.lastPrediction.clear()}}const Ht=[bt.SMOOTHER,bt.POLYGON_MERGER,bt.POLYGON_SIMPLIFIER],Jt=[bt.SPLINE_PRODUCER,bt.SPLINE_INTERPOLATOR,bt.BRUSH_APPLIER,bt.CONVEX_HULL_CHAIN_PRODUCER,bt.POLYGON_MERGER,bt.POLYGON_SIMPLIFIER];class Vt{#c;constructor(){this.layout=[b.Property.X,b.Property.Y],this.pathSegment=new Gt,this.pathProducer=new Q(this.layout),this.smoother=new et(this.layout.length),this.splineProducer=new it(this.layout),this.distanceInterpolator=new nt,this.curvatureInterpolator=new lt,this.brushApplier=new pt,this.polygonMerger=new gt,this.polygonSimplifier=new yt,this.splineProducer.keepAllData=!0,this.phase=void 0,this.pointerID=void 0,this.concatSegments=!1,this.lastPipelineStage=void 0,this.excludedPipelineStages=[],this.configured=!1,Object.defineProperty(this,"allData",{get:()=>{let t={};return this.lastPipelineStage&&(this.smoother.keepAllData&&(t.smootherPoints=this.smoother.allData),this.splineInterpolator.keepAllData&&this.lastPipelineStage.value>bt.SPLINE_INTERPOLATOR.value&&(t.interpolatedSpline=this.splineInterpolator.allData),this.brushApplier.keepAllData&&this.lastPipelineStage.value>bt.BRUSH_APPLIER.value&&(t.shapesPath=this.brushApplier.allData),this.convexHullChainProducer.keepAllData&&this.lastPipelineStage.value>bt.CONVEX_HULL_CHAIN_PRODUCER.value&&(t.convexPath=this.convexHullChainProducer.allData)),t}}),Object.defineProperty(this,"prediction",{get:()=>this.pathProducer.prediction,set:t=>this.pathProducer.prediction=t,enumerable:!0})}configure(t={}){if(this.reset(this.pointerID),t.onBuildComplete)throw new Error("[InkBuilderSettings] onBuildComplete property is deprecated. Use InkBuilder instance onComplete property to set callback.");if("mergePrediction"in t&&console.warn("[InkBuilderSettings] 'mergePrediction' property is deprecated. Do not affects PolygonMerger behaviour."),!t.brush)throw new Error("[InkBuilderSettings] brush property is required");if(t.excludedPipelineStages){if(!Array.isArray(t.excludedPipelineStages))throw new Error("Expected type of excludedPipelineStages is Array instance");let e=t.excludedPipelineStages.filter((t=>!Ht.includes(t)));e.length>0&&console.warn(`[InkBuilderSettings] excludedPipelineStages property includes steps which cannot be excluded: ${e.map((t=>t.name)).join(", ")}`),this.excludedPipelineStages=t.excludedPipelineStages.slice()}if(!this.excludedPipelineStages.includes(bt.SMOOTHER)&&t.movingAverageWindowSize&&(this.smoother.movingAverageWindowSize=t.movingAverageWindowSize),t.lastPipelineStage){if(!Jt.includes(t.lastPipelineStage))throw new Error(`[InkBuilderSettings] lastPipelineStage property expects one of: ${Jt.map((t=>t.name)).join(", ")}`);if(this.excludedPipelineStages.includes(t.lastPipelineStage))throw new Error(`[InkBuilderSettings] lastPipelineStage ${t.lastPipelineStage.name} is disabled, check excludedPipelineStages configuration`);if(t.brush instanceof Xt&&t.lastPipelineStage!=bt.SPLINE_INTERPOLATOR)throw new Error(`[InkBuilderSettings] lastPipelineStage ${t.lastPipelineStage.name} is not compatible with provided brush`);this.lastPipelineStage=t.lastPipelineStage}switch(this.brush=t.brush,this.brush instanceof $t&&(this.brushApplier.brush=this.brush),this.lastPipelineStage||(this.brush instanceof $t?(this.brush.spacing>1?this.lastPipelineStage=bt.BRUSH_APPLIER:this.excludedPipelineStages.includes(bt.POLYGON_SIMPLIFIER)&&this.excludedPipelineStages.includes(bt.POLYGON_MERGER)?this.lastPipelineStage=bt.CONVEX_HULL_CHAIN_PRODUCER:this.lastPipelineStage=bt.POLYGON_MERGER,this.lastPipelineStage==bt.POLYGON_MERGER&&(this.concatSegments=Boolean(t.concatSegments))):this.lastPipelineStage=bt.SPLINE_INTERPOLATOR),this.lastPipelineStage==bt.SPLINE_INTERPOLATOR||this.lastPipelineStage==bt.BRUSH_APPLIER?(this.splineInterpolator=this.distanceInterpolator,this.splineInterpolator.spacing=this.brush.spacing,this.splineInterpolator.scattering=this.brush.scattering,this.splineInterpolator.calculateDerivates=this.brush instanceof Xt):(this.splineInterpolator=this.curvatureInterpolator,this.splineInterpolator.errorThreshold=t.errorThreshold||.15),this.splineInterpolator.keepSplineParameters=!!t.keepSplineParameters,this.splineInterpolator.keepAllData=!1,this.brushApplier.keepAllData=!1,this.convexHullChainProducer.keepAllData=!1,this.polygonMerger.keepAllData=!1,this.polygonSimplifier.keepAllData=!1,this.lastPipelineStage){case bt.SPLINE_PRODUCER:break;case bt.SPLINE_INTERPOLATOR:this.splineInterpolator.keepAllData=!0;break;case bt.BRUSH_APPLIER:this.brushApplier.keepAllData=!0;break;case bt.CONVEX_HULL_CHAIN_PRODUCER:this.convexHullChainProducer.keepAllData=!0;break;case bt.POLYGON_MERGER:this.polygonMerger.keepAllData=!0;break;case bt.POLYGON_SIMPLIFIER:this.polygonSimplifier.keepAllData=!0;break;default:throw console.warn(this.lastPipelineStage),new Error("[InkBuilderSettings] Invalid lastPipelineStage found")}if(this.lastPipelineStage==bt.POLYGON_SIMPLIFIER&&(console.warn("[InkBuilderSettings] Pipeline stage POLYGON_SIMPLIFIER is deprecated. POLYGON_MERGER stage is recommended as last stage."),this.polygonSimplifier.epsilon=t.epsilon||.1),t.keepAllData){t.keepAllData.includes(this.lastPipelineStage)&&(console.warn(`[InkBuilderSettings] keepAllData contains last pipeline stage ${this.lastPipelineStage}. Duplicate is dropped.`),t.keepAllData.remove(this.lastPipelineStage)),t.keepAllData.includes(bt.PATH_PRODUCER)&&(console.warn(`[InkBuilderSettings] keepAllData contains stage ${bt.PATH_PRODUCER}, sensor input is accessible through InputDevice output - SensorData. Dropped from keepAllData.`),t.keepAllData.remove(bt.PATH_PRODUCER)),t.keepAllData.includes(bt.SPLINE_PRODUCER)&&(console.warn(`[InkBuilderSettings] keepAllData contains stage ${bt.SPLINE_PRODUCER}. Use getSpline() method to acceess spline data. Dropped from keepAllData.`),t.keepAllData.remove(bt.SPLINE_PRODUCER));for(let e of t.keepAllData){if(this.excludedPipelineStages.includes(e))throw new Error(`[InkBuilderSettings] keepAllData contains stage ${e}, configured as stage in excludedPipelineStages.`);switch(e){case bt.SMOOTHER:this.smoother.keepAllData=!0;break;case bt.SPLINE_INTERPOLATOR:this.splineInterpolator.keepAllData=!0;break;case bt.BRUSH_APPLIER:this.brushApplier.keepAllData=!0;break;case bt.CONVEX_HULL_CHAIN_PRODUCER:this.convexHullChainProducer.keepAllData=!0;break;default:throw console.warn(e),new Error("Invalid stage found")}}this.#c=t.keepAllData}else this.#c=[];if(t.pathPointCalculator&&(this.calculator=t.pathPointCalculator,this.pathProducer.pathPointCalculator=t.pathPointCalculator),!t.layout)throw new Error("[InkBuilderSettings] layout property is required");{let e=t.pathPointProps||{};if(this.layout=t.layout,this.brush instanceof $t){if(this.layout.includes(b.Property.RED))throw new Error("RED layout channel is not supported for non particles strokes");if(this.layout.includes(b.Property.GREEN))throw new Error("GREEN layout channel is not supported for non particles strokes");if(this.layout.includes(b.Property.BLUE))throw new Error("BLUE layout channel is not supported for non particles strokes");if(this.layout.includes(b.Property.ALPHA))throw new Error("ALPHA layout channel is not supported for non particles strokes")}if(!this.layout.includes(b.Property.RED)&&isNaN(e.red))throw new Error("Stroke color red channel information is required. Please provide via layout or through configure settings via pathPointProps property.");if(!this.layout.includes(b.Property.GREEN)&&isNaN(e.green))throw new Error("Stroke color green channel information is required. Please provide via layout or through configure settings via pathPointProps property.");if(!this.layout.includes(b.Property.BLUE)&&isNaN(e.blue))throw new Error("Stroke color blue channel information is required. Please provide via layout or through configure settings via pathPointProps property.");if(!this.layout.includes(b.Property.ALPHA)&&isNaN(e.alpha))throw new Error("Stroke color alpha channel information is required. Please provide via layout or through configure settings via pathPointProps property.");this.pathProducer.layout=this.layout,this.smoother.dimsCount=this.layout.length,this.splineProducer.layout=this.layout,this.splineProducer.pathPointProps=e}this.configured=!0}add(t,e){if(!this.configured)throw new Error("InkBuilder instance is not configured yet, use configure method to configure the instance.");if(!this.calculator)throw new Error("InkBuilder instance is not configured properly, pathPointCalculator property is required");if(!t.phase)throw new Error("SensorPoint phase is not found");this.phase=t.phase;let i,s=new zt(t);e&&(this.prediction?i=new zt(e):console.warn("Prediction sensor point is available, but ignored, prediction is disabled")),this.device&&(this.phase==Q.Phase.BEGIN&&this.device.openStream(t),this.device.add(s),this.phase==Q.Phase.END&&(this.sensorData=this.device.closeStream()));let r=this.pathProducer.add(this.phase,s,i);this.pathSegment.add(this.phase,r.added,r.predicted)}ignore(t){if(!t.phase)throw new Error("SensorPoint phase is not found");this.device&&t&&t.phase==Q.Phase.UPDATE&&this.device.add(new zt(t),!0)}build(){throw new Error("InkBuilderAbstract.build() is abstract and should be implemented")}processSegment(t,e,i){throw new Error("InkBuilderAbstract.processSegment(path, type, lastSegment) is abstract and should be implemented")}getSensorData(){return this.sensorData}getSpline(){return this.splineProducer.allData}getAllData(){if(0==this.#c.length)return;let t={};for(let e of this.#c)switch(e){case bt.SMOOTHER:t.smoother=this.smoother.allData;break;case bt.SPLINE_INTERPOLATOR:t.interpolatedSpline=this.splineInterpolator.allData;break;case bt.BRUSH_APPLIER:t.shapesPath=this.brushApplier.allData;break;case bt.CONVEX_HULL_CHAIN_PRODUCER:t.convexPath=this.convexHullChainProducer.allData;break;default:throw console.warn(e),new Error("Invalid stage found")}return t}getInkPath(){let t;switch(this.lastPipelineStage){case bt.SPLINE_PRODUCER:return void console.warn("Pipeline stage SPLINE_PRODUCER is configured as lastPipelineStage. Ink Path is a result from Spline processing.");case bt.SPLINE_INTERPOLATOR:t=this.splineInterpolator.allData;break;case bt.BRUSH_APPLIER:t=this.brushApplier.allData;break;case bt.CONVEX_HULL_CHAIN_PRODUCER:t=this.convexHullChainProducer.allData;break;case bt.POLYGON_MERGER:t=this.polygonMerger.allData;break;case bt.POLYGON_SIMPLIFIER:t=this.polygonSimplifier.allData;break;default:throw console.warn(this.lastPipelineStage),new Error("Invalid lastPipelineStage found")}if(this.concatSegments){let e;this.lastPipelineStage!=bt.POLYGON_MERGER&&this.lastPipelineStage!=bt.POLYGON_SIMPLIFIER||(e=this.polygonMerger.process(t)),this.lastPipelineStage==bt.POLYGON_SIMPLIFIER&&(e=this.polygonSimplifier.process(e)),e&&(t=new ct(e))}return t}abort(){this.device&&this.device.closeStream(!0),this.reset()}reset(t){this.pointerID=t,this.phase=void 0,this.concatSegments=!1,this.lastPipelineStage=void 0,this.excludedPipelineStages.clear(),this.sensorData=void 0,this.pathProducer.reset(),this.smoother.reset(),this.splineProducer.reset(),this.distanceInterpolator.reset(),this.curvatureInterpolator.reset(),this.brushApplier.reset(),this.convexHullChainProducer.reset(),this.polygonMerger.reset(),this.polygonSimplifier.reset(),this.configured=!1}}Vt.Phase=Q.Phase;class Zt extends Vt{constructor(){super(),this.convexHullChainProducer=new dt}build(){let t=this.buildSegment();return t.phase=this.phase,t.pointerID=this.pointerID,this.onComplete&&this.onComplete(t),this.phase==Et.END&&(delete this.phase,delete this.pipeline),t}buildSegment(){let t={};return this.pathSegment.accumulatedAddition.length>0&&(t.added=this.processSegment(this.pathSegment.accumulatedAddition,St.ADDITION,this.pathSegment.last),t.pipeline=this.pipeline,t.added&&(t.added.segment=!0)),this.prediction&&this.pathSegment.lastPrediction.length>0&&(t.predicted=this.processSegment(this.pathSegment.lastPrediction,St.PREDICTION,this.pathSegment.last),t.predicted&&(t.predicted.segment=!0)),this.pathSegment.reset(),t}processSegment(t,e,i){if(this.excludedPipelineStages.includes(bt.SMOOTHER)||(t=this.smoother.process(t,e,i)),t=this.splineProducer.process(t,e,i))return this.lastPipelineStage==bt.SPLINE_PRODUCER?t:this.processSpline(t,e,i)}processSpline(t,e=St.PROCESSOR,i=!0){e==St.ADDITION&&(this.pipeline={}),e==St.ADDITION&&(this.pipeline.spline=t);let s,r=this.splineInterpolator.process(t,e,i);if(this.lastPipelineStage==bt.SPLINE_INTERPOLATOR)return r;if(r)return e==St.ADDITION&&(this.pipeline.interpolatedSpline=r),r=this.brushApplier.process(r,e,i),this.lastPipelineStage==bt.BRUSH_APPLIER?r:(e==St.ADDITION&&(this.pipeline.shapesPath=r),r=this.convexHullChainProducer.process(r,e,i),this.lastPipelineStage==bt.CONVEX_HULL_CHAIN_PRODUCER?r:(e==St.ADDITION&&(this.pipeline.convexPath=r),e==St.PREDICTION?r:this.excludedPipelineStages.includes(bt.POLYGON_MERGER)||(s=this.polygonMerger.process(r,e,i),this.lastPipelineStage!=bt.POLYGON_MERGER)?(this.excludedPipelineStages.includes(bt.POLYGON_SIMPLIFIER)||(s=this.polygonSimplifier.process(s,e,i)),new ct(s)):new ct(s)));if(e==St.PROCESSOR)throw new Error("InkBuilder processSpline failed for spline",t)}}(class extends class{constructor(){this.worker,this.transferables=[]}async recieve(t){let e;"INIT"==t.action?(this.worker=t.worker,e=await this.init(t)):e=await this.process(t),e.worker=this.worker,this.send(e)}send(t){self.postMessage(t,this.transferables),this.transferables.length=0}async init(t){return t}async process(t){throw new Error("ThreadProcessor.process(message) is abstract and should be implemented")}static async connect(...t){let e=new this(...t);if("undefined"==typeof self){const t=await import("worker_threads"),{parentPort:e,workerData:i}=t;global.self=e,self.name=i.name,self.data=i}self.on("message",(async t=>await e.recieve(t)))}}{constructor(){super(),this.builder=new Zt,this.brushes={}}process(t){let e={action:t.action,actionID:t.actionID};switch(t.action){case"IMPORT_BRUSHES":this.importBrushes(t.brushes);break;case"BUILD":{let i=this.build(t.brushName,t.spline,t.settings);e=Object.assign(e,i),e.index=t.index;break}default:throw new Error(`Unknow data action found: ${t.action}`)}return e}importBrushes(t){for(let e of t)this.brushes[e.name]||("Brush2D"==e.type?this.brushes[e.name]=$t.fromJSON(e):this.brushes[e.name]=Xt.fromJSON(e))}build(t,e,i){let s={},r=this.brushes[t],n=M.fromJSON(e);i=Object.assign({brush:r,layout:n.layout,pathPointProps:n.pointProps},this.decodeSettings(i)),this.builder.configure(i);let a=this.builder.processSpline(n);if(n.points.buffer instanceof ArrayBuffer&&(s.splineBuffer=n.points.buffer,this.transferables.push(n.points.buffer)),a instanceof L&&(a.points.buffer instanceof ArrayBuffer&&this.transferables.push(a.points.buffer),a.encoding=v.Encoding.NONE),s.path=a.toJSON(),Object.keys(this.builder.allData).length>0){let{interpolatedSpline:t,shapesPath:e,convexPath:i}=this.builder.allData;s.pipeline={},t&&(t.points.buffer instanceof ArrayBuffer&&this.transferables.push(t.points.buffer),t.encoding=v.Encoding.NONE,s.pipeline.interpolatedSpline=t.toJSON()),e&&(s.pipeline.shapesPath=e.toJSON()),i&&(s.pipeline.convexPath=i.toJSON())}return s}decodeSettings(t){if(t)return t.excludedPipelineStages&&(t.excludedPipelineStages=t.excludedPipelineStages.map((t=>bt[t]))),t.lastPipelineStage&&(t.lastPipelineStage=bt[t.lastPipelineStage]),t.keepAllData&&(t.keepAllData=t.keepAllData.map((t=>bt[t]))),t}}).connect();