openstamanager/assets/src/js/wacom/sigCaptDialog/libs/will/digital-ink/digital-ink-min.cjs

2 lines
362 KiB
JavaScript
Executable File

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),require("js-ext");var e=require("js-md5"),t=require("long"),r=require("gl-matrix"),i=require("poly2tri"),s=require("clipper-lib"),n=require("rbush"),o=require("jszip"),a=require("protobufjs");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function h(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var d=h(e),c=l(t),p=h(i),u=h(s),f=l(n),m=h(o),g=h(a);class y{getInkBuilder(e){throw new Error("InkController.getInkBuilder(pointerID) is abstract and should be implemented")}registerInputProvider(e,t){throw new Error("InkController.registerInputProvider(pointerID, isPrimary) is abstract and should be implemented")}reset(e){throw new Error("InkController.reset(sensorPoint) is abstract and should be implemented")}begin(e){throw new Error("InkController.begin(sensorPoint) is abstract and should be implemented")}move(e,t){throw new Error("InkController.move(sensorPoint, [prediction]) is abstract and should be implemented")}end(e){throw new Error("InkController.end(sensorPoint) is abstract and should be implemented")}abort(e){throw new Error("InkController.abort(pointerID) is abstract and should be implemented")}resize(e){throw new Error("InkController.resize() is abstract and should be implemented")}}let b=d?d.default||globalThis.md5:{},E={mask:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",generate(){let e=Date.now();return this.mask.replace(/[xy]/g,(function(t){let r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)}))},validate:e=>"string"==typeof e&&!!e.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(e){let t=[],r=0;return this.mask.split("-").forEach((i=>{t.push(e.substring(r,r+i.length)),r+=i.length})),t.join("-")},fromString(e){return this.fromBytes(new Uint8Array(b.arrayBuffer(e)))},toBytes(e){let t=[];return e.split("-").map(((e,r)=>{(r<3?e.match(/.{1,2}/g).reverse():e.match(/.{1,2}/g)).map((e=>t.push(parseInt(e,16))))})),new Uint8Array(t)},fromBytes(e){let t=Array.from(e).map((e=>e.toString(16))).map((e=>(1==e.length?"0":"")+e));return t.slice(0,4).reverse().join("")+"-"+t.slice(4,6).reverse().join("")+"-"+t.slice(6,8).reverse().join("")+"-"+t.slice(8,10).join("")+"-"+t.slice(10).join("")},toUint32Array(e){let t=new Uint32Array(4),r=this.toBytes(e);return t[0]=new Uint32Array(r.slice(0,4).buffer)[0],t[1]=new Uint32Array(r.slice(4,8).buffer)[0],t[2]=new Uint32Array(r.slice(8,12).buffer)[0],t[3]=new Uint32Array(r.slice(12).buffer)[0],t},fromUint32Array(e){return this.fromBytes(new Uint8Array(e.buffer))},toUint64Array(e){let t=new BigUint64Array(2),r=this.toBytes(e);return t[0]=new BigUint64Array(r.slice(0,8).buffer)[0],t[1]=new BigUint64Array(r.slice(8).buffer)[0],t},fromUint64Array(e){return this.fromBytes(new Uint8Array(e.buffer))},toLongArray(e){let t=new Array(2),r=this.toBytes(e);return t[0]=c.default.fromBytes(r.slice(0,8)),t[1]=c.default.fromBytes(r.slice(8)),t},fromLongArray(e){let t=e[0].toBytes().concat(e[1].toBytes());return this.fromBytes(t)}};class P{static get SEPARATOR(){return"\n"}#e;constructor(e){let t;if(this.#e=e,"function"==typeof this.getMD5Message)t=P.Algorithm.MD5;else if("function"==typeof this.buildURI)t=P.Algorithm.URI;else if(t=P.Algorithm.GUID,e&&!E.validate(e))throw new Error(`Identifiable ${e} is not a well formed UUID`);Object.defineProperty(this,"algorithm",{value:t}),Object.defineProperty(this,"id",{get:()=>(this.#e||(this.#e=this.resolveID()),this.#e),set:e=>{if(this.#e)throw new Error("id is immutable");this.#e=e},enumerable:!0})}invalidateID(){if(this.algorithm!=P.Algorithm.MD5)throw new Error(`Invalidate id is not applicable for ${this.algorithm} algorithm`);this.#e=void 0}resolveID(){if(this.algorithm==P.Algorithm.MD5){let e="",t=this.getMD5Message();for(let r of t){if(Array.isArray(r))for(let t of r)e+=t,e+="\n";else e+=r;e+="\n"}if(!e)throw new Error("Empty MD5 message container found");return b(e)}return this.algorithm==P.Algorithm.URI?this.buildURI():E.generate()}static buildMD5Tokens(e){let t=[];return Object.keys(e).sort().forEach((r=>t.push(r,e[r]))),t}}Object.defineEnum(P,"Algorithm",["GUID","MD5","URI"]);class I extends P{constructor(e,t={}){super(),this.type=e,this.props=Object.assign({},t)}getMD5Message(){if(!Object.isFrozen(this))throw new Error("ID generation failed. InkInputProvider do not belongs to any SensorChannelsContext yet");return["InkInputProvider",this.type.name,P.buildMD5Tokens(this.props)]}}Object.defineEnum(I,"Type",["PEN","TOUCH","MOUSE","CONTROLLER"]);class S{constructor(){this.phase=S.Phase.END}add(e,t,r){if(!this.move(e))throw new Error(`Cannot move from phase ${this.phase.name} to phase ${e.name}`);return this.debug&&(console.log("-------------------------------------"),console.log(this.constructor.name,e.name)),this.addImpl(t,r)}addImpl(e,t){throw new Error("Abstract method addImpl of DataProcessor should be implemented")}move(e){return(this.phase!=S.Phase.END||e==S.Phase.BEGIN)&&((this.phase!=S.Phase.BEGIN||e==S.Phase.UPDATE||e==S.Phase.END)&&((this.phase!=S.Phase.UPDATE||e==S.Phase.UPDATE||e==S.Phase.END)&&(e==S.Phase.BEGIN&&this.reset(),this.phase=e,!0)))}reset(){this.phase=S.Phase.END}}Object.defineEnum(S,"Phase",["BEGIN","UPDATE","END"]);class w{constructor(e,t,i,s){if(isNaN(e))throw new Error(`Invalid x found: ${e}`);if(isNaN(t))throw new Error(`Invalid y found: ${t}`);let n=[e,t];isFinite(i)&&(n.push(i),isFinite(s)&&n.push(s)),this.value=n.toFloat32Array(),Object.defineProperty(this,"x",{get:()=>this.value[0],set:e=>{this.value[0]=e},enumerable:!0}),Object.defineProperty(this,"y",{get:()=>this.value[1],set:e=>{this.value[1]=e},enumerable:!0}),2==n.length?this.vec=r.vec2:3==n.length?(this.vec=r.vec3,Object.defineProperty(this,"z",{get:()=>this.value[2],set:e=>{this.value[2]=e},enumerable:!0})):(this.vec=r.vec4,Object.defineProperty(this,"w",{get:()=>this.value[3],set:e=>{this.value[3]=e},enumerable:!0}))}add(e){e instanceof w||(e=w.fromPoint(e));let t=this.vec.create();return this.vec.add(t,this.value,e.value),w.fromPoint(t)}addSelf(e){return e instanceof w||(e=w.fromPoint(e)),this.vec.add(this.value,this.value,e.value),this}subtract(e){e instanceof w||(e=w.fromPoint(e));let t=this.vec.create();return this.vec.subtract(t,this.value,e.value),w.fromPoint(t)}subtractSelf(e){return e instanceof w||(e=w.fromPoint(e)),this.vec.subtract(this.value,this.value,e.value),this}multiply(e){e instanceof w||(e=w.fromPoint(e));let t=this.vec.create();return this.vec.multiply(t,this.value,e.value),w.fromPoint(t)}multiplySelf(e){return e instanceof w||(e=w.fromPoint(e)),this.vec.multiply(this.value,this.value,e.value),this}divide(e){e instanceof w||(e=w.fromPoint(e));let t=this.vec.create();return this.vec.divide(t,this.value,e.value),w.fromPoint(t)}divideSelf(e){return e instanceof w||(e=w.fromPoint(e)),this.vec.divide(this.value,this.value,e.value),this}scale(e){let t=this.vec.create();return this.vec.scale(t,this.value,e),w.fromPoint(t)}scaleSelf(e){return this.vec.scale(this.value,this.value,e),this}abs(){return new w(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(e){if(!e)return this;let t=this.vec.create();return this.vec.transformMat4(t,this.value,e.toFloat32Array()),w.fromPoint(t)}transformSelf(e){return this.vec.transformMat4(this.value,this.value,e.toFloat32Array()),this}toFloat32Array(){return this.value}toJSON(){let e={x:this.x,y:this.y};return isFinite(this.z)&&(e.z=this.z,isFinite(this.w)&&(e.w=this.w)),e}toString(){return`point(${this.value.join(", ")})`}clone(){return w.fromPoint(this)}static fromPoint(e){return Array.isArray(e)||ArrayBuffer.isTypedArray(e)?new w(e[0],e[1],e[2],e[3]):new w(e.x,e.y,e.z,e.w)}}class x{constructor(e,t,r,i){let s=e,n=t,o=e+r,a=t+i;Object.defineProperties(this,{left:{value:s,enumerable:!0},x:{value:e,enumerable:!0},bottom:{value:n,enumerable:!0},y:{value:t,enumerable:!0},right:{value:o,enumerable:!0},top:{value:a,enumerable:!0},width:{value:r,enumerable:!0},height:{value:i,enumerable:!0}})}union(e){if(e&&!(e instanceof x))throw new TypeError("rect must be instance of RectGL");return e?x.ofEdges(Math.min(this.left,e.left),Math.min(this.bottom,e.bottom),Math.max(this.right,e.right),Math.max(this.top,e.top)):this}intersect(e){if(e&&!(e instanceof x))throw new TypeError("rect must be instance of RectGL");if(!e)return null;let t=x.ofEdges(Math.max(this.left,e.left),Math.max(this.bottom,e.bottom),Math.min(this.right,e.right),Math.min(this.top,e.top));return t.width>0&&t.height>0?t:null}ceil(){return x.ofEdges(Math.floor(this.left),Math.floor(this.bottom),Math.ceil(this.right),Math.ceil(this.top))}floor(){return x.ofEdges(Math.ceil(this.left),Math.ceil(this.bottom),Math.floor(this.right),Math.floor(this.top))}transform(e){if(!e)return this;let t=w.fromPoint({x:this.left,y:this.bottom}).transform(e),r=w.fromPoint({x:this.right,y:this.bottom}).transform(e),i=w.fromPoint({x:this.left,y:this.top}).transform(e),s=w.fromPoint({x:this.right,y:this.top}).transform(e),n=Math.min(i.x,s.x,t.x,r.x),o=Math.min(i.y,s.y,t.y,r.y),a=Math.max(i.x,s.x,t.x,r.x),l=Math.max(i.y,s.y,t.y,r.y);return x.ofEdges(n,o,a,l)}toQuad(e){let t;if(e){let i=w.fromPoint({x:this.left,y:this.bottom}).transform(e),s=w.fromPoint({x:this.right,y:this.bottom}).transform(e),n=w.fromPoint({x:this.left,y:this.top}).transform(e),o=w.fromPoint({x:this.right,y:this.top}).transform(e);t=r.quat2.fromValues(i.x,i.y,s.x,s.y,n.x,n.y,o.x,o.y)}else t=r.quat2.fromValues(this.left,this.bottom,this.right,this.bottom,this.left,this.top,this.right,this.top);return t}toString(){return`gl-rect(${this.x}, ${this.y}, ${this.width}, ${this.height})`}static ofEdges(e,t,r,i){return new x(e,t,r-e,i-t)}static calculateBrushGLSegmentBounds(e,t=0,r){let i,s=.5*e.size,n=Math.abs(t*s);if(r){i=new w(e.x,e.y,e.x,e.z).transform(r)}else i=e;let o=i.x,a=i.y,l=e.scaleX*s,h=e.scaleY*s,d=e.offsetX,c=-e.offsetY,p=Math.cos(e.rotation),u=Math.sin(e.rotation),f=Number.MAX_SAFE_INTEGER,m=Number.MIN_SAFE_INTEGER,g=Number.MAX_SAFE_INTEGER,y=Number.MIN_SAFE_INTEGER;for(let e of x.SQURE){let t=e.x*l+d,r=e.y*h+c,i=p*t+u*r+o,s=-u*t+p*r+a,b=i-n;f=Math.min(f,b),m=Math.max(m,b),b=i+n,f=Math.min(f,b),m=Math.max(m,b);let E=s-n;g=Math.min(g,E),y=Math.max(y,E),E=s+n,g=Math.min(g,E),y=Math.max(y,E)}return x.ofEdges(f,g,m,y)}}Object.defineProperty(x,"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 v{constructor(e,t,r,i){let s,n,o,a=e,l=t,h=e+r,d=t+i;Object.defineProperties(this,{left:{value:a,enumerable:!0},top:{value:l,enumerable:!0},right:{value:h,enumerable:!0},bottom:{value:d,enumerable:!0},x:{value:e,enumerable:!0},y:{value:t,enumerable:!0},width:{value:r,enumerable:!0},height:{value:i,enumerable:!0},size:{get:()=>(s||(s={width:r,height:i}),s),enumerable:!0},area:{get:()=>(n||(n=r*i),n),enumerable:!0},center:{get:()=>(o||(o={x:(a+h)/2,y:(l+d)/2}),o),enumerable:!0}})}union(e){return e?v.ofEdges(Math.min(this.left,e.left),Math.min(this.top,e.top),Math.max(this.right,e.right),Math.max(this.bottom,e.bottom)):this}intersect(e){if(!e)return null;let t=v.ofEdges(Math.max(this.left,e.left),Math.max(this.top,e.top),Math.min(this.right,e.right),Math.min(this.bottom,e.bottom));return t.width>0&&t.height>0?t:null}intersects(e){return this.left<=e.right&&this.right>=e.left&&this.top<=e.bottom&&this.bottom>=e.top}ceil(e){let t=Math.floor(this.left),r=Math.floor(this.top),i=Math.ceil(this.right),s=Math.ceil(this.bottom);if(e){let e=i-t,n=s-r;e+=e%2,n+=n%2,i=t+e,s=r+n}return v.ofEdges(t,r,i,s)}floor(e){let t=Math.ceil(this.left),r=Math.ceil(this.top),i=Math.floor(this.right),s=Math.floor(this.bottom);if(e){let e=i-t,n=s-r;e-=e%2,n-=n%2,i=t+e,s=r+n}return v.ofEdges(t,r,i,s)}contains(e){return this.left<=e.x&&this.right>=e.x&&this.top<=e.y&&this.bottom>=e.y}includes(e){return this.left<=e.left&&this.right>=e.right&&this.top<=e.top&&this.bottom>=e.bottom}transform(e){if(!e)return this;let t=w.fromPoint({x:this.left,y:this.top}).transform(e),r=w.fromPoint({x:this.right,y:this.top}).transform(e),i=w.fromPoint({x:this.left,y:this.bottom}).transform(e),s=w.fromPoint({x:this.right,y:this.bottom}).transform(e),n=Math.min(t.x,r.x,i.x,s.x),o=Math.min(t.y,r.y,i.y,s.y),a=Math.max(t.x,r.x,i.x,s.x),l=Math.max(t.y,r.y,i.y,s.y);return v.ofEdges(n,o,a,l)}toPath(e,t=1){throw new Error("Rect.toPath is deprecated. Path.fromRect(rect, [pointProps]) instead")}toGLRect(){return new x(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(e){if(!e)return null;if(!(e instanceof x))throw new TypeError("rect must be instance of RectGL");return new v(e.left,e.bottom,e.width,e.height)}static isRect(e){return e&&isFinite(e.left)&&isFinite(e.top)&&isFinite(e.width)&&isFinite(e.height)}static fromString(e){return e=e.substring(e.indexOf("(")+1,e.indexOf(")")).split(/,\s*/g),new v(parseFloat(e[0]),parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3]))}static fromRect(e){return"string"==typeof e?v.fromString(e):new v(e.x,e.y,e.width,e.height)}static ofPolygon(e){if(e.shape&&(e=e.shape),0==e.length)return null;let t=Number.MAX_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER,i=Number.MIN_SAFE_INTEGER,s=Number.MIN_SAFE_INTEGER;for(let n=0;n<e.length;n++){let o=e.getPointX(n),a=e.getPointY(n);t=Math.min(t,o),r=Math.min(r,a),i=Math.max(i,o),s=Math.max(s,a)}return v.ofEdges(t,r,i,s)}static ofSpline(e,t=0){let r;for(let i=0;i<e.length;i++)r=x.calculateBrushGLSegmentBounds(e.getPointRef(i),t).union(r);return v.fromGLRect(r)}static ofEdges(e,t,r,i){let s=Math.min(e,r),n=Math.min(t,i),o=Math.max(e,r),a=Math.max(t,i);return new v(s,n,o-s,a-n)}static union(e,t){return e?t?e.union(t):e:t}static intersect(e,t){return e&&t?e.intersect(t):null}}const R={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},T=R.m11,A=R.m12,C=R.m21,O=R.m22,D=R.m41,k=R.m42;class N{constructor(e=r.mat4.create(),t=N.MultiplicationType.PRE){Object.defineProperty(this,"value",{value:e,enumerable:!0}),Object.defineProperty(this,"multiplicationType",{value:t,enumerable:!0});let i=function(e,t){let r=R[e];this.value[r]=t};Object.defineProperty(this,"a",{get:()=>this.value[T],set:i.bind(this,"m11"),enumerable:!0}),Object.defineProperty(this,"b",{get:()=>this.value[A],set:i.bind(this,"m12"),enumerable:!0}),Object.defineProperty(this,"c",{get:()=>this.value[C],set:i.bind(this,"m21"),enumerable:!0}),Object.defineProperty(this,"d",{get:()=>this.value[O],set:i.bind(this,"m22"),enumerable:!0}),Object.defineProperty(this,"e",{get:()=>this.value[D],set:i.bind(this,"m41"),enumerable:!0}),Object.defineProperty(this,"f",{get:()=>this.value[k],set:i.bind(this,"m42"),enumerable:!0}),Object.defineProperty(this,"tx",{get:()=>this.value[D],set:i.bind(this,"m41"),enumerable:!0}),Object.defineProperty(this,"ty",{get:()=>this.value[k],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 N(this.value.clone(),this.multiplicationType)}translate(e){return this.multiply(N.fromTranslate(e))}translateSelf(e){this.multiplySelf(N.fromTranslate(e))}rotate(e,t){return this.multiply(N.fromRotate(e,t))}rotateSelf(e,t){this.multiplySelf(N.fromRotate(e,t))}scale(e,t){return this.multiply(N.fromScale(e,t))}scaleSelf(e,t){this.multiplySelf(N.fromScale(e,t))}multiply(e){return this.multiplicationType==N.MultiplicationType.PRE?this.preMultiply(e):this.postMultiply(e)}preMultiply(e){let t=r.mat4.create();return r.mat4.multiply(t,e.toFloat32Array(),this.value),new N(t,this.multiplicationType)}postMultiply(e){let t=r.mat4.create();return r.mat4.multiply(t,this.value,e.toFloat32Array()),new N(t,this.multiplicationType)}multiplySelf(e){this.multiplicationType==N.MultiplicationType.PRE?this.preMultiplySelf(e):this.postMultiplySelf(e)}preMultiplySelf(e){r.mat4.multiply(this.value,e.toFloat32Array(),this.value)}postMultiplySelf(e){r.mat4.multiply(this.value,this.value,e.toFloat32Array())}invert(){let e=r.mat4.create();return r.mat4.invert(e,this.value),new N(e,this.multiplicationType)}invertSelf(){r.mat4.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(e){return w.fromPoint(e).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(e){if(e){let e=e=>((e<0?"":" ")+e.toPrecision(6)).substring(0,8);return" Matrix 4x4\n"+"-".repeat(39)+`\n${e(this.m11)}, ${e(this.m21)}, ${e(this.m31)}, ${e(this.m41)}`+`\n${e(this.m12)}, ${e(this.m22)}, ${e(this.m32)}, ${e(this.m42)}`+`\n${e(this.m13)}, ${e(this.m23)}, ${e(this.m33)}, ${e(this.m43)}`+`\n${e(this.m14)}, ${e(this.m24)}, ${e(this.m34)}, ${e(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(e,t){let i=r.mat4.create();if("none"!=e){let t=e.substring(0,e.indexOf("("));e=e.substring(e.indexOf("(")+1,e.indexOf(")")).split(/,\s*/g),"matrix3d"==t?(i[0]=parseFloat(e[0]),i[1]=parseFloat(e[1]),i[2]=parseFloat(e[2]),i[3]=parseFloat(e[3]),i[4]=parseFloat(e[4]),i[5]=parseFloat(e[5]),i[6]=parseFloat(e[6]),i[7]=parseFloat(e[7]),i[8]=parseFloat(e[8]),i[9]=parseFloat(e[9]),i[10]=parseFloat(e[10]),i[11]=parseFloat(e[11]),i[12]=parseFloat(e[12]),i[13]=parseFloat(e[13]),i[14]=parseFloat(e[14]),i[15]=parseFloat(e[15])):(i[T]=parseFloat(e[0]),i[A]=parseFloat(e[1]),i[C]=parseFloat(e[2]),i[O]=parseFloat(e[3]),i[D]=parseFloat(e[4]),i[k]=parseFloat(e[5]))}return new N(i,t)}static fromMatrix(e,t){if(!e)throw new Error("data not found, Matrix instance creation failed");if("function"==typeof e)throw new Error("data type function is not allowed");if(e instanceof N)return e;if(Array.isArray(e)&&(e=new Float32Array(e)),e instanceof Float32Array)return new N(e,t);if("string"==typeof e)return N.fromString(e,t);let i=r.mat4.create(),s=Object.assign({},e);return isFinite(e.a)&&(s.m11=e.a),isFinite(e.b)&&(s.m12=e.b),isFinite(e.c)&&(s.m21=e.c),isFinite(e.d)&&(s.m22=e.d),isFinite(e.tx)?s.m41=e.tx:isFinite(e.e)?s.m41=e.e:isFinite(e.dx)&&(s.m41=e.dx),isFinite(e.ty)?s.m42=e.ty:isFinite(e.f)?s.m42=e.f:isFinite(e.dy)&&(s.m42=e.dy),isFinite(s.m11)&&(i[0]=s.m11),isFinite(s.m12)&&(i[1]=s.m12),isFinite(s.m13)&&(i[2]=s.m13),isFinite(s.m14)&&(i[3]=s.m14),isFinite(s.m21)&&(i[4]=s.m21),isFinite(s.m22)&&(i[5]=s.m22),isFinite(s.m23)&&(i[6]=s.m23),isFinite(s.m24)&&(i[7]=s.m24),isFinite(s.m31)&&(i[8]=s.m31),isFinite(s.m32)&&(i[9]=s.m32),isFinite(s.m33)&&(i[10]=s.m33),isFinite(s.m34)&&(i[11]=s.m34),isFinite(s.m41)&&(i[12]=s.m41),isFinite(s.m42)&&(i[13]=s.m42),isFinite(s.m43)&&(i[14]=s.m43),isFinite(s.m44)&&(i[15]=s.m44),new N(i,t||e.multiplicationType)}static fromTranslate(e){let t=isFinite(e)?{tx:e,ty:e}:{tx:e.x,ty:e.y};return N.fromMatrix(t)}static fromRotate(e,t){let r=Math.sin(e),i=Math.cos(e),s={a:i,b:r,c:-r,d:i};return t&&(s.tx=t.x-t.x*i+t.y*r,s.ty=t.y-t.x*r-t.y*i),N.fromMatrix(s)}static fromScale(e,t){isFinite(e)&&(e={x:e,y:e});let r={a:e.x,d:e.y};return t&&(r.tx=t.x-t.x*e.x,r.ty=t.y-t.y*e.y),N.fromMatrix(r)}static fromPoints(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Expected input type Array requirement not satisfied");if(3!=e.length||3!=t.length)throw new Error("Expected input size 3 requirement not satisfied");let r=N.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}),i=N.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=r.invert().preMultiply(i);return N.fromMatrix({a:s.m11,b:s.m12,c:s.m21,d:s.m22,tx:s.m31,ty:s.m32})}static multiply(e,t){let i=r.mat4.create();return r.mat4.multiply(i,e.value,t.value),new N(i)}}N.MultiplicationType=Object.freeze({PRE:"PRE",POST:"POST"});let M={longToByteArray(e){let t=[0,0,0,0,0,0,0,0];for(let r=0;r<t.length;r++){let i=255&e;t[r]=i,e=(e-i)/256}return t},byteArrayToLong(e){let t=0;for(let r=e.length-1;r>=0;r--)t=256*t+e[r];return t},crc32:function(){let e=new Uint32Array(256);for(let t=256;t--;){let r=t;for(let e=8;e--;)r=1&r?3988292384^r>>>1:r>>>1;e[t]=r}return function(t){let r=-1;for(let i=0,s=t.length;i<s;i++)r=r>>>8^e[255&r^t[i]];return(-1^r)>>>0}}(),encodeBitMask(e=[]){if(0==e.length)return 0;let t="",r=Math.max(...e);for(let i=1;i<=r;i++)t+=e.includes(i)?"1":"0";return parseInt(t.split("").reverse().join(""),2)},decodeBitMask(e){let t=[],r=e.toString(2).split("").reverse();for(let e=0;e<r.length;e++)1==r[e]&&t.push(e+1);return t},mapTo:(e,t,r)=>r.min+(M.clamp(e,t)-t.min)/(t.max-t.min)*(r.max-r.min),clamp:(e,t)=>Math.min(Math.max(e,t.min),t.max),debounce(e,t){let r=null;return function(){let i=this,s=arguments;clearTimeout(r),r=setTimeout((function(){e.apply(i,s)}),t)}},comparator(){let e=Array.prototype.slice.call(arguments),t=function(e,t,r){return t.replace("[",".").replace("]","").split(".").forEach((t=>e=e[t])),r?e.toLowerCase():e};return function(r,i){return e.map((e=>function(e,t,r){let i="asc"===r?1:-1;return e>t?1*i:e<t?-1*i:0}(t(r,e.sortBy,e.ignoreCase),t(i,e.sortBy,e.ignoreCase),e.sortOrder))).reduceRight((function(e,t){return t||e}))}},isValidURL(e){if("string"!=typeof e)return!1;try{return new URL(e),!0}catch(e){return!1}},getPropName(e,t){let r=e.split("_"),i=r.first.toLowerCase();t&&(i=i.substring(0,1).toUpperCase()+i.substring(1));for(let e=1;e<r.length;e++)i+=r[e].substring(0,1),i+=r[e].substring(1).toLowerCase();return i},getEnumValueName(e){let t="";for(let r=0;r<e.length;r++)r>0&&e[r]!=e[r].toLowerCase()&&(t+="_"),t+=e[r];return t.toUpperCase()}};class L{constructor(e){this.header=[],this.table=[],e.forEach((e=>{"string"==typeof e&&(e={name:e,title:e}),e.size=e.title.length,this.header.push(e)})),Object.defineProperty(this,"length",{get:()=>this.table.length,enumerable:!0})}insert(e){this.table.push(e),this.header.forEach((t=>{let r=e[t.name];null!=r&&(t.size=Math.max(t.size,r.toString().length))}))}build(){let e=[],t=this.header.length+1,r=[];return this.header.forEach((e=>{t+=e.size+2;let i=e.size-e.title.length,s=Math.floor(i/2),n=Math.ceil(i/2);r.push(this.getRepetedValue(s)+e.title+this.getRepetedValue(n))})),this.table.forEach((t=>{let r=[];this.header.forEach((e=>{let i=null==t[e.name]?"":t[e.name],s=e.size-i.toString().length;r.push(i+this.getRepetedValue(s))})),e.push(r)})),{delimiterLength:t,headerRow:r,content:e}}getFormattedRow(e){let t="| ";return e.forEach((e=>{t+=e,t+=" | "})),t.trim()}getRepetedValue(e,t=" "){return new Array(e+1).join(t)}clear(){this.table.clear()}toString(){let e="",{delimiterLength:t,headerRow:r,content:i}=this.build();return e+=this.getRepetedValue(t,"="),e+="\n",e+=this.getFormattedRow(r),e+="\n",e+=this.getRepetedValue(t,"="),e+="\n",i.forEach((t=>{e+=this.getFormattedRow(t),e+="\n"})),e}}if("object"==typeof window&&"undefined"==typeof TouchEvent){class e extends Event{}window.TouchEvent=e}let _={pointers:{mouse:["down","move","up"],touch:["start","move","end"]},inactive:[],open(e){if(!(e instanceof y))throw new Error("Argument doesn't implement InkController interface");this.inkController=e,this.canvas=e.canvas.surface,this.mounted||(this.mounted=!0,this.begin=this.begin.bind(this),this.move=this.move.bind(this),this.end=this.end.bind(this),this.abort=this.abort.bind(this)),addEventListener("touchcancel",this.abort,{passive:!0}),this.attachResize(),this.start()},reset(e){for(let t in this.pointers){let r=t==_.PointerType.TOUCH?{passive:!0}:void 0,i=t+this.pointers[t][0];this.canvas.removeEventListener(i,this.begin),e.canvas.surface.addEventListener(i,this.begin,r)}this.dettachResize(),this.inkController=e,this.canvas=e.canvas.surface,this.attachResize()},close(){this.stop(),this.dettachResize(),removeEventListener("touchcancel",this.abort),delete this.canvas,delete this.inkController},start(e){let t=e?{[e]:this.pointers[e]}:this.pointers;for(e in e&&this.inactive.remove(e),this.inactive.forEach((e=>delete t[e])),t){let r=e==_.PointerType.TOUCH?{passive:!0}:void 0;for(let i=0;i<t[e].length;i++){let s=e+t[e][i];0==i?this.canvas.addEventListener(s,this.begin,r):addEventListener(s,2==i?this.end:this.move,r)}}},stop(e){let t=e?{[e]:this.pointers[e]}:this.pointers;for(e in e&&!this.inactive.includes(e)&&this.inactive.push(e),this.inactive.forEach((e=>delete t[e])),e&&e!=_.PointerType.MOUSE||clearTimeout(this.timeoutID),t)for(let r=0;r<t[e].length;r++){let i=e+t[e][r];0==r?this.canvas.removeEventListener(i,this.begin):removeEventListener(i,2==r?this.end:this.move)}},isInputAllowed(e){let t=this.provider;if(e.type.endsWith("down")||e.type.endsWith("start")){if(t||(t=this.getInputProvider(e)),this.inactive.includes(t))return!1;if(t==_.PointerType.MOUSE&&0!=e.button)return!1;for(let t in this.suppressKeys)if(e[t])return!1}return t==this.getInputProvider(e)},isInputExpected(e){let t=!1,r=e.changedTouches?Array.from(e.changedTouches).map((e=>e.identifier)):[],i=this.inkController.getInkBuilder(r);return i&&(t=e.type.endsWith("down")||e.type.endsWith("start")?!i.phase:i.phase&&i.phase!=S.Phase.END),t},getSensorPoint(e){let t,r=e.changedTouches?Array.from(e.changedTouches).map((e=>e.identifier)):[],i=this.inkController.getInkBuilder(r);return i&&(t=this.createSensorPoint(e,i.pointerID)),t},createSensorPoint(e,t){let r=this.getOffset(e),i={x:r.x,y:r.y,z:void 0,timestamp:Math.floor(e.timeStamp),pressure:void 0,radiusX:void 0,radiusY:void 0,rotation:void 0},s={id:void 0,type:void 0,button:void 0,buttons:void 0};if(Object.defineProperty(i,"phase",{value:S.Phase[e.type.replace(/pointer|mouse|touch/g,"").replace(/down|start/,"BEGIN").replace(/move/,"UPDATE").replace(/up|end/,"END")],enumerable:!0}),Object.defineProperty(i,"pointer",{value:s,enumerable:!0}),Object.defineProperty(i.pointer,"provider",{get:function(){return I.Type[this.type.toUpperCase()]},enumerable:!0}),e instanceof MouseEvent)s.type=_.PointerType.MOUSE,s.button=e.button,s.buttons=e.buttons;else{if(!(e instanceof TouchEvent))throw new Error(`Unexpected event detected: ${e.constructor.name}. Expected event should be instance of MouseEvent or TouchEvent.`);if(isNaN(t))throw new Error("pointerID is required for touch event");if(!(e=Array.from(e.changedTouches).filter((e=>e.identifier==t)).first))return null;isNaN(i.x)&&(i.x=e.offsetX||e.clientX),isNaN(i.y)&&(i.y=e.offsetY||e.clientY),s.id=e.identifier,s.type=_.PointerType.TOUCH,i.pressure=e.force,i.radiusX=e.radiusX,i.radiusY=e.radiusY,i.rotation=Math.toRadians(e.rotationAngle)}return i},getOffset(e){if(e.changedTouches){let t=Array.from(e.changedTouches).map((e=>e.identifier)),r=this.inkController.getInkBuilder(t);e=r.pointerID!=e.changedTouches.item(0).identifier?Array.from(e.changedTouches).filter((e=>e.identifier==r.pointerID)).first:e.changedTouches.item(0)}let t=this.canvas.offsetParent;if(!t)return{x:0,y:0};"flex"==t.getStyle("display")&&(t=this.canvas);let r=this.inkController.transform,i=this.canvas.getStyle("transform");"none"==i?i=t.getStyle("transform"):t=this.canvas,i="none"==i?null:N.fromMatrix(i);let s=w.fromPoint({x:e.clientX,y:e.clientY}),n=t.getBoundingClientRect();if(i){let e=i.invert();s=s.transform(e),n=v.fromRect(n).transform(e)}let o={x:s.x-n.x,y:s.y-n.y};return r&&(o=w.fromPoint(o).transform(r.invert())),o},getInputProvider:e=>e.type.replace(/down|start|move|up|end/g,""),begin(e){if(this.logSampleInput(e),e instanceof MouseEvent&&0!=e.button)return;if(!this.isInputAllowed(e))return;if(e instanceof TouchEvent){let t=Array.from(e.changedTouches).map((e=>e.identifier));this.inkController.registerInputProvider(t)}if(!this.isInputExpected(e))return;this.provider||(this.provider=this.getInputProvider(e));let t=this.getSensorPoint(e);t&&this.inkController.begin(t,e)},move(e){if(!this.isInputAllowed(e)||!this.isInputExpected(e))return;this.logSampleInput(e);let t=this.getSensorPoint(e);t&&this.inkController.move(t,void 0,e)},end(e){if(!this.isInputAllowed(e)||!this.isInputExpected(e))return;this.logSampleInput(e);let t=this.getSensorPoint(e);t&&(this.inkController.end(t,e),e instanceof MouseEvent||this.inactive.includes(_.PointerType.MOUSE)||(this.stop(_.PointerType.MOUSE),this.timeoutID=setTimeout((()=>this.start(_.PointerType.MOUSE)),500))),e.touches&&0!=e.touches.length||delete this.provider},abort(e){if(delete this.provider,this.inkController.abort)if(e instanceof TouchEvent){let t=Array.from(e.changedTouches).map((e=>e.identifier));this.inkController.abort(t)}else this.inkController.abort()},logSampleInput(e){if(!this.debug)return;const t=e.type.endsWith("move"),r="mouseup"==e.type||"touchend"==e.type;t&&!this.debug.move||r&&!this.debug.end||(r&&this.table.length>0&&(console.log(this.table.toString()),this.table.clear()),this.table||(this.table=new L(["type","id","pointerType","x","y","pressure","radius","rotation","timestamp"])),this.table.insert({type:e.type,id:e.changedTouches?e.changedTouches[0].identifier:void 0,pointerType:this.getInputProvider(e),x:e.changedTouches?e.changedTouches[0].clientX.toFixed(2):e.clientX,y:e.changedTouches?e.changedTouches[0].clientY.toFixed(2):e.clientY,pressure:e.changedTouches?e.changedTouches[0].force.toFixed(2):void 0,radius:e.changedTouches?e.changedTouches[0].radiusX.toFixed(2)+" / "+e.changedTouches[0].radiusY.toFixed(2):void 0,rotation:e.changedTouches?e.changedTouches[0].rotationAngle:e.twist,timestamp:e.timeStamp.toFixed(8)}),t||(console.log(this.table.toString()),this.table.clear()))},PointerType:{MOUSE:"mouse",TOUCH:"touch"}},F={inactive:[],suppressKeys:{ctrlKey:!0,altKey:!0,shiftKey:!0,metaKey:!0},open(e){if(!(e instanceof y))throw new Error("Argument doesn't implement InkController interface");this.inkController=e,this.canvas=e.canvas.surface,this.mounted||(this.mounted=!0,this.begin=this.begin.bind(this),this.move=this.move.bind(this),this.end=this.end.bind(this),this.abort=this.abort.bind(this)),addEventListener("pointercancel",this.abort),this.attachResize(),this.start()},reset(e){this.canvas.removeEventListener("pointerdown",this.begin),e.canvas.surface.addEventListener("pointerdown",this.begin),this.dettachResize(),this.inkController=e,this.canvas=e.canvas.surface,this.attachResize()},close(){this.stop(),this.dettachResize(),removeEventListener("pointercancel",this.abort),delete this.canvas,delete this.inkController},start(e){e?this.inactive.remove(e):(this.canvas.addEventListener("pointerdown",this.begin),addEventListener("pointermove",this.move),addEventListener("pointerup",this.end))},stop(e){e?this.inactive.includes(e)||this.inactive.push(e):(this.canvas.removeEventListener("pointerdown",this.begin),removeEventListener("pointermove",this.move),removeEventListener("pointerup",this.end))},attachResize(){if(this.inkController.resize==y.prototype.resize)return;let e=F.ResizeReason.WINDOW,t=devicePixelRatio,r=screen.width;let i;matchMedia("screen and (orientation: portrait)").addListener((t=>{e=F.ResizeReason.ORIENTATION,r=screen.width})),function r(){i&&(i.removeListener(r),e=t<devicePixelRatio?F.ResizeReason.ZOOM_IN:F.ResizeReason.ZOOM_OUT,t=devicePixelRatio),i=matchMedia(`(resolution: ${devicePixelRatio}dppx)`),i.addListener(r)}(),this.resize=M.debounce((()=>{e==F.ResizeReason.WINDOW&&r!=screen.width&&(e=r<screen.width?F.ResizeReason.SCREEN_SIZE_INCREASED:F.ResizeReason.SCREEN_SIZE_DECREASED,r=screen.width),this.inkController.resize(e),e=F.ResizeReason.WINDOW}),200),addEventListener("resize",this.resize)},dettachResize(){this.inkController.resize!=y.prototype.resize&&removeEventListener("resize",this.resize)},isInputAllowed(e){if("pointerdown"!=e.type)return!0;let t=this.provider;if(t||(t=this.getInputProvider(e)),this.inactive.includes(t))return!1;if(t==F.PointerType.MOUSE){if(0!=e.button)return!1}else if(t==F.PointerType.PEN&&0==e.pressure)return!1;for(let t in this.suppressKeys)if(e[t])return!1;return!0},isInputExpected(e){let t=!1,r=this.inkController.getInkBuilder(e.pointerId);return r&&(t="pointerdown"==e.type?!r.phase:r.phase&&r.phase!=S.Phase.END),t},getSensorPoint(e){let t,r=this.inkController.getInkBuilder(e.pointerId);if(r){if(e.pointerId!=r.pointerID)throw new Error(`Create sensor point failed, expected pointer with id: ${r.pointerID}, found: ${e.pointerId}`);if("pointerdown"==e.type){let t=this.getInputProvider(e);e.pointerType!=t?r.pointerType=t:delete r.pointerType}t=this.createSensorPoint(e,r.pointerType)}return t},createSensorPoint(e,t,r){if(!(e instanceof PointerEvent))throw new Error(`Unexpected event detected: ${e.constructor.name}. Expected event should be instance of PointerEvent.`);let i,s=this.getOffset(e),n={x:s.x,y:s.y,z:void 0,timestamp:Math.round(e.timeStamp),pressure:void 0,radiusX:void 0,radiusY:void 0,tiltX:void 0,tiltY:void 0,rotation:void 0};if(r?(Object.defineProperty(n,"phase",{value:r.phase,enumerable:!0}),i=r.pointer):(Object.defineProperty(n,"phase",{value:S.Phase[e.type.replace(/pointer|mouse|touch/g,"").replace(/down|start/,"BEGIN").replace(/move/,"UPDATE").replace(/up|end/,"END")],enumerable:!0}),i={id:e.pointerId,type:t||e.pointerType,button:void 0,buttons:void 0},Object.defineProperty(i,"provider",{get:function(){return I.Type[this.type.toUpperCase()]},enumerable:!0}),"pen"!=i.type&&"mouse"!=i.type||(i.button=e.button,i.buttons=e.buttons)),Object.defineProperty(n,"pointer",{value:i,enumerable:!0}),"pen"!=i.type&&"touch"!=i.type||(n.pressure=e.pressure,n.rotation=Math.toRadians(e.twist)),"pen"==i.type?(n.tiltX=e.tiltX,n.tiltY=e.tiltY):"touch"==i.type&&(n.radiusX=e.width/2,n.radiusY=e.height/2),!r){if(e.getPredictedEvents){let r=e.getPredictedEvents();if(r.length>0){let e;Object.defineProperty(n,"predicted",{get:()=>(e||(e=r.map((e=>this.createSensorPoint(e,t,n)))),e),enumerable:!0})}}if("pen"==i.type&&e.getCoalescedEvents){let r=e.getCoalescedEvents();if(r.length>1){let e;Object.defineProperty(n,"coalesced",{get:()=>(e||(e=r.map((e=>this.createSensorPoint(e,t,n)))),e),enumerable:!0})}}}return n},getOffset(e){let t=this.canvas.offsetParent;if(!t)return{x:0,y:0};"flex"==t.getStyle("display")&&(t=this.canvas);let r=this.inkController.transform,i=this.canvas.getStyle("transform");"none"==i?i=t.getStyle("transform"):t=this.canvas,i="none"==i?null:N.fromMatrix(i);let s=w.fromPoint({x:e.clientX,y:e.clientY}),n=t.getBoundingClientRect();if(i){let e=i.invert();s=s.transform(e),n=v.fromRect(n).transform(e)}let o={x:s.x-n.x,y:s.y-n.y};return r&&(o=w.fromPoint(o).transform(r.invert())),o},getInputProvider:e=>e.pointerType==F.PointerType.MOUSE&&e.pressure>0&&.5!==e.pressure?F.PointerType.PEN:e.pointerType,begin(e){if(this.logSampleInput(e),!this.isInputAllowed(e))return;if(this.inkController.registerInputProvider(e.pointerId,e.isPrimary),!this.isInputExpected(e))return;this.provider||(this.provider=this.getInputProvider(e));let t=this.getSensorPoint(e);t&&this.inkController.begin(t,e)},move(e){if(!this.isInputAllowed(e)||!this.isInputExpected(e))return;this.logSampleInput(e);let t=this.getSensorPoint(e);if(t){let r;if(this.inkController.getInkBuilder(e.pointerId).prediction&&e.getPredictedEvents){let i=e.getPredictedEvents();i.length>0&&(r=this.createSensorPoint(i.last,t.pointer.type,t))}this.inkController.move(t,r,e)}},end(e){if(!this.isInputAllowed(e)||!this.isInputExpected(e))return;this.logSampleInput(e);let t=this.getSensorPoint(e);t&&this.inkController.end(t,e),delete this.provider},abort(e){delete this.provider,this.inkController.abort(e.pointerId)},logSampleInput(e){this.debug&&(this.debug.move||this.debug.end)&&("pointermove"!=e.type||this.debug.move)&&("pointerup"!=e.type||this.debug.end)&&(e.pointerType!=this.getInputProvider(e)&&(e.pen=!0),"pointerup"==e.type&&this.table.length>0&&(console.log(this.table.toString()),this.table.clear()),this.table||(this.table=new L(["type","id","pointerType","x","y","pressure","radius","tilt","rotation","buttons","timestamp"])),this.table.insert({type:e.type,id:e.pointerId,pointerType:e.pen?`${e.pointerType} / pen`:e.pointerType,x:e.clientX.toFixed(2),y:e.clientY.toFixed(2),pressure:e.pressure.toFixed(8),radius:(e.width/2).toFixed(2)+" / "+(e.height/2).toFixed(2),rotation:e.twist,tilt:isFinite(e.tiltX)?e.tiltX+" / "+e.tiltY:"",buttons:e.buttons,timestamp:e.timeStamp.toFixed(8)}),"pointermove"!=e.type&&(console.log(this.table.toString()),this.table.clear()))},PointerType:{PEN:"pen",MOUSE:"mouse",TOUCH:"touch"}};Object.defineEnum(F,"ResizeReason",["WINDOW","ZOOM_IN","ZOOM_OUT","SCREEN_SIZE_INCREASED","SCREEN_SIZE_DECREASED","ORIENTATION"]),"object"==typeof window&&"undefined"==typeof PointerEvent&&(_.suppressKeys=F.suppressKeys,_.ResizeReason=F.ResizeReason,_.attachResize=F.attachResize,_.dettachResize=F.dettachResize,F=_);var B=F;class U extends w{static defaults={size:1,rotation:0,scaleX:1,scaleY:1,scaleZ:1,offsetX:0,offsetY:0,offsetZ:0};constructor(e,t,r,i={}){super(e,t,r),this.red=i.red,this.green=i.green,this.blue=i.blue,this.alpha=i.alpha,this.size=i.size||U.defaults.size,this.rotation=i.rotation||U.defaults.rotation,this.scaleX=i.scaleX||U.defaults.scaleX,this.scaleY=i.scaleY||U.defaults.scaleY,this.scaleZ=isFinite(r)?i.scaleZ||U.defaults.scaleZ:void 0,this.offsetX=i.offsetX||U.defaults.offsetX,this.offsetY=i.offsetY||U.defaults.offsetY,this.offsetZ=isFinite(r)?i.offsetZ||U.defaults.offsetZ:void 0,this.dX,this.dY}static createInstance(e,t,r,i=0){let s=new U(0,0,e.includes(U.Property.Z)?0:void 0);return r&&s.fill(i,r,e,t),s}fill(e,t,r,i={}){let s={},n=e*r.length;r.forEach(((e,r)=>U.setProperty(s,e,t[n+r]))),this.x=s.x,this.y=s.y,this.z=s.z,this.red=isFinite(s.red)?s.red:i.red,this.green=isFinite(s.green)?s.green:i.green,this.blue=isFinite(s.blue)?s.blue:i.blue,this.alpha=isFinite(s.alpha)?s.alpha:i.alpha,this.size=s.size||i.size||U.defaults.size,this.rotation=s.rotation||i.rotation||U.defaults.rotation,this.scaleX=s.scaleX||i.scaleX||U.defaults.scaleX,this.scaleY=s.scaleY||i.scaleY||U.defaults.scaleY,this.scaleZ=isFinite(s.z)?s.scaleZ||i.scaleZ||U.defaults.scaleZ:void 0,this.offsetX=s.offsetX||i.offsetX||U.defaults.offsetX,this.offsetY=s.offsetY||i.offsetY||U.defaults.offsetY,this.offsetZ=isFinite(s.z)?s.offsetZ||i.offsetZ||U.defaults.offsetZ:void 0,this.dX=s.dX,this.dY=s.dY}getProperty(e){switch(e){case U.Property.X:return this.x;case U.Property.Y:return this.y;case U.Property.Z:return this.z;case U.Property.RED:return this.red;case U.Property.GREEN:return this.green;case U.Property.BLUE:return this.blue;case U.Property.ALPHA:return this.alpha;case U.Property.SIZE:return this.size;case U.Property.ROTATION:return this.rotation;case U.Property.SCALE_X:return this.scaleX;case U.Property.SCALE_Y:return this.scaleY;case U.Property.SCALE_Z:return this.scaleZ;case U.Property.OFFSET_X:return this.offsetX;case U.Property.OFFSET_Y:return this.offsetY;case U.Property.OFFSET_Z:return this.offsetZ;case U.Property.D_X:return this.dX;case U.Property.D_Y:return this.dY;default:throw console.warn(e),new Error("Invalid property found")}}setProperty(e,t){U.setProperty(this,e,t)}static setProperty(e,t,r){switch(t){case U.Property.X:e.x=r;break;case U.Property.Y:e.y=r;break;case U.Property.Z:e.z=r;break;case U.Property.RED:e.red=r;break;case U.Property.GREEN:e.green=r;break;case U.Property.BLUE:e.blue=r;break;case U.Property.ALPHA:e.alpha=r;break;case U.Property.SIZE:e.size=r;break;case U.Property.ROTATION:e.rotation=r;break;case U.Property.SCALE_X:e.scaleX=r;break;case U.Property.SCALE_Y:e.scaleY=r;break;case U.Property.SCALE_Z:e.scaleZ=r;break;case U.Property.OFFSET_X:e.offsetX=r;break;case U.Property.OFFSET_Y:e.offsetY=r;break;case U.Property.OFFSET_Z:e.offsetZ=r;break;case U.Property.D_X:e.dX=r;break;case U.Property.D_Y:e.dY=r;break;default:throw console.warn(t),new Error("Invalid property found")}}transform(e){if(!(e instanceof N))throw new Error(`matrix is instance of ${e.constructor.name} - it should be instance of Matrix. Use Matrix.fromMatrix method to convert.`);let t=e.scaleX,r=e.rotation;this.transformSelf(e),this.size*=t,this.rotation+=r}toArray(e){return e.map((e=>{let t=this.getProperty(e);if(null==t||isNaN(t))throw new Error(`Property ${e.name} has invalid value ${t}`);return t}))}toJSON(){let e={};return U.Property.values.forEach((t=>{let r=this.getProperty(t);null!=r&&isFinite(r)&&(e[t.name]=this.getProperty(t))})),e}}Object.defineEnum(U,"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"]),Object.defineProperty(globalThis,"DIGITAL_INK_ENV",{value:"AUTO",enumerable:!0,configurable:!0});let j,G={version:"1.5.0"};Object.defineEnum(G,"Type",["WEB","WORKER","NODE","SHELL"]),Object.defineEnum(G,"Type2D",["SCREEN","OFFSCREEN"]),Object.defineEnum(G,"TypeGL",["WEB","STACK"]),function(e){let t,r="BROWSER"!=DIGITAL_INK_ENV&&"object"==typeof process&&"function"==typeof require;t="object"==typeof window?"WEB":"function"==typeof importScripts?"WORKER":r?"NODE":"SHELL";let i="undefined"==typeof Screen?"OFFSCREEN":"SCREEN",s="undefined"==typeof WebGLRenderingContext?"STACK":"WEB";Object.defineProperty(G,"commonJS",{value:r,enumerable:!0}),Object.defineProperty(G,"type",{value:G.Type[t],enumerable:!0}),Object.defineProperty(G,"type2D",{value:G.Type2D[i],enumerable:!0}),Object.defineProperty(G,"typeGL",{value:G.TypeGL[s],enumerable:!0})}(),G.commonJS&&(j=require("systeminformation"));var $=j;class Y extends P{constructor(){super(),this.props={}}getMD5Message(){if(!Object.isFrozen(this))throw new Error("ID generation failed. Environment do not belongs to any InputContext yet");return["Environment",P.buildMD5Tokens(this.props)]}static async createInstance(e={}){let t=new Y;if(t.props["wacom.ink.sdk.lang"]="js",t.props["wacom.ink.sdk.version"]=G.version,t.props["runtime.type"]=G.type.name,void 0===$)t.props["user.agent"]=navigator.userAgent;else{let e=await $.osInfo();t.props["os.id"]=e.serial.toLowerCase(),t.props["os.name"]=e.codename,t.props["os.version"]=e.release,t.props["os.build"]=e.build,t.props["os.platform"]=`${e.distro} (${e.platform} ${e.arch})`}return Object.keys(e).forEach((r=>t.props[r]=e[r])),t}}const X={DP:160,PICA:6,POINT:72,DIP:96,DPI:96*("undefined"==typeof window?1:window.devicePixelRatio)};class z{static Units={METER:{METER:1,CENTIMETER:100,MILLIMETER:1e3,MICROMETER:1e6,INCH:39.3700787402},CENTIMETER:{METER:.01,CENTIMETER:1,MILLIMETER:10,MICROMETER:1e4,INCH:.3937007874},MILLIMETER:{METER:.001,CENTIMETER:.1,MILLIMETER:1,MICROMETER:1e3,INCH:.0393700787},MICROMETER:{METER:1e-6,CENTIMETER:1e-4,MILLIMETER:.001,MICROMETER:1,INCH:393701e-10},INCH:{METER:.0254,CENTIMETER:2.54,MILLIMETER:25.4,MICROMETER:25400,INCH:1},SECOND:{SECOND:1,MILLISECOND:1e3,MICROSECOND:1e6,NANOSECOND:1e9},MILLISECOND:{SECOND:.001,MILLISECOND:1,MICROSECOND:1e3,NANOSECOND:1e6},MICROSECOND:{SECOND:1e-6,MILLISECOND:.001,MICROSECOND:1,NANOSECOND:1e3},NANOSECOND:{SECOND:1e-9,MILLISECOND:1e-6,MICROSECOND:.001,NANOSECOND:1},RADIAN:{RADIAN:1,DEGREE:57.2957795},DEGREE:{RADIAN:.0174532925,DEGREE:1},NEWTON:{NEWTON:1}};static getChannelResolution(e,t=1){let r=1,i=z.getUnitMetric(e);return i!=z.Metric.NORMALIZED&&i!=z.Metric.LOGICAL&&(r=z[V[i.name].name][e.name]/t),r}static convert(e,t,r,i){return t?r*z[V[e.name].name][i.name]/t:r}static convertAny(e,t,r,i){return e*z[t.name][r.name]/i}static getUnitMetric(e){switch(e){case z.Unit.METER:case z.Unit.CENTIMETER:case z.Unit.MILLIMETER:case z.Unit.MICROMETER:case z.Unit.INCH:case z.Unit.DP:case z.Unit.PICA:case z.Unit.POINT:case z.Unit.DIP:case z.Unit.DPI:return z.Metric.LENGTH;case z.Unit.SECOND:case z.Unit.MILLISECOND:case z.Unit.MICROSECOND:case z.Unit.NANOSECOND:return z.Metric.TIME;case z.Unit.RADIAN:case z.Unit.DEGREE:return z.Metric.ANGLE;case z.Unit.NEWTON:return z.Metric.FORCE;case z.Unit.NORMALIZED:return z.Metric.NORMALIZED;case z.Unit.LOGICAL:return z.Metric.LOGICAL;default:throw console.warn(e),new Error("Invalid unit found")}}static getMetricUnits(e){switch(e){case z.Metric.LENGTH:return[z.Unit.METER,z.Unit.CENTIMETER,z.Unit.MILLIMETER,z.Unit.MICROMETER,z.Unit.INCH,z.Unit.DP,z.Unit.PICA,z.Unit.POINT,z.Unit.DIP,z.Unit.DPI];case z.Metric.TIME:return[z.Unit.SECOND,z.Unit.MILLISECOND,z.Unit.MICROSECOND,z.Unit.NANOSECOND];case z.Metric.ANGLE:return[z.Unit.RADIAN,z.Unit.DEGREE];case z.Metric.FORCE:return[z.Unit.NEWTON];case z.Metric.NORMALIZED:return[z.Unit.NORMALIZED];case z.Metric.LOGICAL:return[z.Unit.LOGICAL];case z.Metric.DIMENSIONLESS:return[];default:throw console.warn(e),new Error("Invalid metric found")}}static getUnit(e){return V[e.name]}static convertValue(e,t,r){return e*z[t.name][r.name]}}Object.defineEnum(z,"Unit",["METER","CENTIMETER","MILLIMETER","MICROMETER","INCH","DP","PICA","POINT","DIP","DPI","SECOND","MILLISECOND","MICROSECOND","NANOSECOND","RADIAN","DEGREE","NEWTON","NORMALIZED","LOGICAL"]),Object.defineEnum(z,"Metric",["LENGTH","TIME","FORCE","ANGLE","NORMALIZED","LOGICAL","DIMENSIONLESS"]);const V=Object.freeze({LENGTH:z.Unit.METER,TIME:z.Unit.SECOND,FORCE:z.Unit.NEWTON,ANGLE:z.Unit.RADIAN,NORMALIZED:z.Unit.NORMALIZED,LOGICAL:z.Unit.LOGICAL});!function(){let e=z.getMetricUnits(z.Metric.LENGTH).filter((e=>!(e.name in X)));for(let t of e){let e=z.Units[t.name];for(let t in X)e[t]=e.INCH*X[t]}for(let t in X){let r={};for(let i of e)r[i.name]=z.Units.INCH[i.name]/X[t];for(let e in X)r[e]=X[e]/X[t];z.Units[t]=r}for(let e in z.Units)z[e]=z.Units[e]}(),Object.freeze(z);class H extends P{constructor(e,t,r,i,s){if(super(),t==H.Metric.DIMENSIONLESS)r=1;else if(isNaN(r)||!t){let n=H.getDefaultUnitDescriptorPerType(e);if(!t){if(!n)throw new Error("metric is required");t=n.metric}if(!r){if(!n)throw new Error("resolution is required");r=z.getChannelResolution(n.unit)}isNaN(i)&&(i=n.min),isNaN(s)&&(s=n.max)}this.type=e,this.metric=t,this.resolution=r,this.min=i,this.max=s,e==H.Type.TIMESTAMP?this.precision=0:this.precision=2,Object.defineProperty(this,"name",{get:function(){return M.getEnumValueName(this.type.substring(this.type.lastIndexOf("/")+1))}})}getMD5Message(){if(!this.context)throw new Error("ID generation failed. This channel do not belongs to SensorChannelsContext yet");if(!Object.isFrozen(this.context)&&!Object.isFrozen(this))throw new Error("ID generation failed. Underlying SensorChannelsContext do not belongs to any SensorContext yet");let e=[];return e.push("SensorChannel"),e.push(this.context.inkProvider?this.context.inkProvider.id:""),e.push(this.context.device.id),e.push(this.type),e.push(this.metric.name),e.push(this.resolution.toFixed(4)),e.push((this.min||0).toFixed(4)),e.push((this.max||0).toFixed(4)),e.push(this.precision.toString()),e}static getTypeName(e){return Object.keys(H.Type).find((t=>H.Type[t]==e))}static getDefaultUnitDescriptorPerType(e){let t={};switch(e){case H.Type.X:case H.Type.Y:case H.Type.Z:case H.Type.RADIUS_X:case H.Type.RADIUS_Y:t.unit=z.Unit.DIP;break;case H.Type.TIMESTAMP:t.unit=z.Unit.MILLISECOND;break;case H.Type.PRESSURE:t.unit=z.Unit.NORMALIZED,t.min=0,t.max=1;break;case H.Type.ALTITUDE:t.unit=z.Unit.RADIAN,t.min=0,t.max=Math.PI/2;break;case H.Type.AZIMUTH:t.unit=z.Unit.RADIAN,t.min=-Math.PI,t.max=Math.PI;break;case H.Type.ROTATION:t.unit=z.Unit.RADIAN,t.min=0,t.max=2*Math.PI;break;default:t=null}return t.metric=z.getUnitMetric(t.unit),t}static createCustomChannel(e,t,r,i,s,n){let o=new H(e,r,i,s,n);return o.precision=t,o}static createDefaultInstance(e,t){let r=H.getDefaultUnitDescriptorPerType(e);r||console.error(`SensorChannel: createDefaultInstance failed with ${e} type`);let i=z.getChannelResolution(r.unit),s=new H(e,r.metric,i,r.min,r.max);return s.unit=r.unit,e!=H.Type.X&&e!=H.Type.Y||t.type!=I.Type.MOUSE||(s.precision=0),s}}H.defaults=Object.freeze({PEN:["X","Y","TIMESTAMP","PRESSURE","ALTITUDE","AZIMUTH","ROTATION"],TOUCH:["X","Y","TIMESTAMP","PRESSURE","RADIUS_X","RADIUS_Y","ROTATION"],MOUSE:["X","Y","TIMESTAMP"]}),H.Type={X:"will://input/3.0/channel/X",Y:"will://input/3.0/channel/Y",Z:"will://input/3.0/channel/Z",TIMESTAMP:"will://input/3.0/channel/Timestamp",PRESSURE:"will://input/3.0/channel/Pressure",RADIUS_X:"will://input/3.0/channel/RadiusX",RADIUS_Y:"will://input/3.0/channel/RadiusY",ALTITUDE:"will://input/3.0/channel/Altitude",AZIMUTH:"will://input/3.0/channel/Azimuth",ROTATION:"will://input/3.0/channel/Rotation"},H.Metric=z.Metric;class Z extends P{constructor(e,t){super(),this.device=e.freeze(),this.inkProvider=Object.freeze(t);let r,i,s=[];Object.defineProperty(this,"channels",{get:function(){return s},set:function(e){this.invalidateID(),s=[],e.forEach((e=>this.add(e)))},enumerable:!0}),Object.defineProperty(this,"layout",{get:function(){return s.map((e=>e.name))},set:function(e){this.invalidateID(),s=s.filter((t=>e.includes(t.name)))},enumerable:!0}),Object.defineProperty(this,"samplingRate",{get:function(){return r},set:function(e){this.invalidateID(),r=e},enumerable:!0}),Object.defineProperty(this,"latency",{get:function(){return i},set:function(e){this.invalidateID(),i=e},enumerable:!0})}getMD5Message(){if(!Object.isFrozen(this))throw new Error("ID generation failed. SensorChannelsContext do not belongs to any SensorContext yet");let e=["SensorChannelsContext",...this.channels.map((e=>e.id))];return e.push(this.samplingRate||""),e.push(this.latency||""),e.push(this.inkProvider?this.inkProvider.id:""),e.push(this.device.id),e}add(e){if((e.type==H.Type.X||e.type==H.Type.Y)&&!this.inkProvider)throw new Error("inkProvider is not found. Required for ink group.");e.context=this,Object.freeze(e),this.channels.push(e)}get(e){return this.channels.filter((t=>t.id==e)).first}static createDefaultInstance(e,t){let r=new Z(e,t);return r.channels=H.defaults[t.type.name].map((e=>H.createDefaultInstance(H.Type[e],t))),r}}class q extends P{constructor(){super();let e=[];Object.defineProperty(this,"channelsContexts",{get:function(){return e},set:function(t){this.invalidateID(),e=t},enumerable:!0})}getMD5Message(){if(!Object.isFrozen(this))throw new Error("ID generation failed. SensorContext do not belongs to any InputContext yet");return["SensorContext",...this.channelsContexts.map((e=>e.id))]}addContext(e){if(!this.channelsContexts.includes(e)){if(this.channelsContexts.some((t=>t.device==e.device)))throw new Error(`Already exists channelsContext with device ${e.device.id}. Device should be unique in the scope of SensorContext.`);e.inkProvider&&(this.inkChannelsContext=e),Object.freeze(e),this.channelsContexts.push(e)}}getContext(e){return this.channelsContexts.find((t=>t.id==e))}getContextByChannelID(e){return this.channelsContexts.find((t=>t.get(e)))}static createDefaultInstance(e,t){let r=new q;return r.addContext(Z.createDefaultInstance(e,t)),r}}class W extends P{constructor(e,t){super(),this.environment=Object.freeze(e),this.sensorContext=Object.freeze(t)}getMD5Message(){return["InputContext",this.environment.id,this.sensorContext.id]}addChannelsContext(e){this.sensorContext.addContext(e)}static createDefaultInstance(e,t,r){let i=q.createDefaultInstance(t,r);return new W(e,i)}}class K{static createTreeURI(e,t){return`uim:tree/${t?`${t}/`:""}${e}`}static createStrokeURI(e,t){return`uim:stroke/${t?`${t}/`:""}${e}`}static createSensorDataURI(e,t){return`uim:sensor/${t?`${t}/`:""}${e}`}static createNodeURI(e,t,r){if(!e)throw new Error("inkTree is required");let i="";return r&&(i=`#frag=${r.pointIndexStart},${r.pointIndexEnd}`,0==r.ts&&1==r.tf||(i+=`,${r.ts.toFixed(5)},${r.tf.toFixed(5)}`)),`${K.createNodeURISchema(e)}/${t}${i}`}static createNodeURISchema(e,t=e.name){return`uim:node${e.id?`/${e.id}`:""}/${t}`}static createNamedEntityURI(e,t){return`uim:ne/${t?`${t}/`:""}${e}`}}class J extends P{#t;constructor(e,t){super(t),Object.defineProperty(this,"uri",{get:()=>(this.#t||(this.#t=K.createSensorDataURI(this.id)),this.#t),enumerable:!0}),this.created=Date.now(),this.inkState=J.InkState.PLANE,this.context=e,this.streams=[]}add(e){if(!this.context.sensorContext.getContextByChannelID(e.channels.first.id))throw new Error("SensorContext do not contains information about SensorChannelsContext corresponding with this stream");e.ink&&(this.inkStream=e),this.streams.push(e)}}Object.defineEnum(J,"InkState",["PLANE","HOVERING","IN_VOLUME","VOLUME_HOVERING"]);class Q{constructor(e){this.channels=e,this.data=[],this.ignoredIndex=[],Object.defineProperty(this,"layout",{value:e.map((e=>e.name)),enumerable:!0}),Object.defineProperty(this,"stride",{value:this.layout.length,enumerable:!0}),Object.defineProperty(this,"length",{get:function(){return this.data.length/this.stride},enumerable:!0}),this.ink=this.layout.includes("X")&&this.layout.includes("Y")}add(e,t){t&&this.ignoredIndex.push(this.length),this.channels.forEach((t=>{let r=M.getPropName(t.name),i=e[r];if(t.type==H.Type.ALTITUDE&&!("altitude"in e))throw new Error("SensorStream input data do not provides altitude");if(t.type==H.Type.AZIMUTH&&!("azimuth"in e))throw new Error("SensorStream input data do not provides azimuth");this.data.push(i)}))}get(e){if(e>=this.length||e<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);let t={};for(let r=0;r<this.stride;r++){let i=this.channels[r],s=M.getPropName(i.name),n=e*this.stride;t[s]=this.data[n+r]}return t}getChannelData(e){let t=e==H.Type.TIMESTAMP?new Uint32Array(this.length):new Float32Array(this.length),r=this.channels.findIndex((t=>t.type==e));this.channels[r].name;for(let e=0;e<this.length;e++)t[e]=this.data[e*this.stride+r];return t}getPipelineMapping(){let e=[];if(this.ignoredIndex.length>0)for(let t=0;t<this.length;t++)this.ignoredIndex.includes(t)||e.push(t);return e}}class ee extends P{constructor(){super(),this.props={},this.devices=[]}freeze(){return Object.freeze(this.props),this}getMD5Message(){if(!Object.isFrozen(this.props)&&!Object.isFrozen(this))throw new Error("ID generation failed. InputDevice do not belongs to any SensorChannelsContext yet");return["InputDevice",P.buildMD5Tokens(this.props)]}link(e){if(!(e instanceof ee))throw new Error("Implementation of InputDevice is required");this.devices.push(e)}getInkInputProvider(e){return new I(e)}getInkSensorContext(e){let t=this.getInkInputProvider(e);return q.createDefaultInstance(this,t)}openStream(e){if(!this.environment)throw new Error("Environment is not configured for current InputDevice instance");let t=I.Type[e.pointer.type.toUpperCase()],r=this.getInkSensorContext(t),i=new W(this.environment,r);r.inkChannelsContext.layout=ee.getLayout(e),this.sensorData=new J(i),this.sensorData.add(new Q(r.inkChannelsContext.channels)),this.sampleTimestamp=e.timestamp,this.devices.forEach((e=>e.openStream(this.sensorData)))}add(e,t){if(!this.sensorData)throw new Error("Open ink stream not found");e.timestamp-=this.sampleTimestamp,this.sensorData.inkStream.add(e,t)}closeStream(e){let t=this.sensorData;return this.devices.forEach((t=>t.closeStream(e))),this.sensorData=null,this.sampleTimestamp=0,e?null:t}static getLayout(e){let t=[];return Object.keys(H.Type).forEach((r=>{let i,s=H.Type[r];i=s==H.Type.ALTITUDE?"tiltX":s==H.Type.AZIMUTH?"tiltY":M.getPropName(r),ee.isValidInput(i,e)&&t.push(r)})),t}static isValidInput(e,t){let r=!1;return isFinite(t[e])&&(r=!0,"pressure"==e?(r=t.pressure>0,r&&t.pointer&&("mouse"==t.pointer.type?r=!1:"touch"==t.pointer.type&&(r=.5!==t.pressure&&1!==t.pressure))):"tiltX"==e||"tiltY"==e?r=0!=t.tiltX||0!=t.tiltY:"radiusX"==e||"radiusY"==e?r=t.radiusX!=t.radiusY||parseInt(t.radiusX)!=t.radiusX:"rotation"==e&&(r=0!=t.rotation)),r}static async createInstance(e){let t=new this(...Array.from(arguments).slice(1));if(void 0===$)t.props["dev.graphics.resolution"]=`${screen.width}x${screen.height}`;else{let e=await $.system(),r=await $.cpu(),i=await $.graphics(),s=i.displays.filter((e=>e.main))[0],n=i.controllers[0];t.props["dev.id"]=e.uuid.toLowerCase(),t.props["dev.manufacturer"]=e.manufacturer,t.props["dev.model"]=e.model,t.props["dev.cpu"]=`${r.manufacturer} ${r.brand} ${r.speed} - ${r.cores} core(s)`,t.props["dev.graphics.display"]=`${s.model} ${s.currentResX}x${s.currentResY} (${s.pixeldepth} bit)`,t.props["dev.graphics.adapter"]=`${n.model} ${n.vram} GB`}return t.environment=await Y.createInstance(e),t}}let te={};if(G.type==G.Type.WEB)te.Image=globalThis.Image,te.ImageData=globalThis.ImageData,te.CanvasRenderingContext2D=globalThis.CanvasRenderingContext2D,void 0===globalThis.OffscreenCanvas?(te.OffscreenCanvas=function(e,t){let r=document.createElement("canvas");return r.width=e,r.height=t,r},te.OffscreenCanvasRenderingContext2D=globalThis.CanvasRenderingContext2D):(te.OffscreenCanvas=globalThis.OffscreenCanvas,te.OffscreenCanvasRenderingContext2D=globalThis.OffscreenCanvasRenderingContext2D);else if(void 0!==globalThis.OffscreenCanvas)te.Image=globalThis.Image,te.ImageData=globalThis.ImageData,te.OffscreenCanvas=globalThis.OffscreenCanvas,te.OffscreenCanvasRenderingContext2D=globalThis.OffscreenCanvasRenderingContext2D;else if(G.commonJS){const{Canvas:e,CanvasRenderingContext2D:t,Image:r,ImageData:i}=require("canvas");te.Image=r,te.ImageData=i,te.OffscreenCanvas=e,te.OffscreenCanvasRenderingContext2D=t}else console.warn(`Current env - ${G.type.name}, do not provides OffscreenCanvas support`);function re(e){this.clearRect(0,0,this.canvas.width,this.canvas.height),e&&(this.fillStyle=e,this.fillRect(0,0,this.canvas.width,this.canvas.height))}te.CanvasRenderingContext2D&&(te.CanvasRenderingContext2D.prototype.clearCanvas=re),te.OffscreenCanvasRenderingContext2D&&(te.OffscreenCanvasRenderingContext2D.prototype.clearCanvas=re);const{Image:ie,ImageData:se,OffscreenCanvas:ne,CanvasRenderingContext2D:oe,OffscreenCanvasRenderingContext2D:ae}=te;let le;class he{#r={};constructor(...e){if(le)throw new Error("URIResolver instance already available");le=this,Object.defineProperty(this,"items",{get:()=>Object.values(this.#r),enumerable:!0}),this.init(...e)}init(...e){throw new Error("URIResolver.init(...args) is abstract and should be implemented")}get(e){return this.#r[e]}register(e,t){this.#r[e]=t}resolve(e){let t;if(e.includes("?")){let r=e.split("?")[0],i=this.#r[r];if(i){let r=e.split("?")[1],s=[];r.split("&").forEach((e=>{let t=e.split("=")[1],r=parseFloat(t);isFinite(r)?t=r:"true"==t?t=!0:"false"==t&&(t=!1),s.push(t)})),t=function(){return i(...Array.from(arguments).concat(s))}}}else t=this.#r[e];if(!t)throw new Error(`Failed to resolve ${e}`);return t}}Object.defineProperty(he,"instance",{get:()=>le});class de{static encode(e,t=de.Encoding.AUTO){let r;if(t==de.Encoding.AUTO?t="undefined"==typeof Buffer?"undefined"!=typeof SharedArrayBuffer&&e.buffer instanceof SharedArrayBuffer?de.Encoding.NONE:de.Encoding.ARRAY:de.Encoding.BUFFER:t==de.Encoding.ARRAY&&e instanceof Array&&(t=de.Encoding.NONE),t==de.Encoding.NONE)r=e;else if(t==de.Encoding.ARRAY)r=e.toArray();else{if("undefined"==typeof Buffer)throw new Error("Buffer not found, unable to serialize. Please provide Buffer in global scope.");let i=Buffer.from(e.buffer);switch(t){case de.Encoding.BUFFER:r=i.toJSON();break;case de.Encoding.BASE64:r=i.toString("base64");break;default:throw new Error(`Invalid encoding provided: ${t.name}`)}}return{encoding:t.name,type:e.constructor.name,content:r}}static decode(e){let t,r=de.Encoding[e.encoding];if(r==de.Encoding.NONE)t=e.content;else if(r==de.Encoding.ARRAY)t=e.content.toFloat32Array();else{let i;switch(r){case de.Encoding.BUFFER:i="undefined"==typeof Buffer?e.content.data:Buffer.from(e.content);break;case de.Encoding.BASE64:i="undefined"==typeof Buffer?atob(e.content).toCharArray():Buffer.from(e.content,"base64");break;default:throw new Error(`Invalid encoding provided: ${r.name}`)}let s=new Uint8Array(i);t=new globalThis[e.type](s.buffer)}return t}static isTypedArrayData(e){return e&&e.encoding&&e.type&&e.type.endsWith("Array")}}Object.defineEnum(de,"Encoding",["AUTO","NONE","ARRAY","BUFFER","BASE64"]);class ce{static repetitionsCache=new Set;constructor(e,t){this.name=e,!e||M.isValidURL(e)||ce.repetitionsCache.has(e)||(ce.repetitionsCache.add(e),console.warn(`The string ${e} is not a well formed URI`)),Object.defineProperty(this,"value",{get:function(){if(!t){if(!this.name)throw new Error("Resource descriptor identifier not found. Cannot resolve resource content.");if("function"==typeof this.resolve&&(t=this.resolve(this.name)),!t){if(!he.instance)throw new Error(`Resource URI ${this.name} cannot be resolved. URIResolver not implemented yet. Please implement and instantiate.`);t=he.instance.resolve(this.name)}if(!t)throw new Error(`Resource URI ${this.name} cannot be resolved. Please provide resource definition in URIResolver init implementation.`)}return t},set:function(e){t=e},enumerable:!0})}toJSON(){let e=this.value;return ArrayBuffer.isTypedArray(e)?e=de.encode(e,this.encoding):"function"==typeof e&&(e=e()),{name:this.name,value:e}}static fromJSON(e){let t=e.value;return de.isTypedArrayData(t)&&(t=de.decode(t)),new ce(e.name,t)}static getInstance(e,t){return new ce(t,e)}}class pe{constructor(e){M.isValidURL(e)||(ce.repetitionsCache.has(e)||(ce.repetitionsCache.add(e),console.warn(`Brush URI ${e} is not a well formed URI`)),e=this.constructor.onInvalidName(e)),Object.defineProperty(this,"id",{value:e}),Object.defineProperty(this,"uri",{value:e}),Object.defineProperty(this,"name",{value:e,enumerable:!0})}toJSON(){throw new Error("Brush.toJSON() should be implemented")}static fromJSON(e){throw new Error("static Brush.fromJSON() should be implemented")}static onInvalidName(e){return e}}class ue{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(e=ue.defaults.CIRCLE_PRECISION,t=ue.defaults.CIRCLE_RADIUS,r={x:0,y:0}){return ue.createEllipse(e,t,t,r)}static createEllipse(e=ue.defaults.ELLIPSE_PRECISION,t=ue.defaults.ELLIPSE_RADIUS_X,r=ue.defaults.ELLIPSE_RADIUS_Y,i={x:0,y:0}){let s=[],n=2*Math.PI/e;if(t<=0)throw new Error(`Invalid radius x found ${t} > 0`);if(r<=0)throw new Error(`Invalid radius y found ${r} > 0`);for(let o=0;o<e;o++){let e=o*n,a=t*Math.cos(e),l=r*Math.sin(e);s.push(i.x+a,i.y+l)}return Float32Array.createSharedInstance(s)}static createStar(e=ue.defaults.STAR_POINTS,t=ue.defaults.STAR_INTERNAL_RADIUS,r=ue.defaults.STAR_RADIUS){let i=[];if(r<=0)throw new Error(`Invalid radius found ${r} > 0`);if(t<=0)throw new Error(`Invalid internal radius found ${t} > 0`);if(t>r)throw new Error(`Invalid internal radius found 0 < ${t} < ${r}`);let s=2*Math.PI/e;for(let n=0;n<e;n++){let e=n*s,o=r*Math.cos(e),a=r*Math.sin(e),l=t*Math.cos(e+s/2),h=t*Math.sin(e+s/2);i.push(o,a,l,h)}return Float32Array.createSharedInstance(i)}}let fe=p?p.default||globalThis.poly2tri:{};const{SweepContext:me,Point:ge}=fe;let ye=u?u.default||globalThis.ClipperLib:{};const{Clipper:be,Paths:Ee,Path:Pe,ClipType:Ie,PolyType:Se,PolyFillType:we}=ye;class xe{constructor(e,t,r){Object.defineProperties(this,{path:{value:e,enumerable:!0},pointIndexStart:{value:t,enumerable:!0},pointIndexEnd:{value:r,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 ve{constructor(e,t,r,i=1){if(this.red=e,this.green=t,this.blue=r,this.alpha=i,i<0||i>1)throw new Error(`Invalid alpha ${i} 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(e,t,r,i){let s=parseInt(255*e/i),n=parseInt(255*t/i),o=parseInt(255*r/i);return new ve(s,n,o,i)}equals(e){return e&&this.red==e.red&&this.green==e.green&&this.blue==e.blue&&this.alpha==e.alpha}toRGB(){return 1==this.alpha?this:new ve(this.red,this.green,this.blue)}toRGBA(e){return new ve(this.red,this.green,this.blue,e)}toHSLA(){let e=this.red/255,t=this.green/255,r=this.blue/255,i=Math.min(e,t,r),s=Math.max(e,t,r),n=0,o=0,a=(s+i)/2;if(s!=i){let l=s-i;switch(o=l/(1-Math.abs(2*a-1)),s){case e:n=(t-r)/l%6;break;case t:n=(r-e)/l+2;break;case r:n=(e-t)/l+4}}return n*=60,n<0&&(n+=360),{hue:parseFloat(n.toFixed(0)),saturation:parseFloat((100*o).toFixed(2)),lightness:parseFloat((100*a).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(e){return e&&isFinite(e.red)&&isFinite(e.green)&&isFinite(e.blue)}static fromColor(e){let t,r,i,s;if("string"==typeof e)if(e.startsWith("rgb"))e=e.substring(e.indexOf("(")+1,e.indexOf(")")).split(/,\s*/g),t=parseInt(e[0]),r=parseInt(e[1]),i=parseInt(e[2]),s=e[3]?parseInt(e[3]):1;else{if(!e.startsWith("#"))throw new Error(`Unknown input found: ${e}. Expected data starts with rgba, rgb or #.`);e=e.substring(1),t=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16),s=8==e.length?parseInt(e.substring(6,8),16)/255:1}else Array.isArray(e)?(t=e[0],r=e[1],i=e[2],s=e[3]):(t=e.red,r=e.green,i=e.blue,s=e.alpha);return new ve(t,r,i,s)}static fromHSLA(e=0,t=0,r=0,i){e/=60,t/=100,r/=100;let s=(1-Math.abs(2*r-1))*t,n=s*(1-Math.abs(e%2-1)),o=0,a=0,l=0;e>=0&&e<1?(o=s,a=n):e>=1&&e<2?(o=n,a=s):e>=2&&e<3?(a=s,l=n):e>=3&&e<4?(a=n,l=s):e>=4&&e<5?(o=n,l=s):(o=s,l=n);let h=r-s/2;return o+=h,a+=h,l+=h,new ve(Math.round(255*o),Math.round(255*a),Math.round(255*l),i)}static random(e=!1){return new ve(Math.randomInt(0,255),Math.randomInt(0,255),Math.randomInt(0,255),e?Math.random():1)}}ve.TRANSPERENT=new ve(0,0,0,0),ve.BLACK=new ve(0,0,0,1),ve.WHITE=new ve(255,255,255,1),ve.RED=new ve(255,0,0,1),ve.GREEN=new ve(0,255,0,1),ve.BLUE=new ve(0,0,255,1);class Re{constructor(e,t,r={}){this.layout=e,this.pointProps=t,this.sheet={};let i={};Object.defineProperties(i,{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:e=>{e&&(r=e),this.clear(),Object.keys(r).forEach((e=>this.setStyle(e,r[e])))}},clear:{value:this.clear.bind(this)}}),this.style=Object.freeze(i),this.style.reset(r)}setStyle(e,t){if(null==t&&(t=void 0),Re.validate(this.layout,e,t),"color"==e&&t)return this.sheet.red=t.red,this.sheet.green=t.green,this.sheet.blue=t.blue,void(this.sheet.alpha=t.alpha);null==t?delete this.sheet[e]:this.sheet[e]=t}getStyle(e){let t=this.sheet[e];return"visibility"==e?"boolean"!=typeof t&&(t=!0):"color"==e&&ve.isColor(this.sheet)&&(t=ve.fromColor(this.sheet)),t}getComputed(e){let t=this.getStyle(e);if(null==t)if("color"==e){let e={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};ve.isColor(e)&&(t=ve.fromColor(e))}else t=this.pointProps[e];return t}clear(){this.sheet={}}static validate(e,t,r,i){let s;if(r&&e.includes(U.Property[M.getEnumValueName(t)])){if(!i)throw new Error(`Property ${t} value ${r} is not applicable. This is a dynamic property and is part of the layout.`);console.warn(`Property ${t} value ${r} is not applicable. This is a dynamic property and is part of the layout.`),r=void 0}if("color"==t)!r||r instanceof ve||(s=`Property ${t} is not an instance of Color`);else if("blendMode"==t)""==r&&(r=void 0);else if("number"==typeof r)if("size"==t)r<0?s=`Property ${t} with value ${r} is not allowed. Value should be a positive number.`:0==r&&(r=void 0);else if("red"==t||"green"==t||"blue"==t||"alpha"==t){let e="alpha"==t?{min:0,max:1}:{min:0,max:255};r>=e.min&&r<=e.max||(s=`Property ${t} with value ${r} is out of range. Allowd range: [${e.min}, ${e.max}].`)}else"rotation"==t?0==r&&(r=void 0):"scattering"==t&&r<0&&(r=void 0);if(s)throw new Error(s);return r}}const Te=[U.Property.X,U.Property.Y];class Ae{#i;#s;constructor(e,t={},r=Te){if(this.#i=e,Object.defineProperty(this,"points",{get:()=>this.#i,set:e=>{if(this.#i instanceof Float32Array)throw new Error("Points setter is not accessible wehn points type is Float32Array.");this.#i=e,this.validate()},enumerable:!0}),Object.defineProperty(this,"buffer",{get:()=>this.#i.buffer,set:e=>{if(Array.isArray(this.#i))throw new Error("Underlying points buffer is Array. This property is applicable for TypedArray only.");if("undefined"!=typeof SharedArrayBuffer&&this.#i.buffer instanceof SharedArrayBuffer)throw new Error("Underlying buffer is SharedArrayBuffer and cannot be restored");if(this.#i.buffer.byteLength>0)throw new Error("Cannot restore buffer when underlying buffer is not empty");if(e.byteLength/Float32Array.BYTES_PER_ELEMENT/this.stride!=this.length)throw new Error("Value exceeds expected memory length");this.#i=new Float32Array(e)}}),!Object.isSealed(t))for(let e in t)void 0!==t[e]&&(t[e]=Re.validate(r,e,t[e],!0));r.includes(U.Property.ROTATION)||"rotation"in t||(t.rotation=void 0),r.includes(U.Property.SIZE)||t.size||(t.size=1),Object.defineProperties(this,{stride:{value:r.length,enumerable:!0},layout:{value:Object.freeze(r),enumerable:!0},pointProps:{value:Object.seal(t),enumerable:!0}}),e instanceof Float32Array?Object.defineProperty(this,"length",{value:this.#i.length/this.stride,enumerable:!0}):Object.defineProperty(this,"length",{get:()=>this.#i.length/this.stride,enumerable:!0}),r.forEach(((e,t)=>{let r=M.getPropName(e.name,!0);Object.defineProperty(this,`setPoint${r}`,{value:this.setPointPropertyValue.bind(this,t)}),Object.defineProperty(this,`getPoint${r}`,{value:this.getPointPropertyValue.bind(this,t)})}))}validate(){if(this.points.length%this.stride!=0)throw new Error("Path length doesn't match the stride provided via the layout")}setPointPropertyValue(e,t,r){if(isNaN(t))throw new Error("Point index is required");if(t>=this.length||t<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);if(isNaN(r))throw new Error("value is required");this.points[t*this.layout.length+e]=r}getPointPropertyValue(e,t){if(isNaN(t))throw new Error("Point index is required");if(t>=this.length||t<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);return this.points[t*this.layout.length+e]}setPoint(e,t){let r=e*this.stride;this.layout.forEach(((e,i)=>this.points[r+i]=t.getProperty(e)))}getPoint(e,t=this.pointProps){if(e>=this.length||e<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);return U.createInstance(this.layout,t,this.points,e)}getPointRef(e,t=this.pointProps){if(e>=this.length||e<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);return this.#s||(this.#s=U.createInstance(this.layout)),this.#s.fill(e,this.points,this.layout,this.pointProps),this.#s}getChannelData(e){let t=new([U.Property.RED,U.Property.GREEN,U.Property.BLUE].includes(e)?Uint8Array:Float32Array)(this.length),r=this.layout.indexOf(e);if(-1==r)throw new Error(`Property ${e.name} is not part from the spline layout ${this.layout.map((e=>e.name)).join(", ")}`);for(let e=0;e<this.length;e++)t[e]=this.points[e*this.stride+r];return t}transform(e){let t=e.scaleX,i=e.rotation;for(let s=0;s<this.length;s++){let n=s*this.stride,o=r.vec4.fromValues(this.getPointX(s),this.getPointY(s),0,1);r.vec4.transformMat4(o,o,e.value);for(let e=0;e<this.stride;e++){let r=n+e;switch(this.layout[e]){case U.Property.X:this.points[r]=o[0]/o[3];break;case U.Property.Y:this.points[r]=o[1]/o[3];break;case U.Property.Z:this.points[r]=o[2]/o[3];break;case U.Property.ROTATION:this.points[r]+=i;break;case U.Property.SIZE:this.points[r]*=t}}}this.layout.includes(U.Property.ROTATION)||(this.pointProps.rotation=0==i?void 0:i)}clone(){return new Ae(this.#i.clone(),Object.clone(this.pointProps),this.layout.slice())}getFragment(e=0,t=this.length-1){return new xe(this,e,t)}slice(e){let t=this.slicePoints(e.pointIndexStart,e.pointIndexEnd);return new Ae(t,Object.clone(this.pointProps),this.layout.slice())}validateFragment(e,t){if(e<0)throw new Error(`Invalid fragment pointIndexStart ${e} found. The value must be non-negative.`);if(t>this.length-1)throw new Error(`Invalid fragment pointIndexEnd ${t} found. Last point in path index is ${this.length-1}.`)}slicePoints(e,t){let r;if(this.validateFragment(e,t),"undefined"!=typeof SharedArrayBuffer&&this.buffer instanceof SharedArrayBuffer){let i=this.points.subarray(e*this.stride,(t+1)*this.stride),s=new SharedArrayBuffer(i.length*Float32Array.BYTES_PER_ELEMENT);r=new Float32Array(s),r.set(i)}else r=this.points.slice(e*this.stride,(t+1)*this.stride);return r}toSVGPath(){let e=[];for(let t=0;t<this.length;t++)e.push(`${this.getPointX(t)},${this.getPointY(t)}`);return`M ${e.join(" L ")} Z`}toJSON(){return{type:"Path",points:de.encode(this.#i,this.encoding),pointProps:this.pointProps,layout:this.layout.map((e=>e.name))}}static fromJSON(e){if("Path"!=e.type)throw new Error(`Path deserialization failed. JSON type is ${e.type}, expected Path.`);return new Ae(de.decode(e.points),e.pointProps,e.layout.map((e=>U.Property[e])))}static fromRect(e,t){let r=[e.left,e.top,e.right,e.top,e.right,e.bottom,e.left,e.bottom,e.left,e.top];return new Ae(r,t)}static createInstance(e,t,r){return new Ae(e,t,r)}static createSharedInstance(e,t,r){return new Ae(Float32Array.createSharedInstance(e),t,r)}}class Ce{constructor(e,t){if(!Array.isArray(e))throw new Error("Unexpected polygons type found");let r=65534/(t.width+1e-16),i=65534/(t.height+1e-16),s=Math.floor(Math.min(r,i));if(0==s)throw new Error(`Insufficent clipper range - (-32767 - 32767), scale failed - scaleX: ${r}, scaleY: ${i}`);let n=t.left+32767/s,o=t.top+32767/s;this.solution=new Ee,this.bounds=t,this.transform={scale:s,offsetX:n,offsetY:o},this.subject=this.apply(e)}convertPoint(e){let t=(e.x-this.transform.offsetX)*this.transform.scale,r=(e.y-this.transform.offsetY)*this.transform.scale;return{X:t<0?Math.ceil(t):Math.floor(t),Y:r<0?Math.ceil(r):Math.floor(r)}}containsPoint(e){return be.PointInPolygon(this.convertPoint(e),this.solution)}apply(e){let t=new Ee;for(let r of e){let e=new Pe,i=r.shape;for(let t=0;t<i.length;t++)e.push(this.convertPoint({x:i.getPointX(t),y:i.getPointY(t)}));t.push(e)}return t}toPaths(){let e=[];this.lastPoint={};for(let t of this.solution){if(0==t.length)continue;let r=this.flatPath(t);r.length>0&&e.push(r)}return e}flatPath(e){let t=[];for(let r of e)this.lastPoint.X==r.X&&this.lastPoint.Y==r.Y||(t.push(r.X/this.transform.scale+this.transform.offsetX,r.Y/this.transform.scale+this.transform.offsetY),this.lastPoint=r);return t.length<6&&(console.warn(`Invalid contour found: [${t.join(", ")}]`),t.clear()),t}}class Oe{constructor(e=2){this.stride=e}sort(e,t){return this.sortArrayPart(e,0,e.length-this.stride,t),e}partition(e,t,r,i){let s=e[r],n=e[r+1],o=t-this.stride;for(let a=t;a<r;a+=2)i?i(s,n,e[a],e[a+1])&&(o+=this.stride,this.swap(e,o,a)):(s>e[a]||s==e[a]&&n>e[a+1])&&(o+=this.stride,this.swap(e,o,a));return this.swap(e,o+this.stride,r),o+this.stride}swap(e,t,r){let i=e[t],s=e[t+1];return e[t]=e[r],e[t+1]=e[r+1],e[r]=i,e[r+1]=s,e}sortArrayPart(e,t,r,i){if(t<r){let s=this.partition(e,t,r,i);this.sortArrayPart(e,t,s-this.stride,i),this.sortArrayPart(e,s+this.stride,r,i)}}}function De(e,t,r,i,s,n){return(r-e)*(n-t)-(i-t)*(s-e)}function ke(e,t,r,i,s,n){let o=e-r,a=s-r,l=o*(n-i)-a*(t-i);l*=l,o=s-r,a=n-i;let h=o*o+a*a;return h>0?Math.sqrt(l/h):Math.sqrt((r-e)*(r-e)+(i-t)*(i-t))}var Ne=Object.freeze({__proto__:null,vector:function(e,t){let r,i={};return Object.defineProperty(i,"x",{value:t.x-e.x,enumerable:!0}),Object.defineProperty(i,"y",{value:t.y-e.y,enumerable:!0}),Object.defineProperty(i,"length",{get:()=>(isNaN(r)&&(r=Math.sqrt(i.x*i.x+i.y*i.y)),r),enumerable:!0}),i},angle:function(e,t){let r=e.x*t.x+e.y*t.y,i=e.x*t.y-e.y*t.x;return Math.atan2(i,r)},cross:De,perpendicularDistance:ke});class Me{constructor(e=Float32Array){this.ArrayType=e,this.quickSort=new Oe}monotoneChain(e){if(e.length<=0)return new this.ArrayType;this.quickSort.sort(e);let t=new this.ArrayType(e.length),r=0;for(let i=0;i<e.length;i+=2){for(;r>=4&&De(t[r-4],t[r-3],t[r-2],t[r-1],e[i],e[i+1])<=0;)r-=2;t[r]=e[i],t[r+1]=e[i+1],r+=2}t=t.slice(0,r);let i,s=new this.ArrayType(e.length);r=0;for(let t=e.length-2;t>=0;t-=2){for(;r>=4&&De(s[r-4],s[r-3],s[r-2],s[r-1],e[t],e[t+1])<=0;)r-=2;s[r]=e[t],s[r+1]=e[t+1],r+=2}if(s=s.slice(0,r-2),this.ArrayType==Float32Array){let e=s.length+t.length;i=Float32Array.createSharedInstance(e),i.set(s),i.set(t,s.length)}else i=s.concat(t);return i}}class Le{constructor(e,t=[]){if(!(e instanceof Ae))throw new Error("Expected shape type is Path. Use createInstance or createSharedInstance Polygon methods to allocate instance.");if(t.some((e=>!(e instanceof Ae))))throw new Error("Expected hole type is Path. Use createInstance or createSharedInstance Polygon methods to allocate instance.");let r;this.holesDirection=Le.PointsDirection.CLOCKWISE,Object.defineProperty(this,"shape",{value:e,enumerable:!0}),Object.defineProperty(this,"holes",{value:t,enumerable:!0}),Object.defineProperty(this,"contours",{value:[e,...t],enumerable:!0}),Object.defineProperty(this,"ArrayType",{value:e.points instanceof Float32Array?Float32Array:Array}),Object.defineProperty(this,"bounds",{get:()=>v.ofPolygon(this),enumerable:!0}),Object.defineProperty(this,"vertices",{get:()=>(r||(r=this.triangulate()),r),set:e=>r=e,enumerable:!0}),Object.defineProperty(this,"verticesValue",{get:()=>r})}clone(e=!1){let t=this.shape.clone(e),r=this.holes.map((t=>t.clone(e))),i=new Le(t,r);return this.verticesValue&&(i.vertices=this.vertices.slice()),i}fit(e){let t=this.bounds,r=e.width/t.width,i=e.height/t.height,s=r>0&&i>0?Math.min(r,i):Math.max(r,i);for(let e of this.contours)for(let t=0;t<e.length;t++)e.setPointX(t,e.getPointX(t)*s),e.setPointY(t,e.getPointY(t)*s)}center(){let e=this.bounds;for(let t of this.contours)for(let r=0;r<t.length;r++)t.setPointX(r,t.getPointX(r)-e.center.x),t.setPointY(r,t.getPointY(r)-e.center.y)}transform(e){this.contours.forEach((t=>t.transform(e)))}intersects(e){if(!(e instanceof Le))throw new Error("Expected 'poly' type is Polygon");(this.holes.length>0||e.holes.length)&&console.warn("Polygon intersection is for contours only. Holes are ignored.");let t=this.shape,r=e.shape;for(let e=0;e<2;e++){let i=0==e?t:r;for(let e=0;e<i.length;e++){let s=e+1==i.length?0:e+1,n=i.getPointX(e),o=i.getPointY(e),a=i.getPointX(s),l=i.getPointY(s)-o,h=n-a,d=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY;for(let e=0;e<t.length;e++){let r=l*t.getPointX(e)+h*t.getPointY(e);r<d&&(d=r),r>c&&(c=r)}let p=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(let e=0;e<r.length;e++){let t=l*r.getPointX(e)+h*r.getPointY(e);t<p&&(p=t),t>u&&(u=t)}if(c<p||u<d)return!1}}return!0}containsPoint(e){let t=!1,r=this.shape;this.holes.length>0&&console.warn("Polygon intersection is for contours only. Holes are ignored.");for(let i=0,s=r.length-1;i<r.length;s=i++)r.getPointY(i)>e.y!=r.getPointY(s)>e.y&&e.x<(r.getPointX(s)-r.getPointX(i))*(e.y-r.getPointY(i))/(r.getPointY(s)-r.getPointY(i))+r.getPointX(i)&&(t=!t);return t}triangulate(){let e,t=[];for(let e of this.contours){let r=[];for(let t=0;t<e.length;t++){let i=new ge(e.getPointX(t),e.getPointY(t));if(t>0){if(r.last.x==i.x&&r.last.y==i.y)continue;if(t==e.length-1&&r.first.x==i.x&&r.first.y==i.y)continue}r.push(i)}t.push(r)}try{e=new me(t.shift())}catch(e){return console.error(e),new Float32Array}for(let r of t)try{e.addHole(r)}catch(e){return console.error(e),new Float32Array}try{e.triangulate()}catch(e){return console.warn(e),new Float32Array}let r=e.getTriangles(),i=Float32Array.createSharedInstance(6*r.length),s=0;for(let e of r){let t=e.getPoints();for(let e of t)i[s++]=e.x,i[s++]=e.y}return i}convex(){return this.buildConvex(this.shape.points)}union(e){let t=Array.of(...this.shape.points,...e.shape.points);return this.buildConvex(t)}buildConvex(e){this.convexHullProducer||(this.convexHullProducer=new Me(this.ArrayType));let t=this.convexHullProducer.monotoneChain(e);return this.ArrayType==Float32Array?Le.createSharedInstance(t):Le.createInstance(t)}simplify(e=.1){let t=new Ce([this],this.bounds);return t.subject=be.SimplifyPolygons(t.subject,we.pftNonZero),t.solution=be.CleanPolygons(t.subject,e*t.transform.scale),1==t.subject.length&&0==t.solution.first.length&&(t.solution=t.subject),Le.toPolygonArray(t.toPaths())}simplifyRamerDouglasPeucker(e=.1){if(e<=0)throw new Error("epsilon expected value > 0");this.epsilon=e;let t=this.simplifyPath(this.shape),r=[];for(let e of this.holes){let t=this.simplifyPath(e);t.length>0&&r.push(t)}return this.ArrayType==Float32Array?Le.createSharedInstance(t,r):Le.createInstance(t,r)}simplifyPath(e){if(e.length<3)return e.points;let t=Array.of(...e.points,e.getPointX(0),e.getPointY(0)),r=this.simplifyPolyline(t);return r.length<8?t.slice(0,t.length-2):r.slice(0,r.length-2)}simplifyPolyline(e){if(e.length<4)return e;let t=0,r=0;for(let i=2;i<e.length-2;i+=2){let s=ke(e[i],e[i+1],e[0],e[1],e[e.length-2],e[e.length-1]);s>t&&(r=i,t=s)}if(t>this.epsilon){let t=this.simplifyPolyline(e.slice(0,r+2)),i=this.simplifyPolyline(e.slice(r,e.length));return t.concat(i.slice(2,i.length))}return[e[0],e[1],e[e.length-2],e[e.length-1]]}toSVGPath(){return this.contours.map((e=>e.toSVGPath())).join(" ")}toJSON(){return{type:"Polygon",shape:this.shape.toJSON(),holes:this.holes.map((e=>e.toJSON())),holesDirection:this.holesDirection.name,vertices:this.verticesValue}}static fromJSON(e){if("Polygon"!=e.type)throw new Error(`Polygon deserialization failed. JSON type is ${e.type}, expected Polygon.`);let t=Ae.fromJSON(e.shape),r=e.holes.map((e=>Ae.fromJSON(e))),i=new Le(t,r);return i.holesDirection=Le.PointsDirection[e.holesDirection],i.vertices=e.vertices,i}static fromRect(e){return Le.createInstance([e.left,e.top,e.right,e.top,e.right,e.bottom,e.left,e.bottom,e.left,e.top])}static createInstance(e,t=[]){return new Le(Ae.createInstance(e),t.map((e=>Ae.createInstance(e))))}static createSharedInstance(e,t=[]){let r=new Le(Ae.createSharedInstance(e),t.map((e=>Ae.createSharedInstance(e))));return Object.defineProperty(r,"encoding",{get:()=>r.shape.encoding,set:e=>{r.contours.forEach((t=>t.encoding=e))},enumerable:!0}),r}}Object.defineEnum(Le,"PointsDirection",["CLOCKWISE","COUNTERCLOCKWISE"]);class _e{static SHAPE_FRAME=new v(-.5,-.5,1,1);constructor(e,t=1){this.size=t,Object.defineProperty(this,"descriptor",{value:{shape:void 0},enumerable:!0}),Object.defineProperty(this,"shape",{get:function(){if(!e){if("function"==typeof(e=this.descriptor.shape.value)&&(e=e()),(Array.isArray(e)||e instanceof Float32Array)&&(e=Le.createSharedInstance(e)),!(e instanceof Le))throw new Error("Expected shape type is Polygon");_e.fitShape(e)}return e},set:function(t){if(!t)throw new Error("BrushPrototype: shape not found");"string"==typeof t?t=new ce(t):t instanceof Le||t instanceof Float32Array||Array.isArray(t)?t=ce.getInstance(t):t instanceof ce||(t=new ce(t.name,t.value)),e=null,this.descriptor.shape=t,this.descriptor.shape.resolve=_e.resolve},enumerable:!0}),this.shape=e}toJSON(){return this.shape.encoding=this.encoding,{shape:{name:this.descriptor.shape.name,value:this.shape.toJSON()},size:this.size}}static fromJSON(e){return new _e({name:e.shape.name,value:Le.fromJSON(e.shape.value)},e.size)}static create(e,t=0,...r){let i,s=e;switch(e){case _e.Type.CIRCLE:i=ue.createCircle(...r),s+=`?precision=${r[0]||ue.defaults.CIRCLE_PRECISION}&radius=${r[1]||ue.defaults.CIRCLE_RADIUS}`;break;case _e.Type.ELLIPSE:i=ue.createEllipse(...r),s+=`?precision=${r[0]||ue.defaults.ELLIPSE_PRECISION}&radiusX=${r[1]||ue.defaults.ELLIPSE_RADIUS_X}&radiusY=${r[2]||ue.defaults.ELLIPSE_RADIUS_Y}`;break;case _e.Type.STAR:i=ue.createStar(...r),s+=`?points=${r[0]||ue.defaults.STAR_POINTS}&internalRadius=${r[1]||ue.defaults.STAR_INTERNAL_RADIUS}&radius=${r[2]||ue.defaults.STAR_RADIUS}`;break;default:console.error(`Brush2D: createShape fails with ${e} type`)}return new _e({name:s,shape:i},t)}static resolve(e){let t,r=e.split("?"),i=r.first;if(Object.values(_e.Type).includes(i)){let e=r.last.split("&"),s={};switch(e.forEach((e=>{s[e.substring(0,e.indexOf("="))]=e.substring(e.indexOf("=")+1)})),i){case _e.Type.CIRCLE:{let e=s.precision?parseInt(s.precision):void 0,r=s.radius?parseFloat(s.radius):1;t=ue.createCircle(e,r);break}case _e.Type.ELLIPSE:{let e=s.precision?parseInt(s.precision):void 0,r=s.radiusX?parseFloat(s.radiusX):void 0,i=s.radiusY?parseFloat(s.radiusY):void 0;t=ue.createEllipse(e,r,i);break}case _e.Type.STAR:{let e=s.points?parseInt(s.points):void 0,r=s.radius?parseFloat(s.radius):void 0,i=s.internalRadius?parseFloat(s.internalRadius):void 0;t=ue.createStar(e,i,r);break}default:console.error(`Brush2D: createShape fails with ${i} type`)}}return t}static fitShape(e){if(!(e instanceof Le))throw new Error("Expected shape type is Polygon");e.center(),e.fit(_e.SHAPE_FRAME)}}async function Fe(e,t="binary",r={}){if(e instanceof Uint8Array)return e;let i,s=await fetch(e,Object.assign({mode:"no-cors"},r));if("json"==t)i=await s.json();else if("text"==t)i=await s.text();else if("binary"==t){let e=await s.arrayBuffer();i=new Uint8Array(e)}else{let e=await s.blob();i="base64"==t?await Ue(e):e}return i}async function Be(e,t="binary",r={}){return Fe(e,t,r)}function Ue(e){return new Promise(((t,r)=>{let i=new FileReader;i.onloadend=()=>t("data:"==i.result?"":i.result),i.onerror=r,i.readAsDataURL(e)}))}async function je(e){let t;return t="string"==typeof e||"undefined"==typeof createImageBitmap?await function(e){return new Promise(((t,r)=>{let i,s=new ie;s.crossOrigin="anonymous",s.onload=()=>{if(G.type2D==G.Type2D.OFFSCREEN){const e=new ne(s.width,s.height);e.getContext("2d").drawImage(s,0,0),t(e)}else i&&URL.revokeObjectURL(i),t(s)},s.onerror=r,"string"==typeof e?s.src=e:G.type2D==G.Type2D.OFFSCREEN?e instanceof Uint8Array?s.src=Buffer.from(e):e instanceof ne?t(e):s.src=e:(e instanceof Uint8Array&&(e.byteLength!=e.buffer.byteLength&&(e=e.slice()),e=e.buffer),e instanceof ArrayBuffer&&(e=new Blob([e],{type:"image/png"})),i=URL.createObjectURL(e),s.src=i)}))}(e):e instanceof ArrayBuffer||e instanceof Uint8Array?await createImageBitmap(new Blob([e],{type:"image/png"})):await createImageBitmap(e),t}_e.Type={ELLIPSE:"will://brush/3.0/shape/Ellipse",CIRCLE:"will://brush/3.0/shape/Circle",STAR:"will://brush/3.0/shape/Star"};var Ge=Object.freeze({__proto__:null,readFile:Fe,loadFile:Be,exists:async function(e,t={}){return 200==(await fetch(e,Object.assign({method:"HEAD",cache:"no-store"},t))).status},dataURL:Ue,loadImage:je,saveAs:function(e,t,r="application/octet-stream"){let i;if(e instanceof Blob)i=URL.createObjectURL(e);else{let t;if(e instanceof ArrayBuffer)t=[e];else if(e.buffer)e.byteLength<e.buffer.byteLength&&(e=new Uint8Array(e)),t=[e.buffer];else if(e instanceof Array)t=e;else{if("string"!=typeof e)throw new Error("content expected type not found");t=[e]}let s=new Blob(t,{type:r});i=URL.createObjectURL(s)}let s=document.createElement("a");s.href=i,s.download=t,s.appendChild(document.createTextNode(t)),s.style.display="none",document.body.appendChild(s),s.click(),setTimeout((function(){URL.revokeObjectURL(i),s.remove()}),911)}});class $e extends pe{constructor(e,t,r,i=1){super(e),isFinite(r)&&(i=r,r=void 0),i<=0&&(console.warn(`Invalid spacing found ${i}. It should be positive number.`),i=1),Object.defineProperty(this,"shape",{get:()=>t,set:e=>{if(e instanceof Float32Array&&(e=new _e(e)),e instanceof _e&&(e=[e]),e.some((e=>!(e instanceof _e))))throw console.warn(e),new Error("Brush2D: Invalid shape found");e.sort(M.comparator({sortBy:"size",sortOrder:"asc"})),t=e},enumerable:!0}),this.shape=t,this.fill=r,this.spacing=i}async configure(e){if(this.pattern||!this.fill)return;if(!(e instanceof oe||e instanceof ae))throw new Error("ctx is not instance of CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D");let t=await je(this.fill);this.pattern=e.createPattern(t,"repeat")}selectShape(e){let t;for(let r=1;r<this.shape.length;r++)if(this.shape[r].size>e){t=this.shape[r-1];break}return t||(t=this.shape.last),t.shape}toJSON(){return{type:"Brush2D",name:this.name,spacing:this.spacing,shape:this.shape.map((e=>(e.encoding=this.encoding,e.toJSON())))}}static fromJSON(e){let t=1==e.shape.length?_e.fromJSON(e.shape[0]):e.shape.map((e=>_e.fromJSON(e)));return new $e(e.name,t,e.spacing)}}class Ye{static get excludedProps(){return[U.Property.D_X,U.Property.D_Y]}static get posProps(){return[U.Property.X,U.Property.Y,U.Property.Z]}static get colorProps(){return[U.Property.RED,U.Property.GREEN,U.Property.BLUE,U.Property.ALPHA]}static get transformProps(){return[U.Property.ROTATION,U.Property.SCALE_X,U.Property.SCALE_Y,U.Property.SCALE_Z,U.Property.OFFSET_X,U.Property.OFFSET_Y,U.Property.OFFSET_Z]}constructor(){this.state={}}isLayoutPart(e){if(Ye.posProps.includes(e))return this.inputLayout.includes(e.name);if(this.brush instanceof $e&&Ye.colorProps.includes(e))return!1;if(Ye.excludedProps.includes(e))return!1;let t=!1,r=M.getPropName(e.name),i=this.dynamics[r];if(i&&!i.disabled)if(i.dependencies&&i.dependencies.length>0){let e=this.inputLayout.map((e=>H.Type[e]));t=i.dependencies.filter((t=>e.includes(t))).length>0}else t=!0;return t}calculate(e,t,r){return this.point=t.createPathPoint(this.statics),this.calculateProperty(U.Property.SIZE,e,t,r),Ye.colorProps.forEach((i=>this.calculateProperty(i,e,t,r))),Ye.transformProps.forEach((i=>this.calculateTransform(i,e,t,r))),this.point}calculateProperty(e,t,r,i){if(!this.layout.includes(e))return;let s,n=M.getPropName(e.name),o=this.dynamics[n],a=this.state[n];if("function"==typeof a.resolve)s=a.resolve(t,r,i);else if(this.inputLayout.includes("PRESSURE")){let e=r.pressure||t.pressure/2;s=Ye.mapTo(e,a.pressure,o.value)}else{let e=r.speed(t,i);0==e&&t&&(e=t.velocity),r.velocity=e,s=Ye.mapTo(e,a.velocity,o.value)}this.point[M.getPropName(e.name)]=s}calculateTransform(e,t,r,i){if(!this.layout.includes(e))return;let s,n=M.getPropName(e.name),o=this.dynamics[n],a=this.state[n];if("function"==typeof a.resolve)s=a.resolve(t,r,i);else{let i=o.dependencies||[];if(e==U.Property.ROTATION)if(i.includes(H.Type.ROTATION)&&this.inputLayout.includes("ROTATION"))s=r.rotation;else{if(!i.includes(H.Type.AZIMUTH)||!this.inputLayout.includes("AZIMUTH"))throw new Error(`Property ${e.name} is not configured properly. Dependencies are expected or resolve handler.`);s=r.computeNearestAzimuthAngle(t)}else if(i.includes(H.Type.ALTITUDE)&&this.inputLayout.includes("ALTITUDE")){r.cosAltitude||(r.cosAltitude=Math.cos(r.altitude));let e=r.cosAltitude;s=Ye.mapTo(e,a.altitude,o.value)}else{if(e!=U.Property.SCALE_X&&e!=U.Property.SCALE_Y||!i.includes(H.Type.RADIUS_X)&&!i.includes(H.Type.RADIUS_Y)||!this.inputLayout.includes("RADIUS_X")||!this.inputLayout.includes("RADIUS_Y"))throw new Error(`Property ${e.name} is not configured properly. Dependencies are expected or resolve handler.`);{let t=e==U.Property.SCALE_X?"radiusX":"radiusY",i=r[t];s=Ye.mapTo(i,a[t],o.value)}}}if(isNaN(s))throw new Error(`Property ${e.name} has no value`);this.point[M.getPropName(e.name)]=s}reset(e,t,r,i={},s={}){if(this.brush=t,this.dynamics=i,this.statics={},this.color=new ve(0,0,0),this.inputLayout=ee.getLayout(e),this.layout=U.Property.values.filter((e=>this.isLayoutPart(e))),this.debug&&console.log(e.pointer.type,this.inputLayout,this.layout.map((e=>e.name)),e),"size"in s){if(this.isLayoutPart(U.Property.SIZE))throw new Error("Size should exist only in dynamics or statics");this.statics.size=s.size}else{if(!this.isLayoutPart(U.Property.SIZE))throw new Error("Size not found. Should be set through dynamics or statics.");if(0==e.pressure&&"pen"==e.pointer.type)throw new Error("Hover point detected. Should be handeled manually.")}Ye.colorProps.forEach((e=>{let t=M.getPropName(e.name);this.isLayoutPart(e)?this.color[t]=r[t]:(this.statics[t]=isFinite(s[t])?s[t]:r[t],this.color[t]=this.statics[t])})),Ye.transformProps.forEach((e=>{if(this.isLayoutPart(e))return;let t=M.getPropName(e.name);isFinite(s[t])&&(this.statics[t]=s[t])})),this.resetState(e)}resetState(e){this.state={},[U.Property.SIZE].concat(Ye.colorProps).forEach((e=>{if(!this.layout.includes(e))return;let t=M.getPropName(e.name),r=this.dynamics[t],i={};if(r.resolve)i.resolve=Ye.resolveAction(r.resolve);else{if(!r.value)throw new Error(`PathPointContext: dynamics ${t} value property not found`);if(r.value.min>r.value.max)throw new Error(`PathPointContext: dynamics ${t} invalid value range found: ${r.value.min} - ${r.value.max}`);let e=this.clonePropertySettings(r.velocity,0,4e3);e.remap=Ye.resolveAction(e.remap||r.value.remap);let s=this.clonePropertySettings(r.pressure,0,1);s.remap=Ye.resolveAction(s.remap||r.value.remap),i.velocity=Ye.validateRange(t,e,{min:0,max:3e4}),i.pressure=Ye.validateRange(t,s,{min:0,max:1})}this.state[t]=i})),Ye.transformProps.forEach((t=>{if(!this.layout.includes(t))return;let r=M.getPropName(t.name),i=this.dynamics[r],s={};if(i.resolve)s.resolve=Ye.resolveAction(i.resolve);else if(i.dependencies){if(i.dependencies.includes(H.Type.ALTITUDE)){if(!i.value)throw new Error(`PathPointContext: dynamics ${r} value property not found`);if(i.value.min>i.value.max)throw new Error(`PathPointContext: dynamics ${r} invalid value range found: ${i.value.min} - ${i.value.max}`);let e=this.clonePropertySettings(i.altitude,0,Math.PI/2);e.remap=Ye.resolveAction(e.remap||i.value.remap),s.altitude=Ye.validateRange(r,e,{min:0,max:Math.PI/2})}if(t==U.Property.SCALE_X&&i.dependencies.includes(H.Type.RADIUS_X)||t==U.Property.SCALE_Y&&i.dependencies.includes(H.Type.RADIUS_Y)){if(!i.value)throw new Error(`PathPointContext: dynamics ${r} value property not found`);let n=t==U.Property.SCALE_X?"radiusX":"radiusY",o=i[n]||{},a=e[n]<=1?0:1,l=e[n]<=1?1:50,h=e[n]<=1?{min:0,max:1,remap:o.remap}:o,d=this.clonePropertySettings(h,a,l);d.remap=Ye.resolveAction(d.remap||i.value.remap),s[n]=Ye.validateRange(r,d,{min:a,max:l})}}this.state[r]=s}))}clonePropertySettings(e,t,r){let i;return e?(i=Object.clone(e),"min"in i||(i.min=t),"max"in i||(i.max=r)):i={min:t,max:r},i}static resolveAction(e){if(e)return"string"==typeof e?e=new ce(e):"function"==typeof e?e=ce.getInstance(e):e instanceof ce||(e=new ce(e.name,e.value)),e.value}static validateRange(e,t,r){if(t.min<r.min||t.max>r.max)throw new Error(`${e} config is out of range - (${t.min}, ${t.max}), expected values interval - (${r.min}, ${r.max})`);if(t.min>t.max)throw new Error(`${e} min ${t.min} exceeds max ${t.max}`);return t}static mapTo(e,t,r){let i=(M.clamp(e,t)-t.min)/(t.max-t.min);return t.remap&&(i=t.remap(i)),r.min+i*(r.max-r.min)}}class Xe{static ARRAY_TYPE=Array;#n;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.#n||(this.#n=new this.constructor.ARRAY_TYPE),this.getOutput(this.#n,Xe.OutputType.ALL_DATA)},enumerable:!0})}build(e,t=Xe.OutputType.PROCESSOR,r=!0){return console.warn("use process instead"),this.process(e,t,r)}process(e,t=Xe.OutputType.PROCESSOR,r=!0){let i;switch(t){case Xe.OutputType.ADDITION:i=this.add(e,r);break;case Xe.OutputType.PREDICTION:i=this.predict(e);break;case Xe.OutputType.PROCESSOR:this.reset(),i=this.processImpl(e,t);break;default:throw new Error("Unexpected OutputType found. Allowed type is oneof(ADDITION, PREDICTION, PROCESSOR)")}return t!=Xe.OutputType.PREDICTION&&this.keepAllData&&(this.#n||(this.#n=new this.constructor.ARRAY_TYPE),i instanceof Le?this.#n.push(i):t==Xe.OutputType.PROCESSOR?this.#n=i:this.#n.push(...i)),this.debug&&console.log(this.constructor.name,t.name,r,i),this.getOutput(i,t)}add(e,t=!1){return this.processImpl(e,Xe.OutputType.ADDITION)}predict(e){return this.processImpl(e,Xe.OutputType.PREDICTION)}processImpl(e,t){throw new Error("Abstract method processImpl(input, type) of DataSequenceProcessor should be implemented")}getOutput(e,t){return e}reset(){this.#n&&(this.#n=new this.constructor.ARRAY_TYPE)}}function ze(){}Object.defineEnum(Xe,"OutputType",["ADDITION","PREDICTION","ALL_DATA","PROCESSOR"]),ze.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 Ve=ze.BlendMode;class He{static ANTIALIASING={passesSqrt:4,passes:16,spread:1.25,step:.3125,weight:1.01/16};static IDENTITY_MATRIX=r.mat4.create();constructor(e){if(!e)throw new Error("GL context is not available in current environment");let t,r;this.gl=e,this.program=null,this.programs=[],Object.defineProperty(this,"blendMode",{get:()=>t,set:e=>{if(!e)throw new Error("blendMode is required");t!=e&&(this.activeBlendMode(e),t=e)},enumerable:!0}),Object.defineProperty(this,"transform",{get:()=>r&&!r.isIdentity?r:null,set:e=>{e!=r&&(r=e,this.program&&this.program.onContextChange())}}),Object.defineProperty(He,"VERTEX_SHADER_PRECISION",{value:this.getSupportedFloatPrecision(this.gl.VERTEX_SHADER),enumerable:!0,configurable:!0}),Object.defineProperty(He,"FRAGMENT_SHADER_PRECISION",{value:this.getSupportedFloatPrecision(this.gl.FRAGMENT_SHADER),enumerable:!0,configurable:!0}),Object.defineProperty(He,"VERTEX_BATCH_SIZE",{value:1e3,enumerable:!0})}init(e,t){this.gl.disable(this.gl.DITHER),this.gl.disable(this.gl.BLEND),this.gl.disable(this.gl.STENCIL_TEST),this.gl.disable(this.gl.DEPTH_TEST),this.gl.disable(this.gl.SCISSOR_TEST),this.gl.activeTexture(this.gl.TEXTURE0),this.blendMinMaxExt=this.gl.getExtension("EXT_blend_minmax"),this.blendMaxFallback=!this.gl.MAX&&!this.blendMinMaxExt,this.blendMode=Ve.COPY,this.resize(e,t),this.scatterMethodRandomSeed=parseInt(Date.now()/1e3),this.onChange();for(let e=0;e<this.programs.length;e++)this.programs[e].init()}getSupportedFloatPrecision(e){return this.gl.getShaderPrecisionFormat(e,this.gl.HIGH_FLOAT).precision>0?"highp":this.gl.getShaderPrecisionFormat(e,this.gl.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}random(){return this.scatterMethodRandomSeed=1103515245*this.scatterMethodRandomSeed+12345&Number.MAX_INT32,this.scatterMethodRandomSeed/Number.MAX_INT32}static random(e){return(1103515245*e+12345&Number.MAX_INT32)/Number.MAX_INT32}setUniforms(e){let t=r.mat4.create();e?r.mat4.ortho(t,this.graphicsBox.left,this.graphicsBox.right,this.graphicsBox.top,this.graphicsBox.bottom,1,-1):r.mat4.ortho(t,this.graphicsBox.left,this.graphicsBox.right,this.graphicsBox.bottom,this.graphicsBox.top,1,-1),this.graphicsSpaceToFramebufferSpaceT=t,this.onChange()}resize(e,t){this.gl.viewport(e.x,e.y,e.width,e.height),this.bounds=e,this.graphicsBox=t,this.clipRect=t}activeBlendMode(e){switch(e){case Ve.COPY:this.gl.disable(this.gl.BLEND);break;case Ve.SOURCE_OVER:this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA);break;case Ve.DESTINATION_OVER:this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ONE_MINUS_DST_ALPHA,this.gl.ONE);break;case Ve.DESTINATION_IN:this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ZERO,this.gl.SRC_ALPHA);break;case Ve.DESTINATION_OUT:this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ZERO,this.gl.ONE_MINUS_SRC_ALPHA);break;case Ve.DESTINATION_IN_MULTIPLY:this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ZERO,this.gl.SRC_COLOR);break;case Ve.DESTINATION_OUT_NO_ALPHA:this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ZERO,this.gl.ONE_MINUS_SRC_COLOR);break;case Ve.LIGHTER:this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ONE,this.gl.ONE);break;case Ve.MIN:this.gl.enable(this.gl.BLEND),this.gl.MIN?this.gl.blendEquation(this.gl.MIN):this.blendMinMaxExt?this.gl.blendEquation(this.blendMinMaxExt.MIN_EXT):(this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA));break;case Ve.MAX:this.gl.enable(this.gl.BLEND),this.gl.MAX?this.gl.blendEquation(this.gl.MAX):this.blendMinMaxExt?this.gl.blendEquation(this.blendMinMaxExt.MAX_EXT):(this.gl.blendEquation(this.gl.FUNC_ADD),this.gl.blendFunc(this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA));break;case Ve.DIRECT_SOURCE_OUT:this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_SUBTRACT),this.gl.blendFunc(this.gl.ONE,this.gl.ONE);break;case Ve.DIRECT_DESTINATION_OUT:this.gl.enable(this.gl.BLEND),this.gl.blendEquation(this.gl.FUNC_REVERSE_SUBTRACT),this.gl.blendFunc(this.gl.ONE,this.gl.ONE);break;default:throw new Error(`Unsupported blend mode: ${e}`)}}clearColorBuffer(e){this.gl.clearColor(e.red*e.alpha/255,e.green*e.alpha/255,e.blue*e.alpha/255,e.alpha),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}scissors(e){if(e&&!(e instanceof x))throw new TypeError("rect must be undefined or instanceof RectGL");let t=this.gl.isEnabled(this.gl.SCISSOR_TEST);e?(t||this.gl.enable(this.gl.SCISSOR_TEST),this.gl.scissor(e.x,e.y,e.width,e.height)):t&&this.gl.disable(this.gl.SCISSOR_TEST)}isProgramActive(e){return this.program==e}activateProgram(e){this.isProgramActive(e)?e.contextChanged&&(e.onContextChange(),e.contextChanged=!1):(this.program&&this.program.onDeactivate(),this.gl.useProgram(e.program),this.program=e,e.onActivate(),e.onContextChange(),e.contextChanged=!1)}generateBuffersExt(e,t,r,i){let s=this.gl,n=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,n);let o=s.createTexture();return s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,r),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,i,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,o,0),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT),{framebuffer:n,texture:o}}genFrameAndRenders(e,t,r){let i=this.gl.createFramebuffer(),s=this.gl.createRenderbuffer();return this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,i),this.gl.bindRenderbuffer(this.gl.RENDERBUFFER,s),this.gl.renderbufferStorage(this.gl.RENDERBUFFER,e,t,r),this.gl.framebufferRenderbuffer(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.RENDERBUFFER,s),{framebuffer:i,renderbuffer:s}}deleteBuffers(e,t){t&&this.gl.deleteTexture(t),e&&this.gl.deleteFramebuffer(e)}deleteFrameAndRender(e,t){t&&this.gl.deleteRenderbuffer(t),e&&this.gl.deleteFramebuffer(e)}onChange(){for(let e=0;e<this.programs.length;e++)this.programs[e].contextChanged=!0}enableStencilBufferForBlending(e){this.gl.enable(this.gl.STENCIL_TEST),this.gl.stencilMask(4294967295),this.gl.clearStencil(0),this.gl.clear(this.gl.STENCIL_BUFFER_BIT),this.isStencilBufferAvailable()||this.attachStencilBufferForBlending(e)}isStencilBufferAvailable(){return this.gl.getFramebufferAttachmentParameter(this.gl.FRAMEBUFFER,this.gl.STENCIL_ATTACHMENT,this.gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE)==this.gl.RENDERBUFFER}attachStencilBufferForBlending(e){let t=this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING);if(e.framebuffer==t){let t=this.gl.createRenderbuffer();this.gl.bindRenderbuffer(this.gl.RENDERBUFFER,t),this.gl.renderbufferStorage(this.gl.RENDERBUFFER,this.gl.STENCIL_INDEX8,e.width,e.height),this.gl.framebufferRenderbuffer(this.gl.FRAMEBUFFER,this.gl.STENCIL_ATTACHMENT,this.gl.RENDERBUFFER,t),e.renderbuffer=t,e.releaseRenderbuffer=!0}}drawArrays(e,t,r){this.blendMode==Ve.MAX&&this.blendMaxFallback?this.drawBlendMaxFallback(this.gl.drawArrays.bind(this.gl,e,t,r)):this.gl.drawArrays(e,t,r)}drawElements(e,t,r,i){this.blendMode==Ve.MAX&&this.blendMaxFallback?this.drawBlendMaxFallback(this.gl.drawElements.bind(this.gl,e,t,r,i)):this.gl.drawElements(e,t,r,i)}drawBlendMaxFallback(e){this.gl.enable(this.gl.STENCIL_TEST),this.gl.stencilFunc(this.gl.NOTEQUAL,1,1),this.gl.stencilOp(this.gl.REPLACE,this.gl.REPLACE,this.gl.REPLACE),this.blendMode=Ve.DIRECT_DESTINATION_OUT,e(),this.gl.stencilFunc(this.gl.NOTEQUAL,2,1),this.gl.stencilOp(this.gl.REPLACE,this.gl.REPLACE,this.gl.REPLACE),this.inkGLContext.blendMode=Ve.LIGHTER,e(),this.gl.disable(this.gl.STENCIL_TEST)}static logGLError(e,t=""){let r=e.getError();if(r>0){let i;e.constructor.prototype&&(i=Object.keys(e.constructor.prototype).filter((t=>e[t]===r)).join(" | ")),console.error(`WebGL${t?" ":""}${t}: ${r}${i?` - ${i}`:""}`)}}}class Ze{constructor(){}setTransform(e){this.matrix=e}getExportCanvas(e){throw new Error("Abstract method getExportCanvas of Layer inheritor should be implemented")}async toBlob(e,t="image/png",r=.92){if("undefined"==typeof Blob)throw"undefined"==typeof Buffer?new Error("Current environment do not have neither Blob nor Buffer support."):new Error("This method is not compliant in underlying environment. Use `toBuffer` instead.");let i=this.getExportCanvas(e);return i.toBlob?new Promise(((e,s)=>i.toBlob(e,t,r))):i.convertToBlob({type:t,quality:r})}async toBuffer(e,t="image/png",r={}){if("undefined"==typeof Buffer)throw"undefined"==typeof Blob?new Error("Current environment do not have neither Blob nor Buffer support."):new Error("This method is not compliant in underlying environment. Use `toBlob` instead.");let i=this.getExportCanvas(e);if(r.filters){let e=Array.isArray(r.filters)?r.filters.slice():[r.filters],t=0;e.forEach((e=>{t|=i[`PNG_FILTER_${e.name}`]})),Object.assign({},r,{filters:t})}return new Promise(((e,s)=>i.toBuffer(((t,r)=>t?s(t):e(r)),t,r)))}static getDefaultSize(e,t){let r={};return"undefined"==typeof screen?(r.width=e,r.height=t):navigator.maxTouchPoints?(r.width=Math.max(screen.width,screen.height),r.height=r.width):(r.width=screen.width,r.height=screen.height),r}}Object.defineEnum(Ze,"PNGFilterType",["NO","ALL","NONE","SUB","UP","AVG","PAETH"]);class qe{constructor(e,t){Object.defineProperty(this,"ctx",{value:e,enumerable:!0}),Object.defineProperty(this,"value",{value:t,enumerable:!0}),Object.defineProperty(this,"texture",{value:t,enumerable:!0})}async update(e,t){if(Array.isArray(e)){let r=[],i=e;for(let e of i){let t=await je(e);r.push(t)}this.completeMipMap(r),this.fill(r,t)}else{let t=e,r=await je(t);this.fill(r)}}completeMipMap(e){if(e.sort(((e,t)=>t.width-e.width)),1==e.last.width)return;let t=e.last.width;for(;t>1;){t/=2;let r=new ne(e.last.width/2,e.last.height/2);r.getContext("2d").drawImage(e.last,0,0,r.width,r.height),e.push(r)}}fill(e,t){let r=this.ctx,i=this.value;if(r.bindTexture(r.TEXTURE_2D,i),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),Array.isArray(e)){let i=e;this.size=[],i.forEach(((e,t)=>{r.texImage2D(r.TEXTURE_2D,t,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),this.size.push({width:e.width,height:e.height}),e.close&&e.close()})),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR_MIPMAP_NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR)}else r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),this.size={width:e.width,height:e.height},e.close&&e.close();r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.bindTexture(r.TEXTURE_2D,null),this.logError(this.ctx,i.name)}readPixels(){let e=this.ctx,t=this.value,r=(r,i)=>{let s=new Uint8Array(r.width*r.height*4);return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,i),e.readPixels(0,0,r.width,r.height,e.RGBA,e.UNSIGNED_BYTE,s),s},i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i);let s=Array.isArray(this.size)?this.size.map(r):r(this.size,0);return e.deleteFramebuffer(i),s}logError(){let e=this.ctx.getError();if(e>0){let t=Object.keys(this.ctx.constructor.prototype).filter((t=>this.ctx[t]===e)).join(" | ");console.error(`WebGL error - ${this.texture.name}: ${e} - ${t}`)}}static createInstance(e,t=e.CLAMP_TO_EDGE,r=e.NEAREST){let i=e.createTexture();return e.bindTexture(e.TEXTURE_2D,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,r),e.bindTexture(e.TEXTURE_2D,null),new qe(e,i)}}class We extends Ze{constructor(e,t={}){if(super(),this.inkGLContext=e,this.gl=e.gl,this.scaleFactor=t.scaleFactor||1,this.flipY=!!t.flipY,this.useTextureStorage=!1,t.renderbuffer){if(!t.framebuffer)throw new Error("`framebuffer` is required when `renderbuffer` available");let e=this.initWithGLBuffers(t.framebuffer,t.renderbuffer);this.flipY=!0,this.ownGLResources=!!t.ownGLResources,this.setDimensions(e.width,e.height)}else if(t.framebuffer){let e=this.initWithGLFramebuffer(t.framebuffer);this.flipY=!0,this.ownGLResources=!!t.ownGLResources,this.setDimensions(e.width,e.height)}else if(t.texture){if(!(t.texture instanceof WebGLTexture))throw new Error("`texture` is not instance of WebGLTexture");let e;if(this.texture=t.texture,this.useTextureStorage=!0,t.width>0&&t.height>0)e={width:t.width,height:t.height};else if(this.texture.image)e={width:this.texture.image.width,height:this.texture.image.height};else{if(!this.texture.size)throw new Error("`width` and `height` are required when `texture` is available");e=this.texture.size}this.ownGLResources=!!t.ownGLResources,this.setDimensions(e.width,e.height)}else if(this.setDimensions(t.width,t.height),t.display)this.framebuffer=null,this.renderbuffer=null,this.texture=null;else if(this.useTextureStorage=!t.useBuffersStorage,this.ownGLResources=!0,this.useTextureStorage){let e=this.inkGLContext.generateBuffersExt(this.storageWidth,this.storageHeight,this.gl.LINEAR,this.gl.UNSIGNED_BYTE);this.framebuffer=e.framebuffer,this.texture=e.texture}else{let e=this.inkGLContext.genFrameAndRenders(this.gl.RGBA8||this.gl.RGBA4,this.storageWidth,this.storageHeight);this.framebuffer=e.framebuffer,this.renderbuffer=e.renderbuffer}this.releaseRenderbuffer=!1,this.deleted=!1}initWithGLFramebuffer(e){if(!(e instanceof WebGLFramebuffer))throw new Error("`framebuffer` is not instance of WebGLFramebuffer");let t,r=this.gl.getParameter(this.gl.RENDERBUFFER_BINDING);if(this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,e),this.gl.getError()==this.gl.INVALID_OPERATION)throw new Error("Invalid framebuffer");if(this.gl.checkFramebufferStatus(this.gl.FRAMEBUFFER)!=this.gl.FRAMEBUFFER_COMPLETE)throw new Error("Incomplete framebuffer");if(this.gl.getFramebufferAttachmentParameter(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE)!=this.gl.RENDERBUFFER)throw new Error("Renderbuffer attachment not found");return t=this.gl.getFramebufferAttachmentParameter(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,r),this.initWithGLBuffers(e,t)}initWithGLBuffers(e,t){if(!(e instanceof WebGLFramebuffer))throw new Error("`framebuffer` is not instance of WebGLFramebuffer");if(!(t instanceof WebGLRenderbuffer))throw new Error("`renderbuffer` is not instance of WebGLRenderbuffer");let r=this.gl.getParameter(this.gl.RENDERBUFFER_BINDING);this.gl.bindRenderbuffer(this.gl.RENDERBUFFER,t);let i=this.gl.getRenderbufferParameter(this.gl.RENDERBUFFER,this.gl.RENDERBUFFER_WIDTH),s=this.gl.getRenderbufferParameter(this.gl.RENDERBUFFER,this.gl.RENDERBUFFER_HEIGHT);return this.gl.bindRenderbuffer(this.gl.RENDERBUFFER,r),this.framebuffer=e,this.renderbuffer=t,{width:i,height:s}}setDimensions(e,t){let r=Math.ceil(e*this.scaleFactor),i=Math.ceil(t*this.scaleFactor),s=new x(0,0,e,t),n=new x(0,0,r,i);Object.defineProperties(this,{width:{value:e,enumerable:!0,configurable:!0},height:{value:t,enumerable:!0,configurable:!0},graphicsBounds:{value:s,enumerable:!0,configurable:!0},storageWidth:{value:r,enumerable:!0,configurable:!0},storageHeight:{value:i,enumerable:!0,configurable:!0},storageBounds:{value:n,enumerable:!0,configurable:!0}})}resize(e,t){e>0&&t>0&&(this.width!=e||this.height!=t)&&(this.setDimensions(e,t),this.useTextureStorage?(this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.storageWidth,this.storageHeight,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null)):this.renderbuffer&&(this.gl.bindRenderbuffer(this.gl.RENDERBUFFER,this.renderbuffer),this.gl.renderbufferStorage(this.gl.RENDERBUFFER,this.gl.RGBA8||this.gl.RGBA4,this.storageWidth,this.storageHeight)))}fillTexture(e){if(!this.texture)throw new Error("Underlying layer is not texture based");new qe(this.gl,this.texture).fill(e)}delete(){this.ownGLResources&&(this.useTextureStorage?this.inkGLContext.deleteBuffers(this.framebuffer,this.texture):this.inkGLContext.deleteFrameAndRender(this.framebuffer,this.renderbuffer)),this.releaseRenderbuffer&&this.renderbuffer&&(this.gl.deleteRenderbuffer(this.renderbuffer),this.renderbuffer=null,this.releaseRenderbuffer=!1),this.deleted=!0}deleteLater(){setTimeout((()=>this.delete()),0)}isDeleted(){return this.deleted}}class Ke{constructor(e){this.gl=e.gl,this.inkGLContext=e,this.program=this.createProgram(this.compileShader(this.constructor.getVertexShader(),this.gl.VERTEX_SHADER),this.compileShader(this.constructor.getFragmentShader(this.gl.getContextAttributes().premultipliedAlpha),this.gl.FRAGMENT_SHADER)),this.contextChanged=!0}init(){}compileShader(e,t){let r=this.gl.createShader(t);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw new Error(`${this.constructor.name} could not compile ${t==this.gl.VERTEX_SHADER?"VERTEX":"FRAGMENT"} shader: ${this.gl.getShaderInfoLog(r)}`);return r}createProgram(e,t){let r=this.gl.createProgram();if(this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),!this.gl.getProgramParameter(r,this.gl.LINK_STATUS))throw new Error(`${this.constructor.name} failed to link: ${this.gl.getProgramInfoLog(r)}`);return r}onActivate(){}onDeactivate(){}onContextChange(){}activate(){this.inkGLContext.activateProgram(this)}}class Je extends Ke{constructor(e){super(e),this.buffer=this.gl.createBuffer()}init(){this.a_position=this.gl.getAttribLocation(this.program,"a_position"),this.u_color=this.gl.getUniformLocation(this.program,"u_color"),this.u_projectionMatrix=this.gl.getUniformLocation(this.program,"u_projectionMatrix"),this.u_viewMatrix=this.gl.getUniformLocation(this.program,"u_viewMatrix")}onContextChange(){this.gl.uniform4f(this.u_color,this.color.red,this.color.green,this.color.blue,this.color.alpha),this.gl.uniformMatrix4fv(this.u_projectionMatrix,!1,this.inkGLContext.graphicsSpaceToFramebufferSpaceT),this.gl.uniformMatrix4fv(this.u_viewMatrix,!1,this.inkGLContext.transform?this.inkGLContext.transform.value:He.IDENTITY_MATRIX)}onDeactivate(){this.gl.disableVertexAttribArray(this.a_position),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}drawVertices(e,t,r,i=!0,s=!1,n=!1){let o;this.color=r.premultiply(),i&&!n?(t=this.antialias(t),o=Ve.LIGHTER):(Array.isArray(t)&&(t=new Float32Array(t)),o=n?Ve.MAX:Ve.SOURCE_OVER);let a=t.length/2;this.activate(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,e),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.buffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.a_position),this.gl.vertexAttribPointer(this.a_position,2,this.gl.FLOAT,!1,0,0),s&&(this.inkGLContext.blendMode=Ve.DIRECT_DESTINATION_OUT,this.gl.drawArrays(this.gl.TRIANGLES,0,a)),this.inkGLContext.blendMode=o,this.gl.drawArrays(this.gl.TRIANGLES,0,a)}antialias(e){let{passesSqrt:t,passes:r,spread:i,step:s,weight:n}=He.ANTIALIASING,o=new Float32Array(e.length*r),a=0;for(let r=0;r<t;r++)for(let n=0;n<t;n++){let t=r*s-(i-s)/2,l=n*s-(i-s)/2;for(let r=0;r<e.length;r+=2)o[a++]=e[r]+t,o[a++]=e[r+1]+l}return this.color={red:this.color.red*n,green:this.color.green*n,blue:this.color.blue*n,alpha:this.color.alpha*n},o}static getVertexShader(){return`\n\t\t\tprecision ${He.VERTEX_SHADER_PRECISION} float;\n\n\t\t\tuniform mat4 u_projectionMatrix;\n\t\t\tuniform mat4 u_viewMatrix;\n\t\t\tuniform lowp vec4 u_color;\n\n\t\t\tattribute highp vec4 a_position;\n\n\t\t\tvarying lowp vec4 v_color;\n\n\t\t\tvoid main() {\n\t\t\t\tvec4 viewPosition = u_viewMatrix * a_position;\n\n\t\t\t\tgl_Position = u_projectionMatrix * viewPosition;\n\t\t\t\tv_color = u_color;\n\t\t\t}\n\t\t`}static getFragmentShader(){return"\n\t\t\tvarying lowp vec4 v_color;\n\n\t\t\tvoid main() {\n\t\t\t\tgl_FragColor = v_color;\n\t\t\t}\n\t\t"}}const Qe=16*Float32Array.BYTES_PER_ELEMENT;class et extends Ke{constructor(e){super(e),this.vao=this.gl.createVertexArray(),this.positionBuffer=this.gl.createBuffer(),this.colorBuffer=this.gl.createBuffer(),this.matrixBuffer=this.gl.createBuffer()}init(){this.a_position=this.gl.getAttribLocation(this.program,"a_position"),this.a_color=this.gl.getAttribLocation(this.program,"a_color"),this.a_matrix=this.gl.getAttribLocation(this.program,"a_matrix"),this.u_viewMatrix=this.gl.getUniformLocation(this.program,"u_viewMatrix")}onContextChange(){this.gl.uniformMatrix4fv(this.u_viewMatrix,!1,this.inkGLContext.transform?this.inkGLContext.transform.value:He.IDENTITY_MATRIX)}onDeactivate(){this.gl.disableVertexAttribArray(this.a_position),this.gl.disableVertexAttribArray(this.a_color),this.gl.disableVertexAttribArray(this.a_matrix),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.bindVertexArray(null)}drawVertices(e,t,i,s=!0,n=!1,o=!1){i=i.premultiply(),Array.isArray(t)&&(t=new Float32Array(t));let a,l,h,d=1,c=t.length/2,p=this.inkGLContext.graphicsSpaceToFramebufferSpaceT;if(s&&!o){let{passesSqrt:e,passes:t,spread:s,step:n,weight:o}=He.ANTIALIASING,c=[i.red*o,i.green*o,i.blue*o,i.alpha*o];d=t,a=new Float32Array(4*d),l=new Float32Array(16*d);for(let e=0;e<d;++e)for(let t=0;t<4;t++)a[4*e+t]=c[t];for(let t=0;t<e;t++)for(let i=0;i<e;i++){let o=16*(e*t+i),a=o*Float32Array.BYTES_PER_ELEMENT;for(let e=0;e<16;e++)l[o+e]=p[e];let h=new Float32Array(l.buffer,a,16),d=t*n-(s-n)/2,c=i*n-(s-n)/2;r.mat4.translate(h,h,r.vec4.fromValues(d,c,0,1))}h=Ve.LIGHTER}else a=new Float32Array([i.red,i.green,i.blue,i.alpha]),l=p,h=o?Ve.MAX:Ve.SOURCE_OVER;this.activate(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,e),this.gl.bindVertexArray(this.vao),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.a_position),this.gl.vertexAttribPointer(this.a_position,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.colorBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,a,this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.a_color),this.gl.vertexAttribPointer(this.a_color,4,this.gl.FLOAT,!1,0,0),this.gl.vertexAttribDivisor(this.a_color,1),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.matrixBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,l,this.gl.STATIC_DRAW);for(let e=0;e<4;e++){let t=this.a_matrix+e,r=16*e;this.gl.enableVertexAttribArray(t),this.gl.vertexAttribPointer(t,4,this.gl.FLOAT,!1,Qe,r),this.gl.vertexAttribDivisor(t,1)}n&&(this.inkGLContext.blendMode=Ve.DIRECT_DESTINATION_OUT,this.gl.drawArraysInstanced(this.gl.TRIANGLES,0,c,d)),this.inkGLContext.blendMode=h,this.gl.drawArraysInstanced(this.gl.TRIANGLES,0,c,d)}static getVertexShader(){return"#version 300 es\n\t\t\tin vec4 a_position;\n\t\t\tin vec4 a_color;\n\t\t\tin mat4 a_matrix;\n\n\t\t\tuniform mat4 u_viewMatrix;\n\n\t\t\tout vec4 v_color;\n\n\t\t\tvoid main() {\n\t\t\t\tvec4 viewPosition = u_viewMatrix * a_position;\n\n\t\t\t\tgl_Position = a_matrix * viewPosition;\n\t\t\t\tv_color = a_color;\n\t\t\t}\n\t\t"}static getFragmentShader(){return"#version 300 es\n\t\t\tprecision highp float;\n\n\t\t\tin vec4 v_color;\n\n\t\t\tout vec4 outColor;\n\n\t\t\tvoid main() {\n\t\t\t\toutColor = v_color;\n\t\t\t}\n\t\t"}}class tt extends Ke{constructor(e){super(e),this.destBuffer=this.gl.createBuffer(),this.srcBuffer=this.gl.createBuffer()}init(){this.a_position=this.gl.getAttribLocation(this.program,"a_position"),this.a_srcPosition=this.gl.getAttribLocation(this.program,"a_srcPosition"),this.u_texture=this.gl.getUniformLocation(this.program,"u_texture"),this.u_projectionMatrix=this.gl.getUniformLocation(this.program,"u_projectionMatrix"),this.u_textureMatrix=this.gl.getUniformLocation(this.program,"u_textureMatrix")}onDeactivate(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}drawTexture(e,t,r,i,s){this.activate(),this.gl.disable(this.gl.DEPTH_TEST),this.gl.disable(this.gl.STENCIL_TEST),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.uniform1i(this.u_texture,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.destBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.a_position),this.gl.vertexAttribPointer(this.a_position,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.srcBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.a_srcPosition),this.gl.vertexAttribPointer(this.a_srcPosition,2,this.gl.FLOAT,!1,0,0),this.gl.uniformMatrix4fv(this.u_projectionMatrix,!1,i),this.gl.uniformMatrix4fv(this.u_textureMatrix,!1,s),this.inkGLContext.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}static getVertexShader(){return`\n\t\t\tprecision ${He.VERTEX_SHADER_PRECISION} float;\n\n\t\t\tuniform mat4 u_projectionMatrix;\n\t\t\tuniform mat4 u_textureMatrix;\n\t\t\tattribute highp vec4 a_position;\n\t\t\tattribute highp vec4 a_srcPosition;\n\t\t\tvarying highp vec2 v_textureCoordinate;\n\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = u_projectionMatrix * a_position;\n\t\t\t\tv_textureCoordinate = (u_textureMatrix * a_srcPosition).xy;\n\t\t\t}\n\t\t`}static getFragmentShader(){return`\n\t\t\tprecision ${He.FRAGMENT_SHADER_PRECISION} float;\n\n\t\t\tvarying vec2 v_textureCoordinate;\n\t\t\tuniform lowp sampler2D u_texture;\n\n\t\t\tvoid main() {\n\t\t\t\tgl_FragColor = texture2D(u_texture, v_textureCoordinate);\n\t\t\t}\n\t\t`}}class rt extends pe{constructor(e,t,r,i={},s={}){super(e),this.spacing=i.spacing||.15,this.scattering=i.scattering||0,this.rotationMode=i.rotationMode||rt.RotationMode.RANDOM;let n,o=i.blendMode||Ve.SOURCE_OVER;Object.defineProperty(this,"blendMode",{get:()=>o,set:e=>{if(!e)throw new Error("BrushGL blendMode is required");o=e}}),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((e=>e.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:e=>{n=e,Array.isArray(this.descriptor.shape)?this.descriptor.shape.forEach((t=>t.encoding=e)):this.descriptor.shape.encoding=e,this.descriptor.fill.encoding=e},enumerable:!0}),this.updateShape(t),this.updateFill(r,s)}async updateShape(e){Array.isArray(e)?e=e.map((e=>"string"==typeof e?ce.getInstance(e):e instanceof ce?e:new ce(e.name,e.value))):"string"==typeof e?e=ce.getInstance(e):e instanceof ce||(e=new ce(e.name,e.value)),this.descriptor.shape=e,this.ctx&&await this.configureShape()}async updateFill(e,t={}){if(this.randomizeFill=!("randomize"in t)||t.randomize,this.fillTextureSize=t.size,this.fillTextureOffset=t.offset||{x:0,y:0},Array.isArray(e))throw new Error("Mipmap is not compatible whith fill texture");"string"==typeof e?e=ce.getInstance(e):e instanceof ce||(e=new ce(e.name,e.value)),this.descriptor.fill=e,this.ctx&&await this.configureFill()}async configure(e){this.ctx=e,await this.configureShape(),await this.configureFill()}async configureShape(){this.shapeTexture||(this.shapeTexture=qe.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=qe.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 e;if(Array.isArray(this.shape)){let t=[];for(let e of this.shape){let r=await Be(e);t.push(r)}e=t}else e=await Be(this.shape);return e}async getFillBinary(){return await Be(this.fill)}toJSON(){return{type:"BrushGL",name:this.name,shape:Array.isArray(this.descriptor.shape)?this.descriptor.shape.map((e=>e.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(e){e.particleSettings.blendMode=Ve[e.particleSettings.blendMode],e.particleSettings.rotationMode=rt.RotationMode[e.particleSettings.rotationMode];let t=Array.isArray(e.shape)?e.shape.map((e=>ce.fromJSON(e))):ce.fromJSON(e.shape),r=ce.fromJSON(e.fill);return new rt(e.name,t,r,e.particleSettings,e.fillTextureSettings)}equals(e){return e==this&&e.shapeTexture==this.shapeTexture&&e.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(rt,"RotationMode",["NONE","RANDOM","TRAJECTORY"]);class it extends Ke{constructor(e){super(e),this.buffer=this.gl.createBuffer(),this.indexBuffer=this.gl.createBuffer()}init(){this.a_coordinates=this.gl.getAttribLocation(this.program,"a_coordinates"),this.a_xys=this.gl.getAttribLocation(this.program,"a_xys"),this.a_spriteRotation=this.gl.getAttribLocation(this.program,"a_spriteRotation"),this.a_spriteScaleAndOffset=this.gl.getAttribLocation(this.program,"a_spriteScaleAndOffset"),this.a_color=this.gl.getAttribLocation(this.program,"a_color"),this.a_velocity=this.gl.getAttribLocation(this.program,"a_velocity"),this.a_transformParams=this.gl.getAttribLocation(this.program,"a_transformParams"),this.u_projectionMatrix=this.gl.getUniformLocation(this.program,"u_projectionMatrix"),this.u_viewMatrix=this.gl.getUniformLocation(this.program,"u_viewMatrix"),this.u_fillTextureSize=this.gl.getUniformLocation(this.program,"u_fillTextureSize"),this.u_fillTextureOffset=this.gl.getUniformLocation(this.program,"u_fillTextureOffset"),this.u_shapeTexture=this.gl.getUniformLocation(this.program,"u_shapeTexture"),this.u_fillTexture=this.gl.getUniformLocation(this.program,"u_fillTexture")}setBrush(e){this.brush=e,this.brushChanged=!0}onActivate(){this.brushChanged=!0,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.buffer),this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,this.indexBuffer);let e=19*Float32Array.BYTES_PER_ELEMENT;this.gl.vertexAttribPointer(this.a_coordinates,2,this.gl.FLOAT,!1,e,0*Float32Array.BYTES_PER_ELEMENT),this.gl.vertexAttribPointer(this.a_xys,3,this.gl.FLOAT,!1,e,2*Float32Array.BYTES_PER_ELEMENT),this.gl.vertexAttribPointer(this.a_spriteRotation,1,this.gl.FLOAT,!1,e,5*Float32Array.BYTES_PER_ELEMENT),this.gl.vertexAttribPointer(this.a_spriteScaleAndOffset,4,this.gl.FLOAT,!1,e,6*Float32Array.BYTES_PER_ELEMENT),this.gl.vertexAttribPointer(this.a_color,4,this.gl.FLOAT,!1,e,10*Float32Array.BYTES_PER_ELEMENT),this.gl.vertexAttribPointer(this.a_velocity,2,this.gl.FLOAT,!1,e,14*Float32Array.BYTES_PER_ELEMENT),this.gl.vertexAttribPointer(this.a_transformParams,3,this.gl.FLOAT,!1,e,16*Float32Array.BYTES_PER_ELEMENT),this.gl.enableVertexAttribArray(this.a_coordinates),this.gl.enableVertexAttribArray(this.a_xys),this.gl.enableVertexAttribArray(this.a_spriteRotation),this.gl.enableVertexAttribArray(this.a_spriteScaleAndOffset),this.gl.enableVertexAttribArray(this.a_color),this.gl.enableVertexAttribArray(this.a_velocity),this.gl.enableVertexAttribArray(this.a_transformParams)}onContextChange(){this.gl.uniformMatrix4fv(this.u_projectionMatrix,!1,this.inkGLContext.graphicsSpaceToFramebufferSpaceT),this.gl.uniformMatrix4fv(this.u_viewMatrix,!1,this.inkGLContext.transform?this.inkGLContext.transform.value:He.IDENTITY_MATRIX)}onDeactivate(){this.gl.disableVertexAttribArray(this.a_coordinates),this.gl.disableVertexAttribArray(this.a_xys),this.gl.disableVertexAttribArray(this.a_spriteRotation),this.gl.disableVertexAttribArray(this.a_spriteScaleAndOffset),this.gl.disableVertexAttribArray(this.a_color),this.gl.disableVertexAttribArray(this.a_velocity),this.gl.disableVertexAttribArray(this.a_transformParams),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateTextures(){this.brushChanged&&(this.brushChanged=!1,this.gl.uniform2f(this.u_fillTextureOffset,this.brush.fillTextureOffset.x,this.brush.fillTextureOffset.y),this.gl.uniform2f(this.u_fillTextureSize,this.brush.fillTextureSize.width,this.brush.fillTextureSize.height),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.brush.shapeTexture.value),this.gl.uniform1i(this.u_shapeTexture,0),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.brush.fillTexture.value),this.gl.uniform1i(this.u_fillTexture,1))}drawSprites(e){let t;this.activate(),this.updateTextures();let r=Math.ceil(e.length/He.VERTEX_BATCH_SIZE);for(let i=0;i<r;i++){t=this.drawSpritesBatch(e,i).union(t)}return t}drawSpritesBatch(e,t){let r,i=t*He.VERTEX_BATCH_SIZE,s=i+He.VERTEX_BATCH_SIZE;s>e.length&&(s=i+e.length%He.VERTEX_BATCH_SIZE);let n=s-i,o=new Float32Array(76*n),a=new Uint16Array(6*n),l=this.brush.rotationMode==rt.RotationMode.TRAJECTORY?1:0,h=U.createInstance(e.layout);for(let t=i;t<s;t++){h.fill(t,e.points,e.layout,e.style);let s=76*(t-i);r=x.calculateBrushGLSegmentBounds(h,this.brush.scattering).union(r);let n=h.red/255*h.alpha,a=h.green/255*h.alpha,d=h.blue/255*h.alpha;0==h.dX&&0==h.dY&&(h.dX=2*this.inkGLContext.random()-1,h.dY=2*this.inkGLContext.random()-1);let c=this.brush.rotationMode==rt.RotationMode.RANDOM?2*this.inkGLContext.random()*Math.PI:0,p=(2*this.inkGLContext.random()-1)*this.brush.scattering;x.SQURE.forEach(((e,t)=>{let r=s+19*t;o[r]=e.x,o[r+1]=e.y,o[r+2]=h.x,o[r+3]=h.y,o[r+4]=h.size,o[r+5]=h.rotation,o[r+6]=h.scaleX,o[r+7]=h.scaleY,o[r+8]=h.offsetX,o[r+9]=h.offsetY,o[r+10]=n,o[r+11]=a,o[r+12]=d,o[r+13]=h.alpha,o[r+14]=h.dX,o[r+15]=h.dY,o[r+16]=l,o[r+17]=c,o[r+18]=p}))}let d=0;for(let e=0;e<a.length;e+=6)a[e]=d,a[e+1]=d+1,a[e+2]=d+2,a[e+3]=d+2,a[e+4]=d+1,a[e+5]=d+3,d+=4;return this.gl.bufferData(this.gl.ARRAY_BUFFER,o,this.gl.STATIC_DRAW),this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER,a,this.gl.STATIC_DRAW),this.inkGLContext.drawElements(this.gl.TRIANGLES,a.length,this.gl.UNSIGNED_SHORT,0),r}static getVertexShader(){return`\n\t\t\tprecision ${He.VERTEX_SHADER_PRECISION} float;\n\n\t\t\tuniform mat4 u_projectionMatrix;\n\t\t\tuniform mat4 u_viewMatrix;\n\t\t\tuniform vec2 u_fillTextureSize;\n\t\t\tuniform vec2 u_fillTextureOffset;\n\n\t\t\tattribute lowp vec4 a_color;\n\t\t\t/* (x,y) is the center. z is the offset by x, w is the offset by y */\n\t\t\tattribute highp vec2 a_coordinates;\n\t\t\t/* the velocity at that point. It is the derivative of the function */\n\t\t\tattribute vec2 a_velocity;\n\t\t\t/* 1-shape trajectory rotation coficient, 2-shape randrom rotation angle, 3-scattering value */\n\t\t\tattribute vec3 a_transformParams;\n\n\t\t\t/* sprite rotation angle */\n\t\t\tattribute highp float a_spriteRotation;\n\t\t\t/* sprite's: 1-scaleX, 2-scaleY, 3-offsetX, 4-offsetY */\n\t\t\tattribute highp vec4 a_spriteScaleAndOffset;\n\n\t\t\tvarying lowp vec4 v_color;\n\t\t\tattribute vec3 a_xys;\n\t\t\tvarying highp vec2 v_shapeTexturePosition;\n\t\t\tvarying highp vec2 v_fillTexturePosition;\n\n\t\t\tmat2 trajectoryRotate(vec2 vNormal, float value) {\n\t\t\t\tvec2 base = vec2(1.0, 0.0);\n\n\t\t\t\tvec2 vNormalR = mix(base, vNormal, value);\n\t\t\t\tvNormalR = normalize(vNormalR);\n\n\t\t\t\tfloat cosfi = dot(vNormalR, base);\n\t\t\t\tfloat sinfi = vNormalR.x * base.y - vNormalR.y * base.x;\n\n\t\t\t\treturn mat2(\n\t\t\t\t\tcosfi, -sinfi,\n\t\t\t\t\tsinfi, cosfi\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tmat2 angleRotate2(float fi) {\n\t\t\t\tfloat sinfi = sin(fi);\n\t\t\t\tfloat cosfi = cos(fi);\n\n\t\t\t\treturn mat2(\n\t\t\t\t\tcosfi, -sinfi,\n\t\t\t\t\tsinfi, cosfi\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tmat2 scale2(float sx, float sy) {\n\t\t\t\treturn mat2(sx, 0.0, 0.0, sy);\n\t\t\t}\n\n\t\t\tmat3 rotate2h(float fi) {\n\t\t\t\tfloat sinfi = sin(fi);\n\t\t\t\tfloat cosfi = cos(fi);\n\n\t\t\t\treturn mat3(\n\t\t\t\t\tcosfi, sinfi, 0.0,\n\t\t\t\t\t-sinfi, cosfi, 0.0,\n\t\t\t\t\t0.0, 0.0, 1.0\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tmat3 scale2h(float sx, float sy) {\n\t\t\t\treturn mat3(\n\t\t\t\t\tsx, 0.0, 0.0,\n\t\t\t\t\t0.0, sy, 0.0,\n\t\t\t\t\t0.0, 0.0, 1.0\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tmat3 translate2h(float tx, float ty) {\n\t\t\t\treturn mat3(\n\t\t\t\t\t1.0, 0.0, 0.0,\n\t\t\t\t\t0.0, 1.0, 0.0,\n\t\t\t\t\ttx, ty, 1.0\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tvec2 orthoOffset(vec2 vNormal, float value) {\n\t\t\t\tvec2 vno = vec2(vNormal.y * value, vNormal.x * value);\n\t\t\t\treturn vno;\n\t\t\t}\n\n\t\t\tvoid main() {\n\t\t\t\t// Calculate radius from size\n\t\t\t\tfloat halfSize = a_xys.z / 2.0;\n\n\t\t\t\tvec2 vNormal = normalize(a_velocity);\n\n\t\t\t\t// Because this applied to the texture, the y reversed because the texture coordinate system y is increasing downwards.\n\t\t\t\tvNormal.y = -vNormal.y;\n\n\t\t\t\tfloat spriteRotation = a_spriteRotation;\n\t\t\t\tvec4 spriteScaleAndOffset = a_spriteScaleAndOffset;\n\t\t\t\tspriteScaleAndOffset.y = -spriteScaleAndOffset.y;\n\t\t\t\tspriteScaleAndOffset.w = -spriteScaleAndOffset.w;\n\n\t\t\t\tmat2 productRotateMatrix = angleRotate2(a_transformParams.y) * trajectoryRotate(vNormal, a_transformParams.x);\n\t\t\t\tvec2 scatterOffset = orthoOffset(vNormal, a_transformParams.z * halfSize);\n\t\t\t\tvec2 transformedCoordinates = productRotateMatrix * a_coordinates;\n\n\t\t\t\tvec3 coordinatesH = vec3(transformedCoordinates.x, transformedCoordinates.y, 1.0);\n\t\t\t\tcoordinatesH = rotate2h(spriteRotation) * translate2h(spriteScaleAndOffset.z, spriteScaleAndOffset.w) * scale2h(spriteScaleAndOffset.x * halfSize, spriteScaleAndOffset.y * halfSize) * coordinatesH;\n\t\t\t\tvec2 coordinates = coordinatesH.xy;\n\n\t\t\t\tvec2 offset = coordinates + scatterOffset;\n\t\t\t\tvec4 position = vec4(a_xys.x + offset.x, a_xys.y + offset.y, 0.0, 1.0);\n\n\t\t\t\tv_color = a_color;\n\n\t\t\t\tvec4 viewPosition = u_viewMatrix * position;\n\t\t\t\tgl_Position = u_projectionMatrix * viewPosition;\n\t\t\t\tv_fillTexturePosition = position.xy / u_fillTextureSize + u_fillTextureOffset;\n\t\t\t\tv_shapeTexturePosition = (a_coordinates + 1.0) * 0.5; /* [-1;1] -> [0;1] */\n\t\t\t}\n\t\t`}static getFragmentShader(e){return`\n\t\t\tuniform lowp sampler2D u_shapeTexture;\n\t\t\tuniform lowp sampler2D u_fillTexture;\n\n\t\t\t/* lowp seems to lead to an overflow on PowerVR SGX540, so use mediump instead :)*/\n\t\t\tvarying mediump vec4 v_color;\n\t\t\tvarying highp vec2 v_shapeTexturePosition;\n\t\t\tvarying highp vec2 v_fillTexturePosition;\n\n\t\t\tvoid main() {\n\t\t\t\tlowp vec4 c = v_color * texture2D(u_shapeTexture, v_shapeTexturePosition) * texture2D(u_fillTexture, v_fillTexturePosition);\n\n\t\t\t\tgl_FragColor = ${e?"c":"vec4(c.x / c.w, c.y / c.w, c.z / c.w, c.w * 255.0)"};\n\t\t\t}\n\t\t`}}class st{constructor(e,t){let r=e.getContext("webgl2",t)||e.getContext("webgl",t);if(this.debug){let e=new Proxy(r,{get:function(e,t,r){let i;return i="function"==typeof e[t]?Reflect.get(...arguments):e[t],"getError"!=t&&He.logGLError(e,t),i}});Object.getOwnPropertyNames(r.constructor.prototype).forEach((t=>{let i=r[t];"function"==typeof i&&(e[t]=i.bind(r))})),r=e}this.gl=r,this.glVersion=r.drawArraysInstanced?2:1,this.inkGLContext=new He(r);const i=r.drawArraysInstanced?et:Je;this.simpleProgram=new i(this.inkGLContext),this.textureProgram=new tt(this.inkGLContext),this.spriteProgram=new it(this.inkGLContext),this.inkGLContext.programs=[this.simpleProgram,this.textureProgram,this.spriteProgram],this.currentTarget=null,this.inkGLContext.init(new x(0,0,0,0),new x(0,0,0,0))}createLayer(e,t){return new We(this.inkGLContext,e,t)}drawLayerWithTransform(e,t,r){if(!this.currentTarget)return;let i=e.graphicsBounds.toQuad(),s=e.graphicsBounds.toQuad(t);this.drawLayer(e,i,s,r)}drawLayer(e,t,i,s){if(!this.currentTarget)return;if(!e.useTextureStorage)return;let n=r.mat4.create(),o=r.mat4.create(),a=this.currentTarget;a.flipY?r.mat4.ortho(o,0,a.width,a.height,0,1,-1):r.mat4.ortho(o,0,a.width,0,a.height,1,-1),e.flipY?r.mat4.ortho(n,-e.width,e.width,2*e.height,0,0,1):r.mat4.ortho(n,-e.width,e.width,-e.height,e.height,0,1),this.inkGLContext.blendMode=s,this.textureProgram.drawTexture(e.texture,i,t,o,n)}setTarget(e,t){if(e&&!(e instanceof We))throw new TypeError("layer must be unset or instanceof InkLayer");if(t&&!(t instanceof x))throw new TypeError("clipRect must be unset or instanceof RectGL");if(e){this.currentTarget=e;let r=new x(0,0,e.storageWidth,e.storageHeight),i=new x(0,0,e.width,e.height);this.inkGLContext.resize(r,i),this.inkGLContext.setUniforms(e.flipY),t?this.setTargetClipRect(t):this.disableTargetClipRect(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,e.framebuffer)}}clearColor(e){this.inkGLContext.clearColorBuffer(e)}setTargetClipRect(e){if(e=e.floor().intersect(this.currentTarget.graphicsBounds),this.currentTarget.flipY)e=new x(e.x,this.currentTarget.storageHeight-e.top,e.width,e.height);else{let t=this.currentTarget.scaleFactor;e=new x(e.x*t,e.y*t,e.width*t,e.height*t)}this.inkGLContext.clipRect=e,this.inkGLContext.scissors(e)}disableTargetClipRect(){let e=this.inkGLContext;e.scissors(null),e.clipRect=e.graphicsBox}drawStroke(e,t,r){return this.currentTarget?0==t.length?null:(this.inkGLContext.blendMaxFallback&&e.blendMode==Ve.MAX&&this.inkGLContext.enableStencilBufferForBlending(this.currentTarget),this.inkGLContext.transform=this.currentTarget.matrix,e instanceof rt?this.drawGL(e,t,r):this.draw2D(e,t,r)):null}drawGL(e,t,r){let i;r&&(i=this.inkGLContext.scatterMethodRandomSeed,this.inkGLContext.scatterMethodRandomSeed=r.randomSeed),this.spriteProgram.setBrush(e),this.inkGLContext.blendMode=e.blendMode;let s=this.spriteProgram.drawSprites(t);return r&&(r.randomSeed=this.inkGLContext.scatterMethodRandomSeed,this.inkGLContext.scatterMethodRandomSeed=i),this.clipDirtyArea(s)}draw2D(e,t,r){return this.fill(t,r,!0,t.segment)}fill(e,t,r=!0,i=!1){let s=this.clipDirtyArea(e.bounds.toGLRect());if(s){let n=e.vertices;n.length>0?this.simpleProgram.drawVertices(this.currentTarget.framebuffer,n,t,r,i):s=void 0}return s}clipDirtyArea(e){let t=e,r=this.inkGLContext.clipRect;return this.inkGLContext.transform&&(t=t.transform(this.inkGLContext.transform)),t=r.intersect(t),t&&(t=t.ceil(),1==this.glVersion&&(t=x.ofEdges(t.left-1,t.bottom-1,t.right+1,t.top+1))),t}readPixels(e){let t=this.currentTarget;if(e){if(!(e instanceof x))throw new TypeError("box must be instance of RectGL")}else e=t.graphicsBounds;t.flipY&&(e=new x(e.x,t.height-e.y-e.height,e.width,e.height)),this.setTarget(t);let r=new Uint8Array(e.width*e.height*4);return this.gl.readPixels(parseInt(e.x*t.scaleFactor),parseInt(e.y*t.scaleFactor),parseInt(e.width*t.scaleFactor),parseInt(e.height*t.scaleFactor),this.gl.RGBA,this.gl.UNSIGNED_BYTE,r),r}writePixels(e,t){if(e&&!(e instanceof x))throw new TypeError("rect must be instance of RectGL");let r=this.currentTarget;if(e||(e=new x(0,0,r.width,r.height)),!r.useTextureStorage)throw new Error("writePixels layer without texture is not supported!");{r.flipY&&(e=new x(e.x,r.height-e.y-e.height,e.width,e.height));let i=new x(e.x*r.scaleFactor,e.y*r.scaleFactor,e.width*r.scaleFactor,e.height*r.scaleFactor);this.gl.finish(),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,r.texture),this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,parseInt(i.x),parseInt(i.y),parseInt(i.width),parseInt(i.height),this.gl.RGBA,this.gl.UNSIGNED_BYTE,t)}}}class nt extends Array{static get[Symbol.species](){return Array}constructor(...e){if(super(...e),e.some((e=>!(e instanceof Le))))throw new Error("Expected data item type is Polygon");Object.defineProperty(this,"bounds",{get:()=>{let e;return this.length>0&&(this.forEach((t=>e=t.bounds.union(e))),e=e.ceil()),e},enumerable:!0}),Object.defineProperty(this,"vertices",{get:()=>this.triangulate(),enumerable:!0})}clone(){return new this.constructor(...this.map((e=>e.clone())))}push(...e){if(e.some((e=>!(e instanceof Le))))throw new Error("Expected data item type is Polygon");super.push(...e)}triangulate(){return Float32Array.createSharedInstance().concat(...this.map((e=>e.vertices)))}transform(e){this.forEach((t=>t.transform(e)))}toJSON(){return{type:"PolygonArray",polygons:this.map((e=>e.toJSON()))}}static fromJSON(e){if("PolygonArray"!=e.type)throw new Error(`PolygonArray deserialization failed. JSON type is ${e.type}, expected PolygonArray.`);return new nt(...e.polygons.map((e=>Le.fromJSON(e))))}static fromPathsData(e){return new nt(...e.map((e=>Le.createInstance(e))))}}Le.toPolygonArray=nt.fromPathsData;let ot={palettes:{}};const at=["AliceBlue","#F0F8FF","AntiqueWhite","#FAEBD7","Aqua","#00FFFF","Aquamarine","#7FFFD4","Azure","#F0FFFF","Beige","#F5F5DC","Bisque","#FFE4C4","Black","#000000","BlanchedAlmond","#FFEBCD","Blue","#0000FF","BlueViolet","#8A2BE2","Brown","#A52A2A","BurlyWood","#DEB887","CadetBlue","#5F9EA0","Chartreuse","#7FFF00","Chocolate","#D2691E","Coral","#FF7F50","CornflowerBlue","#6495ED","Cornsilk","#FFF8DC","Crimson","#DC143C","Cyan","#00FFFF","DarkBlue","#00008B","DarkCyan","#008B8B","DarkGoldenRod","#B8860B","DarkGray","#A9A9A9","DarkGreen","#006400","DarkKhaki","#BDB76B","DarkMagenta","#8B008B","DarkOliveGreen","#556B2F","DarkOrange","#FF8C00","DarkOrchid","#9932CC","DarkRed","#8B0000","DarkSalmon","#E9967A","DarkSeaGreen","#8FBC8F","DarkSlateBlue","#483D8B","DarkSlateGray","#2F4F4F","DarkTurquoise","#00CED1","DarkViolet","#9400D3","DeepPink","#FF1493","DeepSkyBlue","#00BFFF","DimGray","#696969","DodgerBlue","#1E90FF","FireBrick","#B22222","FloralWhite","#FFFAF0","ForestGreen","#228B22","Fuchsia","#FF00FF","Gainsboro","#DCDCDC","GhostWhite","#F8F8FF","Gold","#FFD700","GoldenRod","#DAA520","Gray","#808080","Green","#008000","GreenYellow","#ADFF2F","HoneyDew","#F0FFF0","HotPink","#FF69B4","IndianRed","#CD5C5C","Indigo","#4B0082","Ivory","#FFFFF0","Khaki","#F0E68C","Lavender","#E6E6FA","LavenderBlush","#FFF0F5","LawnGreen","#7CFC00","LemonChiffon","#FFFACD","LightBlue","#ADD8E6","LightCoral","#F08080","LightCyan","#E0FFFF","LightGoldenRodYellow","#FAFAD2","LightGray","#D3D3D3","LightGreen","#90EE90","LightPink","#FFB6C1","LightSalmon","#FFA07A","LightSeaGreen","#20B2AA","LightSkyBlue","#87CEFA","LightSlateGray","#778899","LightSteelBlue","#B0C4DE","LightYellow","#FFFFE0","Lime","#00FF00","LimeGreen","#32CD32","Linen","#FAF0E6","Magenta","#FF00FF","Maroon","#800000","MediumAquaMarine","#66CDAA","MediumBlue","#0000CD","MediumOrchid","#BA55D3","MediumPurple","#9370DB","MediumSeaGreen","#3CB371","MediumSlateBlue","#7B68EE","MediumSpringGreen","#00FA9A","MediumTurquoise","#48D1CC","MediumVioletRed","#C71585","MidnightBlue","#191970","MintCream","#F5FFFA","MistyRose","#FFE4E1","Moccasin","#FFE4B5","NavajoWhite","#FFDEAD","Navy","#000080","OldLace","#FDF5E6","Olive","#808000","OliveDrab","#6B8E23","Orange","#FFA500","OrangeRed","#FF4500","Orchid","#DA70D6","PaleGoldenRod","#EEE8AA","PaleGreen","#98FB98","PaleTurquoise","#AFEEEE","PaleVioletRed","#DB7093","PapayaWhip","#FFEFD5","PeachPuff","#FFDAB9","Peru","#CD853F","Pink","#FFC0CB","Plum","#DDA0DD","PowderBlue","#B0E0E6","Purple","#800080","RebeccaPurple","#663399","Red","#FF0000","RosyBrown","#BC8F8F","RoyalBlue","#4169E1","SaddleBrown","#8B4513","Salmon","#FA8072","SandyBrown","#F4A460","SeaGreen","#2E8B57","SeaShell","#FFF5EE","Sienna","#A0522D","Silver","#C0C0C0","SkyBlue","#87CEEB","SlateBlue","#6A5ACD","SlateGray","#708090","Snow","#FFFAFA","SpringGreen","#00FF7F","SteelBlue","#4682B4","Tan","#D2B48C","Teal","#008080","Thistle","#D8BFD8","Tomato","#FF6347","Turquoise","#40E0D0","Violet","#EE82EE","Wheat","#F5DEB3","White","#FFFFFF","WhiteSmoke","#F5F5F5","Yellow","#FFFF00","YellowGreen","#9ACD32"],lt={red:["LightSalmon","Salmon","DarkSalmon","LightCoral","IndianRed","Crimson","FireBrick","Red","DarkRed"],orange:["Coral","Tomato","OrangeRed","Gold","Orange","DarkOrange"],yellow:["LightYellow","LemonChiffon","LightGoldenRodYellow","PapayaWhip","Moccasin","PeachPuff","PaleGoldenRod","Khaki","DarkKhaki","Yellow"],green:["LawnGreen","Chartreuse","LimeGreen","Lime","ForestGreen","Green","DarkGreen","GreenYellow","YellowGreen","SpringGreen","MediumSpringGreen","LightGreen","PaleGreen","DarkSeaGreen","MediumSeaGreen","SeaGreen","Olive","DarkOliveGreen","OliveDrab"],cyan:["LightCyan","Cyan","Aqua","Aquamarine","MediumAquaMarine","PaleTurquoise","Turquoise","MediumTurquoise","DarkTurquoise","LightSeaGreen","CadetBlue","DarkCyan","Teal"],blue:["PowderBlue","LightBlue","LightSkyBlue","SkyBlue","DeepSkyBlue","LightSteelBlue","DodgerBlue","CornflowerBlue","SteelBlue","RoyalBlue","Blue","MediumBlue","DarkBlue","Navy","MidnightBlue","MediumSlateBlue","SlateBlue","DarkSlateBlue"],purple:["Lavender","Thistle","Plum","Violet","Orchid","Fuchsia","Magenta","MediumOrchid","MediumPurple","BlueViolet","DarkViolet","DarkOrchid","DarkMagenta","Purple","RebeccaPurple","Indigo"],pink:["Pink","LightPink","HotPink","DeepPink","PaleVioletRed","MediumVioletRed"],white:["White","Snow","HoneyDew","MintCream","Azure","AliceBlue","GhostWhite","WhiteSmoke","SeaShell","Beige","OldLace","FloralWhite","Ivory","AntiqueWhite","Linen","LavenderBlush","MistyRose"],gray:["Gainsboro","LightGray","Silver","DarkGray","Gray","DimGray","LightSlateGray","SlateGray","DarkSlateGray","Black"],brown:["Cornsilk","BlanchedAlmond","Bisque","NavajoWhite","Wheat","BurlyWood","Tan","RosyBrown","SandyBrown","GoldenRod","Peru","DarkGoldenRod","Chocolate","SaddleBrown","Sienna","Brown","Maroon"]};let ht={};function dt(e,t){return ht[e]||(ht[e]=ve.fromColor(t)),ht[e]}for(let e=0;e<at.length;e+=2){let t=M.getEnumValueName(at[e]);Object.defineProperty(ot,t,{get:()=>dt(t,at[e+1]),enumerable:!0})}for(let e in lt){let t=lt[e];ot.palettes[e]={scale:t};for(let r=0;r<t.length;r++){let i=M.getEnumValueName(t[r]);Object.defineProperty(ot.palettes[e],i,{get:()=>ot[i],enumerable:!0})}}class ct{constructor(e){Object.defineProperty(this,"ctx",{value:e,enumerable:!0})}clearCanvas(){this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height)}setTransform(e){this.ctx.setTransform(e.a,e.b,e.c,e.d,e.tx,e.ty)}drawRect(e,t=ot.GRAY.toRGBA(.3)){this.ctx.strokeStyle=t.toString(),this.ctx.strokeRect(e.left,e.top,e.width,e.height)}fillRect(e,t=ot.GRAY.toRGBA(.3)){this.ctx.fillStyle=t.toString(),this.ctx.fillRect(e.left,e.top,e.width,e.height)}drawPoint(e,t=5,r=ot.BLACK){this.ctx.beginPath(),this.ctx.arc(e.x,e.y,t,0,2*Math.PI),this.renderStyle({type:"stroke",style:r})}fillPoint(e,t=5,r=ot.BLACK){this.ctx.beginPath(),this.ctx.arc(e.x,e.y,t,0,2*Math.PI),this.renderStyle({type:"fill",style:r})}drawEllipse(e,t,r,i=ot.BLACK){this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,t,r,0,0,2*Math.PI),this.renderStyle({type:"stroke",style:i})}fillEllipse(e,t,r,i=ot.BLACK){this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,t,r,0,0,2*Math.PI),this.renderStyle({type:"fill",style:i})}drawShape(e,t=ot.DARK_MAGENTA.toRGBA(.5)){this.renderShape(e,{type:"stroke",style:t})}fillShape(e,t=ot.ORANGE.toRGBA(.6)){this.renderShape(e,{type:"fill",style:t})}renderShape(e,t={}){if(e instanceof Ae)this.ctx.beginPath(),this.renderPath(e);else if(e instanceof Le)this.renderPolygon(e);else{if(!(e instanceof nt))throw new Error("Unexpected shape type found");this.ctx.beginPath();for(let t of e)this.renderPolygon(t,{segment:!0})}this.renderStyle(t)}renderPolygon(e,t={}){t.segment||this.ctx.beginPath(),this.renderPath(e.shape),e.holes.forEach((t=>this.renderPath(t,{holesDirection:e.holesDirection}))),t.segment||this.renderStyle(t)}renderPath(e,t={}){if(!t.holesDirection||t.holesDirection==Le.PointsDirection.CLOCKWISE){this.ctx.moveTo(e.getPointX(0),e.getPointY(0));for(let t=1;t<e.length;t++)this.ctx.lineTo(e.getPointX(t),e.getPointY(t))}else{this.ctx.moveTo(e.getPointX(e.length-1),e.getPointY(e.length-1));for(let t=e.length-2;t>=0;t--)this.ctx.lineTo(e.getPointX(t),e.getPointY(t))}this.ctx.closePath(),this.renderStyle(t)}renderStyle(e){if(e.type){if("fill"!=e.type&&"stroke"!=e.type)throw new Error("Option type should be oneof(stroke, fill)");e.style&&(this.ctx[`${e.type}Style`]=e.style instanceof ve?e.style.toString():e.style),this.ctx[e.type]()}}}class pt extends ct{constructor(e){super(e.getContext("2d"))}clear(){let e=this.ctx.canvas.toRect().transform(this.ctx.getTransform().invert());this.ctx.clearRect(e.left,e.top,e.width,e.height),this.clearCanvas()}refresh(){if(this.suppressRefresh)return;let e=[];pt.allocateSegments(e,this.data,0),this.clear(),this.drawRange(e)}drawRange(e){e.forEach((e=>this.drawRect(e.bounds,ot.MAGENTA)))}static allocateSegments(e,t,r){if(t&&(t.bounds&&e.push(t),t.children))if(10!==r)for(let i=0;i<t.children.length;i++)pt.allocateSegments(e,t.children[i],r+1);else console.warn("depth 10")}static getInstance(e,t){if(!e)return;let r=new pt(e);return Object.defineProperty(r,"data",{get:()=>t.data,enumerable:!0}),r}}class ut extends f.default{constructor(...e){let t;super(...e),"undefined"!=typeof document&&("loading"==document.readyState?addEventListener("DOMContentLoaded",(e=>t=pt.getInstance(document.getElementById("rbush"),this))):t=pt.getInstance(document.getElementById("rbush"),this)),Object.defineProperty(this,"canvas",{get:()=>this.debug?t:null,enumerable:!0})}toBBox(e){return{minX:e.bounds.left,minY:e.bounds.top,maxX:e.bounds.right,maxY:e.bounds.bottom}}compareMinX(e,t){return e.bounds.x-t.bounds.x}compareMinY(e,t){return e.bounds.y-t.bounds.y}search(e){return super.search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom})}find(e,t=this.data,r=0,i=[]){if(t){if(t.stroke){let r=!0;Object.keys(e).forEach((i=>{r=r&&t[i]==e[i]})),r&&i.push(t)}if(t.children){if(6!==r){for(let s=0;s<t.children.length;s++)this.find(e,t.children[s]||null,r+1,i);return i}console.warn("depth 6")}}}load(e){Array.isArray(e)||(e=[e]),0!=e.length&&(super.load(e),this.canvas&&this.canvas.refresh())}unload(e){Array.isArray(e)||(e=[e]),e.forEach((e=>this.remove(e))),this.canvas&&this.canvas.refresh()}}let ft=m?m.default||globalThis.JSZip:{},mt=new TextEncoder,gt={fourCCLength:4,versionLength:3,chunkDescriptorLength:4+Uint32Array.BYTES_PER_ELEMENT,fourCC:{RIFF:mt.encode("RIFF"),LIST:mt.encode("LIST"),LIST_ITEM:mt.encode("LI "),HEAD:mt.encode("HEAD"),META:mt.encode("META"),DATA:mt.encode("DATA"),TXT:mt.encode("TEXT"),JSON:mt.encode("JSON")}};Object.defineEnum(gt,"ContentType",["BINARY","PROTO","JSON","TEXT","LIST"]),Object.defineEnum(gt,"CompressionType",["NONE","ZIP","LZMA"]);class yt{constructor(e,t=new Uint8Array([0,0,0])){this.textEncoder=new TextEncoder,Object.defineProperty(this,"format",{get:()=>e,set:t=>{if(!t)throw new Error("format is expected");if("string"==typeof t&&(t=this.textEncoder.encode(t)),!(t instanceof Uint8Array))throw new Error("format expected type is Uint8Array");if(t.length!=gt.fourCCLength)throw new Error(`format expected length is ${gt.fourCCLength}`);e=t}}),Object.defineProperty(this,"version",{get:()=>t,set:e=>{if(e){if("string"==typeof e&&(e=new Uint8Array(e.split("."))),!(e instanceof Uint8Array))throw new Error("version expected type is Uint8Array");if(e.length!=gt.versionLength)throw new Error(`version expected length is ${gt.versionLength}`)}t=e}}),Object.defineProperty(this,"length",{get:()=>this.descriptors.length}),this.format=e,this.version=t,this.reset()}add(e,t={}){(t=Object.assign({},t,{data:e})).data&&(this.validateChunkDescriptor(t),Object.equals(t.fourCC,gt.fourCC.META)?this.descriptors.unshift(t):this.descriptors.push(t))}validateChunkDescriptor(e){if(e.fourCC||(e.fourCC=gt.fourCC.DATA),e.version||(e.version=new Uint8Array([0,0,0])),!e.contentType){if(!(e.data instanceof ArrayBuffer||ArrayBuffer.isTypedArray(e.data)))throw new Error("descriptor contentType auto detect failed - should be provided");e.contentType=gt.ContentType.BINARY}if(Array.isArray(e.data)&&(e.list=!0),e.compressionType||(e.compressionType=gt.CompressionType.NONE),"string"==typeof e.fourCC&&(e.fourCC=this.textEncoder.encode(e.fourCC)),"string"==typeof e.version&&(e.version=new Uint8Array(e.version.split("."))),!(e.fourCC instanceof Uint8Array))throw new Error(`Invalid fourCC type - ${e.fourCC}, expected string or Uint8Array`);if(e.fourCC.length!=gt.fourCCLength)throw new Error(`Invalid fourCC: [${e.fourCC}]`);if(!(e.version instanceof Uint8Array))throw new Error(`Invalid chunk version - ${e.version}, expected string or Uint8Array`);if(e.version.length!=gt.versionLength)throw new Error(`Invalid version: [${e.version}]`);if(Object.equals(e.fourCC,gt.fourCC.RIFF))throw new Error("RIFF fourCC is reserved");if(Object.equals(e.fourCC,gt.fourCC.META)){if(e.contentType==gt.ContentType.BINARY)throw new Error("Binary meta is not allowed");if(e.list)throw new Error("Multi-value meta is not allowed");if(this.descriptors.some((e=>Object.equals(e.fourCC,gt.fourCC.META))))throw new Error("Meta chunk is found. More than 1 meta chunk is not allowed.")}e.list&&e.data.forEach(((t,r)=>{let i=Object.assign({},e,{data:t});i.fourCC=gt.fourCC.LIST_ITEM,i.list=Array.isArray(t),e.data[r]=i,this.validateChunkDescriptor(i)}))}async encode(){if(0==this.descriptors.length)throw new Error("Chunks not found. Build process failed.");let e=await this.build();return this.reset(),e}async build(){if(0==this.descriptors.length)throw new Error("RIFF build failed. Chunks not found.");let e=0,t=[],r=0;for(let e of this.descriptors){let i=await this.buildChunk(e);t.push(i),r+=i.length}let i=this.buildHeadChunk(t);r+=i.length,t.unshift(i);let s=gt.fourCCLength+r,n=gt.fourCC.RIFF.length+Uint32Array.BYTES_PER_ELEMENT+s,o=new ArrayBuffer(n);this.content=new Uint8Array(o),this.contentView=new DataView(o),this.content.set(gt.fourCC.RIFF,e),e+=gt.fourCC.RIFF.length,this.contentView.setUint32(e,s,!0),e+=Uint32Array.BYTES_PER_ELEMENT,this.content.set(this.format,e),e+=this.format.length;for(let r of t)this.appendChunk(r,e),e+=r.length;return this.content}async buildChunk(e){let t=e.data;if(e.list)t=await Promise.all(t.map((async e=>await this.buildChunk(e))));else switch(e.contentType==gt.ContentType.JSON&&(t=JSON.stringify(t)),e.compressionType){case gt.CompressionType.NONE:e.contentType!=gt.ContentType.JSON&&e.contentType!=gt.ContentType.TEXT||(t=this.textEncoder.encode(t));break;case gt.CompressionType.ZIP:{let e=new ft;e.file("data",t),t=await e.generateAsync({type:"uint8array",compression:"DEFLATE",compressionOptions:{level:9}});break}case gt.CompressionType.LZMA:throw new Error("LZMA compression is not supported yet");default:throw new Error(`Invalid compression type: ${e.compressionType}`)}let r=0,i=0;return e.list?(i=t.map((e=>e.length)).reduce(((e,t)=>e+t),0),r=i,i+=gt.chunkDescriptorLength,i+=e.fourCC.length):(r=t.length,i+=r,i+=r%2,i+=gt.chunkDescriptorLength),this.debug&&console.log("buildChunk",this.readFourCC(e.fourCC),r,i,e.data),Object.assign({},e,{data:t,size:r,length:i})}buildHeadChunk(e){let t=this.version.length+1+e.length*gt.chunkDescriptorLength,r=t%2,i=gt.fourCCLength+Uint32Array.BYTES_PER_ELEMENT+t+r,s=new Uint8Array(t+r),n=this.version.length+1;return s.set(this.version,0),e.forEach(((e,t)=>{let r=new Uint8Array(8);r.set(e.version,0),r.set([e.contentType.value],3),r.set([e.compressionType.value],4),s.set(r,n+t*gt.chunkDescriptorLength)})),{fourCC:gt.fourCC.HEAD,data:s,size:t,length:i}}appendChunk(e,t){if(this.debug&&console.log("appendChunk",this.readFourCC(e.fourCC),e.size,e.length),e.list&&(this.content.set(gt.fourCC.LIST,t),t+=gt.fourCCLength,this.contentView.setUint32(t,e.size+e.fourCC.length,!0),t+=Uint32Array.BYTES_PER_ELEMENT),this.content.set(e.fourCC,t),t+=e.fourCC.length,e.list)for(let r of e.data)this.appendChunk(r,t),t+=r.length;else this.contentView.setUint32(t,e.size,!0),t+=Uint32Array.BYTES_PER_ELEMENT,this.content.set(e.data,t)}readFourCC(e){return this.textDecoder||(this.textDecoder=new TextDecoder),this.textDecoder.decode(e)}reset(){this.descriptors=[],this.content=null,this.contentView=null}}const bt={contentType:gt.ContentType.BINARY,compressionType:gt.CompressionType.NONE};class Et extends Array{}class Pt{constructor(){this.textDecoder=new TextDecoder}async decode(e,t){"undefined"!=typeof Buffer&&e instanceof Buffer&&(e=new Uint8Array(e)),t instanceof Uint8Array&&(t=this.textDecoder.decode(t));let r=0,i=r+gt.fourCC.RIFF.length;if(this.content=e,this.contentView=new DataView(e.buffer),this.descriptor={},this.onChunkDecoded||(this.descriptor.chunks=[],this.descriptor.asProps=function(){let e={};for(let t of this.chunks){let r=t.fourCC.toLowerCase();if(e[r])if(e[r]instanceof Et)e[r].push(t.value);else{let i=new Et;i.push(e[r]),i.push(t.value),e[r]=i}else e[r]=t.value}return e}),!Object.equals(this.content.subarray(r,i),gt.fourCC.RIFF))throw new Error("Invalid RIFF fourCC");r=i,i=r+Uint32Array.BYTES_PER_ELEMENT;let s=this.contentView.getUint32(r,!0)+i;if(s%2!=0)throw new Error("Invalid RIFF file size");if(s!=this.content.length)throw new Error("Incomplete RIFF file");r=i,i=r+gt.fourCCLength,this.descriptor.format=this.textDecoder.decode(this.content.subarray(r,i)),r=i;let n=[],o=0;for(;r<s;){let e=this.content.subarray(r,r+gt.fourCCLength);if(Object.equals(e,gt.fourCC.HEAD)){let e=this.decodeHead(r);r+=e.length,n=e.descriptors}else{let i;if(Object.equals(e,gt.fourCC.LIST)){let e=this.content.subarray(r+gt.chunkDescriptorLength,r+gt.chunkDescriptorLength+gt.fourCCLength);i=this.textDecoder.decode(e)}else i=this.textDecoder.decode(e);if(t&&i!=t){r+=this.readChunkDimensionality(r).length}else{let s=this.readChunk(r);r+=s.length;let a,l=n[o]||bt;if(a=Object.equals(e,gt.fourCC.LIST)?await this.decodeList(s.data,l):await this.decodeChunk(s.data,l),t)return a;this.onChunkDecoded?await this.onChunkDecoded(i,a,this.descriptor):this.descriptor.chunks.push({fourCC:i,value:a})}o++}}return this.onChunkDecoded?void 0:this.descriptor}decodeHead(e){let t=this.readChunk(e),r={size:t.size,length:t.length,descriptors:[]},i=`${t.data[0]}.${t.data[1]}.${t.data[2]}`;"0.0.0"!=i&&(this.descriptor.version=i);let s=(t.size+t.size%2-4)/8;for(let e=0;e<s;e++){let s=4+e*gt.chunkDescriptorLength,n=t.data.slice(s,s+8);i=`${n[0]}.${n[1]}.${n[2]}`;let o={contentType:gt.ContentType[n[3]],compressionType:gt.CompressionType[n[4]]};"0.0.0"!=i&&(o.version=i),r.descriptors.push(o)}return r}readChunk(e){let t,r=this.content.subarray(e,e+gt.fourCCLength),i=this.readChunkDimensionality(e);if(this.debug&&console.log("readChunk",this.textDecoder.decode(r),i.size,i.length),i.size>0){let s=i.byteOffset+i.size;if(t=this.content.subarray(i.byteOffset,s),t=new Uint8Array(t,t.byteOffset,t.length),Object.equals(r,gt.fourCC.LIST)){let r=[],s=0;for(e+=gt.chunkDescriptorLength,e+=gt.fourCCLength;s<i.size-gt.fourCCLength;){let t=this.readChunk(e);s+=t.length,e+=t.length,r.push(t.data)}t=r}}else t=new Uint8Array(0);return{data:t,size:i.size,length:i.length}}readChunkDimensionality(e){e+=gt.fourCCLength;let t=this.contentView.getUint32(e,!0),r=gt.fourCCLength+Uint32Array.BYTES_PER_ELEMENT+t,i=r%2;return{byteOffset:e+Uint32Array.BYTES_PER_ELEMENT,size:t,length:r+i}}async decodeList(e,t){return await Promise.all(e.map((async e=>Array.isArray(e)?await this.decodeList(e,t):await this.decodeChunk(e,t))))}async decodeChunk(e,t){let r;switch(t.compressionType){case gt.CompressionType.NONE:r=t.contentType==gt.ContentType.JSON||t.contentType==gt.ContentType.TEXT?this.textDecoder.decode(e):e;break;case gt.CompressionType.ZIP:{let i=await ft.loadAsync(e);r=t.contentType==gt.ContentType.JSON||t.contentType==gt.ContentType.TEXT?await i.file("data").async("string"):await i.file("data").async("uint8array");break}case gt.CompressionType.LZMA:throw new Error("LZMA compression is not supported yet");default:throw new Error(`Invalid compression type: ${t.compressionType}`)}return t.contentType==gt.ContentType.JSON&&(r=JSON.parse(r)),r}}class It{calculatePrecision(e,t){throw new Error("PrecisionCalculator.calculatePrecision(data, property) should be implemented")}}const St=["position","size","rotation","scale","offset"],wt={position:0,size:4,rotation:8,scale:12,offset:16};class xt{constructor(e=0){this.precisions=e;for(let e of St)Object.defineProperty(this,e,{get:()=>this.get(e),set:t=>this.set(e,t),enumerable:!0});Object.defineProperty(this,"factors",{get:()=>Object.assign({},...St.map((e=>({[e]:10**this[e]})))),enumerable:!0})}get(e){return this.precisions>>wt[e]&15}set(e,t){if(t>15||t<0)throw new Error(`Invalid '${e}' precision value ${t} found. The value must be in the interval [0, 15].`);if(t>this[e])throw new Error(`PrecisionSchema '${e}' update failed. Update value ${t} > ${this[e]} - update value should be less than current value.`);t!=this[e]&&(this.precisions=this.precisions&~(15<<wt[e])|t<<wt[e])}update(e){St.forEach((t=>{let r=e[t];r<this[t]&&(this[t]=r)}))}decode(){return Object.assign({},...St.map((e=>({[e]:this[e]}))))}static encode(e={}){let t=0;return St.forEach((r=>{let i=e[r]||0;if(i>15||i<0)throw new Error(`Invalid '${r}' precision value ${i} found. The value must be in the interval [0, 15].`);t=t&~(15<<wt[r])|i<<wt[r]})),t}}class vt{static l2Norm(e){let t=0;for(let r of e)t+=r*r;return Math.sqrt(t)}static rmse(e,t){let r=0;for(let i=0;i<e.length;i++){let s=e[i]-t[i];r+=s*s}return Math.sqrt(r/e.length)}static variance(e){if(e.length<=1)return 0;let t=this.average(e),r=0;for(let i of e){let e=i-t;r+=e*e}return r/(e.length-1)}static average(e){let t=0;for(let r of e)t+=r;return t/e.length}static calculateError(e,t){let r=10**t,i=new Float32Array(e.length);for(let t=0;t<i.length;t++){let s=Math.round(e[t]*r);if(s>Number.MAX_INT32||s<-Number.MAX_INT32)return NaN;i[t]=s}let s=new Float32Array(e.length);for(let e=0;e<i.length;e++)s[e]=i[e]/r;return this.rmse(e,s)}static isZero(e){return Math.abs(e)<Number.EPSILON}}class Rt extends S{constructor(e,t){super(),this.layout=e,this.pathPointCalculator=t,this.inputBuffer=[],this.prediction=!0}togglePrediction(e){console.warn("PathProducer togglePrediction method is deprecated. Use InkBuilder instance prediction property to configure prediction behaviour."),this.prediction=e}addImpl(e,t){if(e.phase!=this.phase)throw new Error(`The phase of the addition (${e.phase.name}) doesn't match the phase of the PathProducer (${this.phase.name})`);let r=[],i=[];e&&this.inputBuffer.push(e);let s=this.inputBuffer.length>=3?this.inputBuffer[this.inputBuffer.length-3]:null,n=this.inputBuffer.length>=2?this.inputBuffer[this.inputBuffer.length-2]:null,o=this.inputBuffer.length>=1?this.inputBuffer[this.inputBuffer.length-1]:null,a=this.calculate(s,n,o);return e&&a&&r.push(...a.toArray(this.layout)),this.phase==S.Phase.END?(a=this.calculate(n,o,null),a&&r.push(...a.toArray(this.layout))):this.prediction&&(this.phase==S.Phase.UPDATE||t)&&(a=this.calculate(n,o,t),a&&(i.push(...a.toArray(this.layout)),a=this.calculate(o,t,null),a&&i.push(...a.toArray(this.layout)))),{added:r,predicted:i}}calculate(e,t,r){return t?this.pathPointCalculator(e,t,r):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 At extends Xe{#o=[];#a=0;constructor(e,t=15){super(),this.filter=Tt.slice(),Object.defineProperty(this,"movingAverageWindowSize",{get:function(){return t},set:function(e){t=e,this.filter.length!=e&&(this.filter=At.resample(Tt,e)),this.predictionPointsCount=4*e/15,this.windowSize=this.filter.length},enumerable:!0}),this.dimsCount=e,this.movingAverageWindowSize=t}add(e,t){return t?this.project(e):this.addSequence(e)}processImpl(e){return this.project(e)}project(e){if(e.length%this.dimsCount!=0)throw new Error(`Points size ('${e.length}') must be multiple of the dimensions count ('${this.dimsCount}').`);if(0==e.length)return[];let t=[],r=this.#o.slice(),i=e.slice(0,e.length-this.dimsCount),s=this.addSequence(i);t.push(...s);let n=e.slice(e.length-this.dimsCount,e.length),o=this.predictionPointsCount;for(let e=0;e<o;e++){let r=this.addPoint(n);o-e<=this.#a&&t.push(...r)}return this.#o=r,t}addSequence(e){if(e.length%this.dimsCount!=0)throw new Error(`Points size ('${e.length}') must be multiple of the dimensions count ('${this.dimsCount}').`);let t=[],r=e.length/this.dimsCount;for(let i=0;i<r;i++){let r=this.addPoint(e.slice(i*this.dimsCount,(i+1)*this.dimsCount));t.push(...r)}return this.#a+=r,t}addPoint(e){for(this.#o.push(...e);this.#o.length<this.windowSize*this.dimsCount;)this.#o.unshift(...this.#o.slice(0,this.dimsCount));for(;this.#o.length>this.windowSize*this.dimsCount;)this.#o=this.#o.slice(this.dimsCount);return this.filterBuffer()}filterBuffer(){let e=[];for(let t=0;t<this.windowSize;t++)for(let r=0;r<this.dimsCount;r++)isNaN(e[r])&&(e[r]=0),e[r]+=this.#o[t*this.dimsCount+r]*this.filter[t];return e}reset(){super.reset(),this.#a=0,this.#o.clear()}static resample(e,t){let r=new Float32Array(t),i=e.length/t,s=0;for(let n=0;n<t;n++){let o=(e.length-1)*n/(t-1),a=Math.floor(o),l=Math.ceil(o),h=o-a,d=i*(e[a]*(1-h)+e[l]*h);s+=d,r[n]=d}let n=1/s;for(let e=0;e<t;e++)r[e]*=n;return r}}class Ct{constructor(e,t){e>0&&0==t?(this.segmentIndex=e-1,this.t=1):(this.segmentIndex=e,this.t=t),Object.defineProperty(this,"index",{get:()=>(console.warn("SplineParameter index => segmentIndex"),this.segmentIndex)})}equals(e){return this.segmentIndex==e.segmentIndex&&this.t==e.t}toString(){return`spline-parameter(${this.segmentIndex}, ${this.t})`}toJSON(){return{segmentIndex:this.segmentIndex,t:this.t}}static fromJSON(e){return new Ct(e.segmentIndex,e.t)}static calcMiddleOfSegment(e,t){let r=.5*(e.t+t.t+(t.segmentIndex-e.segmentIndex)),i=Math.trunc(r),s=r-i;return new Ct(e.segmentIndex+i,s)}static areDistantEnough(e,t,r=.01){return t.t+(t.segmentIndex-e.segmentIndex)-e.t>r}}class Ot{#e;constructor(e,t,r,i,s){1==r&&(t++,r=0),0==s&&(i--,s=1),Object.defineProperties(this,{spline:{value:e,enumerable:!0},segmentIndexStart:{value:t,enumerable:!0},segmentIndexEnd:{value:i,enumerable:!0},ts:{value:r,enumerable:!0},tf:{value:s,enumerable:!0}}),Object.defineProperty(this,"pointIndexStart",{value:t,enumerable:!0}),Object.defineProperty(this,"pointIndexEnd",{value:i+3,enumerable:!0}),Object.defineProperty(this,"length",{value:this.pointIndexEnd-this.pointIndexStart+1,enumerable:!0}),Object.defineProperty(this,"id",{get:()=>(this.#e||(this.#e=E.generate()),this.#e),set:e=>{if(this.#e)throw new Error("id is immutable");this.#e=e}}),this.validate()}validate(){let e=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(e<1)throw new Error(`Invalid fragment points range {${this.pointIndexStart}, ${this.pointIndexEnd}} found. At least 4 points are needed to define spline.`);if(1==e&&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(e){let t=[this,e];t.sort(Ot.compare);let r=t.first,i=t.last,s=r.segmentIndexEnd,n=r.tf;if(1==n&&(s++,n=0),s!=i.segmentIndexStart||n!=i.ts)throw new Error(`Fragments ${r} and ${i} are not adjacent.`);let o=new Ot(this.spline,r.segmentIndexStart,r.ts,i.segmentIndexEnd,i.tf);return o.#e=this.#e,this.inside&&(o.inside=this.inside),o}overlaps(e){if(e.spline!=this.spline)return!1;let t=e.segmentIndexStart<this.segmentIndexEnd||e.segmentIndexStart==this.segmentIndexEnd&&e.ts<=this.tf,r=e.segmentIndexEnd>this.segmentIndexStart||e.segmentIndexEnd==this.segmentIndexStart&&e.tf>=this.ts;return t&&r}toString(){return`fragment(${this.segmentIndexStart}, ${this.ts} - ${this.segmentIndexEnd}, ${this.tf})`}static compare(e,t){return e.segmentIndexStart<t.segmentIndexStart?-1:e.segmentIndexStart>t.segmentIndexStart?1:e.ts<t.ts?-1:e.ts>t.ts?1:0}static getInstance(e,t,r){return new Ot(e,t.segmentIndex,t.t,r.segmentIndex,r.t)}}class Dt extends Ae{constructor(e,t,r,i=0,s=1){super(t,r,e),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=i,this.tf=s,Object.defineProperty(this,"bounds",{get:()=>v.ofSpline(this,this.pointProps.scattering).ceil(),enumerable:!0}),Object.defineProperty(this,"color",{get:()=>ve.isColor(this.pointProps)?ve.fromColor(this.pointProps):void 0,set:e=>{if(!e)throw new Error("Spline color cannot be removed");if(!(e instanceof ve))throw new Error("Expected value should be Color instance");"red"in this.pointProps&&(this.pointProps.red=e.red),"green"in this.pointProps&&(this.pointProps.green=e.green),"blue"in this.pointProps&&(this.pointProps.blue=e.blue),"alpha"in this.pointProps&&(this.pointProps.alpha=e.alpha)},enumerable:!0}),this.validate()}validate(){let e=this.points instanceof Float32Array;if(super.validate(),!this.layout.includes(U.Property.X))throw new Error("Layout doesn't contains required properties X");if(!this.layout.includes(U.Property.Y))throw new Error("Layout doesn't contains required properties Y");if(e&&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(e&&this.segmentsCount<1)throw new Error("Incompleted spline found. Spline is defined with at least 4 control points.")}clone(){return new Dt(this.layout.slice(),this.points.clone(),Object.clone(this.pointProps),this.ts,this.tf)}slice(e){let t=this.slicePoints(e.pointIndexStart,e.pointIndexEnd),r=new Dt(this.layout.slice(),t,Object.clone(this.pointProps),e.ts,e.tf);return r.id=e.id,r}getSegment(e){let t=e,r=e+3,i=0==t?this.ts:0,s=r+1==this.length?this.tf:1;return this.slice({pointIndexStart:t,pointIndexEnd:r,ts:i,tf:s})}getFragment(e=0,t=this.ts,r=this.segmentsCount-1,i=this.tf,s=!1){return new Ot(this,e,t,s?r-3:r,i)}toPlainPath(){let e=new Ae([]);for(let t=0;t<this.length;t++)e.points.push(this.getPointX(),this.getPointY());return e}toJSON(){return{type:"Spline",id:this.id,layout:this.layout.map((e=>e.name)),points:de.encode(this.points,this.encoding),pointProps:this.pointProps,ts:this.ts,tf:this.tf}}static fromJSON(e){let t=de.decode(e.points),r=new Dt(e.layout.map((e=>U.Property[e])),t,e.pointProps,e.ts,e.tf);return r.id=e.id,r}static fromRect(e,t){let r=[e.left,e.top,e.left,e.top,e.right,e.top,e.right,e.bottom,e.left,e.bottom,e.left,e.top,e.left,e.top];return new Dt(void 0,r,t)}static createInstance(e,t,r=[],i,s){return new Dt(e,r,t,i,s)}static createSharedInstance(e,t,r,i,s){return new Dt(e,Float32Array.createSharedInstance(t),r,i,s)}}class kt extends Xe{#l;#h;constructor(e){super(),this.layout=e,this.pathPointProps={}}add(e,t){this.#l||(this.#l=Dt.createInstance(this.layout,this.pathPointProps)),0==this.#l.points.length&&e.length>0&&e.unshift(...e.slice(0,this.layout.length)),t&&(e.length>=this.layout.length?e.push(...e.slice(e.length-this.layout.length,e.length)):e.push(...this.getLastPart()));let r=this.getFirstPart();return this.#l.points=r.concat(e),e}predict(e=[]){if(0==e.length)return e;this.#h?this.#h.points.clear():this.#h=Dt.createInstance(this.layout,this.pathPointProps);let t=this.#h.points,r=this.getFirstPart();for(t.push(...r),t.push(...e),t.push(...t.slice(t.length-this.layout.length,t.length));t.length<4*this.layout.length;)t.unshift(t.slice(0,this.layout.length));return t}processImpl(e){let t=[];return e.length>0&&(t.push(...e.slice(0,this.layout.length)),t.push(...e),e.length>=this.layout.length&&t.push(...e.slice(e.length-this.layout.length,e.length))),e}getOutput(e,t){if(t==kt.OutputType.ADDITION){if(this.#l.points.length>=4*this.layout.length)return this.#l}else if(t==kt.OutputType.PREDICTION){if(this.#h.points.length>0)return this.#h}else if(e.length>0)return Dt.createSharedInstance(this.layout,e,this.pathPointProps)}getFirstPart(){return this.#l.points.slice(Math.max(0,this.#l.points.length-3*this.layout.length),this.#l.points.length)}getLastPart(){return this.#l.points.slice(this.#l.points.length-this.layout.length,this.#l.points.length)}reset(){super.reset(),this.#l=null,this.#h=null}}class Nt extends Ae{constructor(e,t,r,i=[]){super(t,r,e),i.length>0&&!Object.isFrozen(i.first)&&i.forEach((e=>Object.freeze(e))),Object.defineProperty(this,"splineParameters",{value:Object.freeze(i),enumerable:!0});let s=new Re(e,r);Object.defineProperty(this,"style",{get:()=>s.style,set:e=>s.style.reset(e),enumerable:!0}),Object.defineProperty(this,"color",{get:()=>this.style.color,set:e=>{if(!e)throw new Error("Spline color cannot be removed");if(!(e instanceof ve))throw new Error("Expected value should be Color instance");"red"in this.pointProps&&(this.pointProps.red=e.red),"green"in this.pointProps&&(this.pointProps.green=e.green),"blue"in this.pointProps&&(this.pointProps.blue=e.blue),"alpha"in this.pointProps&&(this.pointProps.alpha=e.alpha)},enumerable:!0}),Object.defineProperty(this,"bounds",{get:()=>v.ofSpline(this,this.pointProps.scattering).ceil(),enumerable:!0}),this.validate()}validate(){let e=this.points instanceof Float32Array;if(super.validate(),!this.layout.includes(U.Property.X))throw new Error("Layout doesn't contains required properties X");if(!this.layout.includes(U.Property.Y))throw new Error("Layout doesn't contains required properties Y");if(e&&0==this.points.length)throw new Error("Empty spline is not allowed")}clone(){return new Nt(this.layout.slice(),this.points.clone(),Object.clone(this.pointProps),this.splineParameters.slice())}slice(e){let t=this.slicePoints(e.pointIndexStart,e.pointIndexEnd);return new Nt(this.layout.slice(),t,Object.clone(this.pointProps),this.splineParameters.slice())}getPoint(e){return super.getPoint(e,this.style)}getPointRef(e){return super.getPointRef(e,this.style)}getPointSegmentIndex(e){return this.splineParameters[e]?this.splineParameters[e].index:void 0}getPointT(e){return this.splineParameters[e]?this.splineParameters[e].t:void 0}getPointParameter(e){return this.splineParameters[e]}toJSON(){return{type:"InterpolatedSpline",layout:this.layout.map((e=>e.name)),points:de.encode(this.points,this.encoding),pointProps:this.pointProps,splineParameters:this.splineParameters}}static fromJSON(e){let t=de.decode(e.points);return new Nt(e.layout.map((e=>U.Property[e])),t,e.pointProps,e.splineParameters.map(Ct.fromJSON))}static fromRect(e,t){throw new Error("InterpolatedSpline.fromRect is not supported. Try Spline.fromRect and interpolate with particular Spline interpolator.")}static createInstance(e,t,r=[]){return new Nt(e,r,t)}static createSharedInstance(e,t,r,i){return new Nt(e,Float32Array.createSharedInstance(t),r,i)}}const Mt=r.mat4.fromValues(0,-.5,1,-.5,1,0,-2.5,1.5,0,.5,2,-1.5,0,0,-.5,.5);class Lt extends Xe{#l;#h;#d;constructor(e=!1,t=!1){super(),this.calculateDerivates=e,this.keepSplineParameters=t,this.state={segmentIndex:-1,lastPointPosition:void 0,lastPointSize:0}}initState(e){this.state.layout={},e.layout.forEach(((e,t)=>{this.state.layout[e.name]={index:t,polynomials:r.vec4.create()}})),this.keepSplineParameters?this.state.splineParameters?this.state.splineParameters.clear():this.state.splineParameters=[]:delete this.state.splineParameters,this.splineLayout=e.layout,this.pathPointProps=Object.clone(e.pointProps),this.scattering&&(this.pathPointProps.scattering=this.scattering),this.layout=this.calculateDerivates?e.layout.concat([U.Property.D_X,U.Property.D_Y]):e.layout,this.state.ready=!0}predict(e){if(!e)return[];this.state.ready||this.initState(e),this.#h?this.#h.points.clear():this.#h=Nt.createInstance(this.layout,this.pathPointProps),this.path=this.#h;let t=Object.clone(this.state);return delete this.state.splineParameters,this.resetState(),this.discretize(e),this.state=t,this.path.points}processImpl(e,t){if(!e)return[];let r;return e instanceof Ot&&(r=e,e=r.spline),this.state.ready||this.initState(e),t==Lt.OutputType.ADDITION?(this.#l?this.#l.points.clear():this.#l=Nt.createInstance(this.layout,this.pathPointProps),this.path=this.#l):(this.#d=Nt.createInstance(this.layout,this.pathPointProps),this.path=this.#d),this.discretize(e,r),this.path.points}getOutput(e,t){if(0!=e.length){if(t==Lt.OutputType.PROCESSOR||t==Lt.OutputType.ALL_DATA){let t=this.state.splineParameters;return t&&(t=t.slice()),Nt.createSharedInstance(this.layout,e,this.pathPointProps,t)}return this.path}}calculateInterpolatedPoint(e,t,i){this.initState(e);let s=new U(0,0,this.splineLayout.includes(U.Property.Z)?0:void 0),n=r.vec4.fromValues(1,i,i*i,i*i*i);return this.calculatePolynomials(e,t),this.splineLayout.forEach((e=>{let t=r.vec4.dot(this.state.layout[e.name].polynomials,n);s[M.getPropName(e.name)]=t})),s}discretize(e,t){throw new Error("This method is abstract and should be implemented")}storeLastPoint(e,t=0){this.state.lastPointPosition=new w(this.getPropValue(U.Property.X,e,t),this.getPropValue(U.Property.Y,e,t),this.getPropValue(U.Property.Z,e,t)),this.state.lastPointSize=this.getPropValue(U.Property.SIZE,e,t)}getPropValue(e,t,r=0){return this.state.layout[e.name]?t[r+this.state.layout[e.name].index]:void 0}calculatePolynomials(e,t){let i=e.points,s=this.splineLayout.length*(t+0),n=this.splineLayout.length*(t+1),o=this.splineLayout.length*(t+2),a=this.splineLayout.length*(t+3);this.splineLayout.forEach(((e,t)=>{let l=r.vec4.fromValues(i[s+t],i[n+t],i[o+t],i[a+t]);r.vec4.transformMat4(this.state.layout[e.name].polynomials,l,Mt)}))}samplePoint(e){let t=[],i=r.vec4.fromValues(1,e,e*e,e*e*e);return this.splineLayout.forEach((e=>{let s=r.vec4.dot(this.state.layout[e.name].polynomials,i);t.push(s)})),this.calculateDerivates&&(t.push(this.getDerivativeOf(this.state.layout.X.polynomials,i)),t.push(this.getDerivativeOf(this.state.layout.Y.polynomials,i))),t}getDerivativeOf(e,t){let i=r.vec4.fromValues(e[1],2*e[2],3*e[3],0);return r.vec4.dot(i,t)}keepSegmentT(e){this.state.splineParameters&&this.state.splineParameters.push(new Ct(this.state.segmentIndex,e))}resetState(){this.state.segmentIndex=-1}reset(){super.reset(),this.state.ready=!1,this.state.lastPointPosition=void 0,this.state.lastPointSize=0,this.resetState(),this.#l=null,this.#h=null,this.#d=null}}class _t extends Lt{constructor(e=.1,t,r){super(t,r),this.spacing=e}split(e,t=8){let r=this.spacing;this.spacing=1,this.splitCount=t;let i=this.process(e);return this.spacing=r,delete this.splitCount,i}discretize(e,t){let i,s,n=this.path.points,o=this.splitCount,a=Math.max(1,10*(this.spacing>1?1:this.spacing)),l=0,h=e.segmentsCount-1,d=e.ts,c=e.tf;t&&(l=t.segmentIndexStart,h=t.segmentIndexEnd,d=t.ts,c=t.tf,this.state.segmentIndex=l-1);for(let t=l;t<h+1;t++){if(this.state.segmentIndex++,this.calculatePolynomials(e,t),isNaN(this.splitCount)){i||(i=U.createInstance(e.layout),s=U.createInstance(e.layout)),i.fill(t+1,e.points,e.layout,e.pointProps),s.fill(t+2,e.points,e.layout,e.pointProps);let n=r.vec2.distance(i.value,s.value),l=this.pathPointProps.size;this.state.layout.SIZE&&(l=Math.min(i.size,s.size)),o=Math.floor(a*(n/l)/this.spacing)+1}let l=1/o;for(let e=0;e<=o;e++){let r=!this.state.lastPointPosition,i=e/o;if(0==t&&i<d){if(!(i+l>=d))continue;i=d,r=this.spacing<=1}if(t==h&&i>=c){if(!(i<c+l))continue;i=c,r=this.lastSegment&&this.spacing<=1}if(t>0&&0==i)continue;let s=this.samplePoint(i);if(!r&&this.state.lastPointPosition){let e=new w(this.getPropValue(U.Property.X,s),this.getPropValue(U.Property.Y,s),this.getPropValue(U.Property.Z,s)),t=this.state.lastPointPosition.vec.squaredDistance(this.state.lastPointPosition.value,e.value),i=(this.state.layout.SIZE?(this.state.lastPointSize+s[this.state.layout.SIZE.index])/2:this.pathPointProps.size)*this.spacing;r=t>=i*i}r&&(n.push(...s),this.storeLastPoint(s),this.keepSegmentT(i))}}}}class Ft{constructor(e){this.key=e,this.height=1}leftRotate(){let e=this.right,t=e.left;return e.left=this,this.right=t,this.height=Math.max(Ft.height(this.left),Ft.height(this.right))+1,e.height=Math.max(Ft.height(e.left),Ft.height(e.right))+1,e}rightRotate(){let e=this.left,t=e.right;return e.right=this,this.left=t,this.height=Math.max(Ft.height(this.left),Ft.height(this.right))+1,e.height=Math.max(Ft.height(e.left),Ft.height(e.right))+1,e}getBalanceFactor(){return Ft.height(this.left)-Ft.height(this.right)}static height(e){return e?e.height:0}static minValue(e){if(!e)return;let t=e;for(;t.left;)t=t.left;return t.key}static maxValue(e){if(!e)return;let t=e;for(;t.right;)t=t.right;return t.key}}class Bt{constructor(){this.count=0,this.hasKey=!1,this.root}min(){return Ft.minValue(this.root)}max(){return Ft.maxValue(this.root)}add(e){return this.hasKey=!1,this.root=this.insertNode(this.root,e),this.hasKey||this.count++,!this.hasKey}insertNode(e,t){if(!e)return new Ft(t);if(t<e.key)e.left=this.insertNode(e.left,t);else{if(!(t>e.key))return this.hasKey=!0,e;e.right=this.insertNode(e.right,t)}if(!this.hasKey){e.height=1+Math.max(Ft.height(e.left),Ft.height(e.right));let r=e.getBalanceFactor();if(r>1){if(t<e.left.key)return e.rightRotate();if(t>e.left.key)return e.left=e.left.leftRotate(),e.rightRotate()}else if(r<-1){if(t>e.right.key)return e.leftRotate();if(t<e.right.key)return e.right=e.right.rightRotate(),e.leftRotate()}}return e}contains(e){return this.containsNode(this.root,e)}containsNode(e,t){return!!e&&(t<e.key?this.containsNode(e.left,t):!(t>e.key)||this.containsNode(e.right,t))}printTree(){if(!this.root)return;let e=[this.root],t=this.root.height;for(;e.length>0;){let r=e.shift();t!=r.height&&console.log("-"),console.log(`${r.key} with height: ${r.height}, balance: ${r.getBalanceFactor()}`),t=r.height;let i=r.left,s=r.right;i&&e.push(i),s&&e.push(s)}}toArray(){let e=[];return Bt.fillArray(e,this.root),e}static fillArray(e,t){t&&(this.fillArray(e,t.left),e.push(t.key),this.fillArray(e,t.right))}}class Ut{constructor(){this.tree=new Bt,Object.defineProperty(this,"length",{get:()=>this.tree.count,enumerable:!0})}clear(){this.tree=new Bt}add(e){return this.tree.add(e)}includes(e){return this.tree.contains(e)}min(){return this.tree.min()}max(){return this.tree.max()}toArray(){return this.tree.toArray()}}class jt extends Lt{constructor(e,t){super(e,t),this.state.lastSegmentIndex=-1,this.state.lastPointRotation=0,this.state.lastPointT=0,this.state.absAccumulatedErrorPos=0,this.state.absAccumulatedErrorS=0,this.setT=new Ut,this.samples=[],Object.defineProperty(this,"errorThreshold",{get:()=>this.error,set:e=>{this.error=e,this.errorDistSq=this.error*this.error,this.error10=10*this.error},enumerable:!0}),this.errorThreshold=.15}discretize(e,t){let r=this.path.points,i=0,s=e.segmentsCount-1,n=e.ts,o=e.tf;t&&(i=t.segmentIndexStart,s=t.segmentIndexEnd,n=t.ts,o=t.tf,this.state.segmentIndex=i-1);for(let t=i;t<s+1;t++){this.state.segmentIndex++,this.calculatePolynomials(e,t);let i=this.calculateTValues(t==s,n,o);r.push(...this.samplePoints(i)),i.length>0&&(this.resetAccumulatedErrors(),this.storeLastPoint(r))}}samplePoints(e){return this.samples.clear(),e.toArray().forEach((e=>{this.keepSegmentT(e),this.samples.push(...this.samplePoint(e))})),this.samples}storeLastPoint(e){let t=e.length-this.layout.length;super.storeLastPoint(e,t),this.state.lastPointRotation=this.getPropValue(U.Property.ROTATION,e,t),this.state.lastPointT=this.setT.max(),this.state.lastSegmentIndex=this.state.segmentIndex}calculateTValues(e,t,r){let i=0==this.state.segmentIndex?t:0,s=e?r:1;return this.setT.clear(),this.getTForPos(i,s),this.state.layout.SIZE&&this.getTForCubic(i,s,this.state.layout.SIZE.polynomials,this.error),this.mustAddStartT()&&this.setT.add(i),e&&this.setT.add(s),this.state.layout.ROTATION&&this.getTForRotation(i,s),this.setT}mustAddStartT(){if(this.state.lastSegmentIndex<0)return!0;let e=this.state.lastPointT-(this.state.segmentIndex-this.state.lastSegmentIndex),t=this.setT.length>0?this.setT.min():1,r=this.getPosErrorAtT0(t,this.state.lastPointPosition);if(this.state.absAccumulatedErrorPos+=Math.abs(r),this.state.layout.SIZE){let r=this.getErrorAtT0(this.state.layout.SIZE.polynomials,t,e,this.state.lastPointSize);this.state.absAccumulatedErrorS+=Math.abs(r)}return this.state.absAccumulatedErrorPos>this.errorDistSq||this.state.absAccumulatedErrorS>this.error}getPosErrorAtT0(e,t){let r=this.getTPoint(e),i=this.getTPoint(0);return this.minDistanceSq(t,r,i)}getErrorAtT0(e,t,r,i){let s=r,n=i,o=t,a=this.cubicCalc(e,o),l=this.cubicCalc(e,0),h=n+(0-s)*(a-n)/(o-s);return Math.abs(l-h)}getTForPos(e,t){let r=this.getTPoint(e),i=this.getTPoint(t),s=this.subdividePos(r,i);if(s.split)this.subdivideRecursivePos(r,s),this.setT.add(s.t),this.subdivideRecursivePos(s,i);else{let e=this.subdividePos(r,s),t=this.subdividePos(s,i);e.split&&(this.subdivideRecursivePos(r,e),this.setT.add(e.t),this.subdivideRecursivePos(e,s)),(e.split||t.split)&&this.setT.add(s.t),t.split&&(this.subdivideRecursivePos(s,t),this.setT.add(t.t),this.subdivideRecursivePos(t,i))}}subdivideRecursivePos(e,t){let r=this.subdividePos(e,t);r.split&&(this.subdivideRecursivePos(e,r),this.setT.add(r.t),this.subdivideRecursivePos(r,t))}subdividePos(e,t){let r=.5*(e.t+t.t),i=this.getTPoint(r),s=this.minDistanceSq(e,t,i),n=e.add(t).scaleSelf(.5),o=i.subtract(n).absSelf();return i.split=s>this.errorDistSq||o.x>this.error10||o.y>this.error10,this.state.layout.Z&&(i.split=i.split||o.z>this.error10),i}getTForCubic(e,t,r,i){let s={v:this.cubicCalc(r,e),t:e},n={v:this.cubicCalc(r,t),t:t},o=this.subdivide(s,n,r);if(o.diff>i)this.subdivideRecursive(s,o,r,i),this.setT.add(o.t),this.subdivideRecursive(o,n,r,i);else{let e=this.subdivide(s,o,r),t=this.subdivide(o,n,r);e.diff>i&&(this.subdivideRecursive(s,e,r,i),this.setT.add(e.t),this.subdivideRecursive(e,o,r,i)),(e.diff>i||t.diff>i)&&this.setT.add(o.t),t.diff>i&&(this.subdivideRecursive(o,t,r,i),this.setT.add(t.t),this.subdivideRecursive(t,n,r,i))}}subdivideRecursive(e,t,r,i){let s=this.subdivide(e,t,r);s.diff>i&&(this.subdivideRecursive(e,s,r,i),this.setT.add(s.t),this.subdivideRecursive(s,t,r,i))}subdivide(e,t,r){let i=.5*(e.t+t.t),s=this.cubicCalc(r,i),n=.5*(e.v+t.v);return{v:s,t:i,diff:Math.abs(s-n)}}getTForRotation(e,t){let r=this.state.layout.ROTATION.polynomials,i=this.state.lastPointRotation;this.state.lastSegmentIndex<0&&(i=this.cubicCalc(r,e));let s=.25*(t-e);for(let t=0;t<4;t++){let n=e+t*s,o=this.cubicCalc(r,n);Math.abs(o-i)>.06&&(this.setT.add(n),i=o)}}minDistanceSq(e,t,r){let i=r.vec,s=i.squaredDistance(e.value,t.value);if(0==s)return i.squaredDistance(r.value,e.value);let n=Math.max(0,Math.min(1,i.dot(r.subtract(e).value,t.subtract(e).value)/s)),o=t.subtract(e).scale(n).add(e);return i.squaredDistance(r.value,o.value)}getTPoint(e){let t=new w(this.cubicCalc(this.state.layout.X.polynomials,e),this.cubicCalc(this.state.layout.Y.polynomials,e),this.state.layout.Z?this.cubicCalc(this.state.layout.Z.polynomials,e):void 0);return t.t=e,t}cubicCalc(e,t){return e[0]+e[1]*t+e[2]*t*t+e[3]*t*t*t}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 Gt extends nt{constructor(...e){let t;super(...e),Object.defineProperty(this,"encoding",{get:()=>t,set:e=>{t=e,this.forEach((t=>t.encoding=e))},enumerable:!0})}union(e=!1,t=.1){let r=new Ce(this,this.bounds);r.subject=be.SimplifyPolygons(r.subject,we.pftNonZero),r.solution=be.CleanPolygons(r.subject,t*r.transform.scale),1==r.subject.length&&0==r.solution.first.length&&(r.solution=r.subject);let i=r.toPaths();return e?Le.createSharedInstance(i.first,i.slice(1)):Le.createInstance(i.first,i.slice(1))}intersects(e){e instanceof Le&&(e=[e]);for(let t of this)for(let r of e)if(t.intersects(r))return{poly1:t,poly2:r};return null}toJSON(){let e=super.toJSON();return e.type="InkPath2D",e}static fromJSON(e){if("InkPath2D"!=e.type)throw new Error(`InkPath2D deserialization failed. JSON type is ${e.type}, expected InkPath2D.`);return new Gt(...e.polygons.map((e=>Le.fromJSON(e))))}}class $t extends Xe{static ARRAY_TYPE=Gt;#l;#h;#d;#n;constructor(e){super(),this.brush=e}processImpl(e,t){return t==$t.OutputType.ADDITION?(this.#l||(this.#l=new Gt),this.#n=this.#l):t==$t.OutputType.PREDICTION?(this.#h||(this.#h=new Gt),this.#n=this.#h):(this.#d||(this.#d=new Gt),this.#n=this.#d),this.#n.clear(),this.generatePolygons(e),this.#n}generatePolygons(e){if(!e)return this.#n;for(let t=0;t<e.length;t++){let r=e.getPointRef(t),i=this.applyBrush(r);this.#n.push(i)}}applyBrush(e){let t=this.createTransform(e),i=this.brush.selectShape(t.maxScale).shape,s=Float32Array.createSharedInstance(2*i.length);for(let e=0;e<i.length;e++){let n=e*i.stride,o=r.vec2.fromValues(i.getPointX(e),i.getPointY(e));r.vec2.transformMat2d(o,o,t),s[n]=o[0],s[n+1]=o[1]}return Le.createSharedInstance(s)}createTransform(e){if(isNaN(e.size))throw new Error("Size information not found");let t=r.mat2d.create(),i=e.size*e.scaleX,s=e.size*e.scaleY,n=Math.max(i,s);return r.mat2d.translate(t,t,r.vec2.fromValues(e.x,e.y)),r.mat2d.rotate(t,t,e.rotation),r.mat2d.translate(t,t,r.vec2.fromValues(e.offsetX,e.offsetY)),r.mat2d.scale(t,t,r.vec2.fromValues(i,s)),t.maxScale=n,t}reset(){super.reset(),this.#l&&this.#l.clear(),this.#h&&this.#h.clear(),this.#d&&(this.#d=new Gt)}}class Yt extends Xe{static ARRAY_TYPE=Gt;#l;#h;#d;#n;#c;constructor(){super()}add(e,t){return this.#l||(this.#l=new Gt),this.#n=this.#l,this.#n.clear(),this.buildConvexHulls(e,!0),this.#n}processImpl(e,t){if(!(e instanceof Gt)){if(!(e instanceof Le))throw new Error("ConvexHullChainProducer build 'input' type missmatch, expected type is oneof(Polygon, InkPath2D)");e=[e]}return t==Yt.OutputType.PREDICTION?(this.#h||(this.#h=new Gt),this.#n=this.#h):(this.#d||(this.#d=new Gt),this.#n=this.#d),this.#n.clear(),this.buildConvexHulls(e),this.#n}buildConvexHulls(e,t=!1){let r=this.#c;for(let t of e){if(r||1==e.length){let e=r?r.union(t):t.convex();this.#n.push(e)}r=t}t&&e.length>0&&(this.#c=e.last)}reset(){super.reset(),this.#c=null,this.#l&&this.#l.clear(),this.#h&&this.#h.clear(),this.#d&&this.#d.clear()}}"function"==typeof Worker&&(Worker.prototype.on=function(e,t){this[`on${e}`]=r=>{let i="message"==e?r.data:r;t(i)}}),"function"==typeof DedicatedWorkerGlobalScope&&(DedicatedWorkerGlobalScope.prototype.on=function(e,t){this[`on${e}`]=r=>{let i="message"==e?r.data:r;t(i)}});let Xt=!1;class zt{constructor(e,t,r=zt.WorkerType.CLASSIC){if(!Xt)throw new Error("Constructor is private, use static method getInstance instead.");this.name=e,this.type=r,t&&t.startsWith("file://")&&(t=t.replace("file://","")),this.src=t,this.workers=[],this.transferables=[],this.status=zt.Status.CLOSED,this.resolver={};let i=0;Object.defineProperty(this,"nextID",{get:()=>String(i++),enumerable:!0,configurable:!0})}async open(e=this.src){if(this.status!=zt.Status.CLOSED)throw new Error(`${this.name} worker cannot be opened. Current status is ${this.status.name}.`);if(!e)throw new Error(`${this.name} worker location is not defined.`);let t,r;if("function"==typeof Worker)t=Worker,r=navigator.hardwareConcurrency||1;else{const e=await Promise.resolve().then((function(){return h(require("os"))})),i=await Promise.resolve().then((function(){return h(require("worker_threads"))})),{Worker:s}=i;t=s,r=e.cpus().length}this.ready=0;for(let i=0;i<r;i++){let r=this.name+i,s=new t(e,{type:this.type,name:r,workerData:{name:r}});s.name=i,s.on("message",(e=>"INIT"==e.action?this.confirmWorkerReady():this.recieve(e))),s.on("error",(e=>this.recieveError(e,i))),this.workers.push(s)}return this.status=zt.Status.OPEN_IN_PROGRESS,new Promise(((e,t)=>{this.workers.forEach(((e,t)=>e.postMessage({action:"INIT",worker:t}))),this.resolve=e}))}confirmWorkerReady(){this.ready++,this.ready==this.workers.length&&(this.resolve(),delete this.ready,delete this.resolve,this.status=zt.Status.OPEN)}close(){this.workers.forEach((e=>e.terminate())),this.workers.clear(),this.status=zt.Status.CLOSED}async broadcast(e,t){if(this.status!=zt.Status.OPEN)throw new Error(`ThreadBridge is not opened yet. Current status is ${this.status.name}. Use open first.`);return new Promise(((r,i)=>{this.resolver[t]=r;for(let r of this.workers){let i=this.buildRequestMessage(e,t);if(!i)break;this.send(r.name,i)}}))}async broadcastMessage(e){if(this.status!=zt.Status.OPEN)throw new Error(`ThreadBridge is not opened yet. Current status is ${this.status.name}. Use open first.`);if(!e.actionID)throw new Error("message actionID is required");return new Promise(((t,r)=>{this.resolver[e.actionID]=t;for(let t of this.workers)this.send(t.name,e)}))}send(e,t){if(this.status!=zt.Status.OPEN)throw new Error(`ThreadBridge is not opened yet. Current status is ${this.status.name}. Use open first.`);if(!t)throw new Error("message is required");this.workers[e].postMessage(t,this.transferables),this.transferables.clear()}buildRequestMessage(e,t){throw new Error("ThreadBridge.buildRequestMessage(action, actionID) is abstract and should be implemented")}recieve(e){throw new Error("ThreadBridge.recieve(message) is abstract and should be implemented")}resolve(e,t){this.resolver[e](t),delete this.resolver[e]}recieveError(e,t){console.warn(`${this.name} worker ${t}: ${e.message}`),e.filename||console.error(e)}static getInstance(){return this.instance||(Xt=!0,this.instance=new this,Xt=!1),this.instance}}Object.defineEnum(zt,"Status",["OPEN","OPEN_IN_PROGRESS","CLOSED"]),zt.WorkerType={CLASSIC:"classic",MODULE:"module"};class Vt extends zt{static WORKER_NAME="ConvexHullProvider";constructor(){super(Vt.WORKER_NAME,Vt.buildWorkerURL(),Vt.buildWorkerURL().contains("/wacom-src/")?zt.WorkerType.MODULE:zt.WorkerType.CLASSIC),this.state={}}static buildWorkerURL(){if("function"==typeof DedicatedWorkerGlobalScope)return;let e="undefined"==typeof __location?"undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("digital-ink-min.cjs",document.baseURI).href:__location;return e=e.substring(0,e.lastIndexOf("/")),e.endsWith("workers")||(e+="/workers"),e+=`/${Vt.WORKER_NAME}.js`,e}async build(e,t,r){let i=this.nextID;return this.state[i]={type:t,input:e,output:new Gt,queue:[...e.slice()],lastPolygon:r,expected:e.length,processed:0},await this.broadcast("BUILD",i)}buildRequestMessage(e,t){let r={action:e,actionID:t},i=this.state[t];if("BUILD"!=e)throw new Error(`Unknow data action found: ${e}`);{let e=i.queue.shift();if(!e)return;let t,s=i.input.indexOf(e),n=0==s?i.lastPolygon:i.input[s-1];n?t=Array.of(...n.shape.points,...e.shape.points):(n=e,e=i.queue.shift(),e?(t=Array.of(...n.shape.points,...e.shape.points),i.updateIndex=!0,i.expected--,s++):t=n.shape.points),r.index=s,r.data=t}return r}recieve(e){let t=this.state[e.actionID],r=t.updateIndex?e.index-1:e.index;if(t.output[r]=Le.createSharedInstance(e.data),t.processed++,t.processed==t.expected)delete this.state[e.actionID],this.keepAllData&&t.type==Xe.OutputType.ADDITION&&(this.path||(this.path=new Gt),this.path.push(...t.output)),this.resolve(e.actionID,t.output);else{let t=this.buildRequestMessage(e.action,e.actionID);t&&this.send(e.worker,t)}}}class Ht extends Xe{static ARRAY_TYPE=Gt;constructor(){super(),this.lastPolygon,this.convexHullProducer=Vt.getInstance(),Object.defineProperty(this,"closed",{get:()=>this.convexHullProducer.status==zt.Status.CLOSED,enumerable:!0})}static buildWorkerURL(){return Vt.buildWorkerURL()}async open(){await this.convexHullProducer.open()}close(){this.convexHullProducer.close()}async process(e,t=Ht.OutputType.PROCESSOR,r=!0){let i=this.lastPolygon;t==Ht.OutputType.ADDITION&&e.length>0&&(this.lastPolygon=e.last),r&&(this.lastPolygon=null);let s=await this.convexHullProducer.build(e,t,i);return this.getOutput(s)}reset(){super.reset(),this.lastPolygon=null}}class Zt extends Xe{static ARRAY_TYPE=Gt;predict(e){return console.warn("Prediction merge is not recommended"),e}processImpl(e,t){return this.merge(e,t==Zt.OutputType.PROCESSOR)}merge(e,t){if(0!=e.length)return e.union(t)}}class qt extends Xe{static ARRAY_TYPE=Gt;constructor(e=.1){super(),this.epsilon=e}predict(e){return console.warn("Prediction simplify is not recommended"),e}processImpl(e){return e instanceof Le?e.simplifyRamerDouglasPeucker(this.epsilon):new e.constructor(...e.map((e=>e.simplify(this.epsilon))))}}function Wt(){}Object.defineEnum(Wt,"Stage",["PATH_PRODUCER","SMOOTHER","SPLINE_PRODUCER","SPLINE_INTERPOLATOR","BRUSH_APPLIER","CONVEX_HULL_CHAIN_PRODUCER","POLYGON_MERGER","POLYGON_SIMPLIFIER"]);const Kt=Wt.Stage,Jt=S.Phase,Qt=Xe.OutputType;var er=Object.freeze({__proto__:null,Stage:Kt,Phase:Jt,OutputType:Qt,PathProducer:Rt,Smoother:At,SplineProducer:kt,DistanceBasedInterpolator:_t,CurvatureBasedInterpolator:jt,BrushApplier:$t,ConvexHullChainProducer:Yt,ConvexHullChainProducerAsync:Ht,PolygonMerger:Zt,PolygonSimplifier:qt});class tr{constructor(e){this.phase=e.phase;let t=isNaN(e.altitude)||isNaN(e.azimuth)?void 0:{altitude:e.altitude,azimuth:e.azimuth};Object.defineProperty(this,"x",{value:e.x,enumerable:!0}),Object.defineProperty(this,"y",{value:e.y,enumerable:!0}),Object.defineProperty(this,"z",{value:e.z,enumerable:!0}),Object.defineProperty(this,"timestamp",{value:e.timestamp,enumerable:!0,writable:!0}),Object.defineProperty(this,"force",{value:e.pressure,enumerable:!0}),Object.defineProperty(this,"pressure",{value:e.pressure,enumerable:!0}),Object.defineProperty(this,"rotation",{value:e.rotation,enumerable:!0}),Object.defineProperty(this,"radiusX",{value:e.radiusX,enumerable:!0}),Object.defineProperty(this,"radiusY",{value:e.radiusY,enumerable:!0}),Object.defineProperty(this,"altitude",{get:()=>(t||(t=this.computeTilt(e)||{}),t.altitude),enumerable:!0}),Object.defineProperty(this,"azimuth",{get:()=>(t||(t=this.computeTilt(e)||{}),t.azimuth),enumerable:!0}),e.pointer&&Object.defineProperty(this,"pointer",{value:e.pointer,enumerable:!0}),this.computedAzimuth=void 0}createPathPoint(e){return new U(this.x,this.y,this.z,e)}computeTilt(e){if(isNaN(e.tiltX)||isNaN(e.tiltY))return;let{tiltX:t,tiltY:r}=e,i=Math.tan(Math.toRadians(t)),s=Math.tan(Math.toRadians(r)),n=Math.sqrt(i*i+s*s);return{altitude:Math.atan2(1,n),azimuth:Math.atan2(s,i)}}speed(e,t){let r={x:0,y:0,time:0};return r=e&&!t?this.minus(e):t&&!e?t.minus(this):t.minus(e),r.time>0?tr.getMagnitude(r.x,r.y)/(r.time/1e3):(0==r.time||console.warn(`Speed out of range: ${r.time}ms`),0)}computeNearestAzimuthAngle(e){let t;if(isNaN(this.azimuth))return 0;if(e){if(isNaN(e.azimuth))return 0;let r=2*Math.PI,i=e.computedAzimuth||e.azimuth,s=parseInt(i/r);t=this.azimuth+s*r;let n=t-i;n>=Math.PI?t-=r:n<-Math.PI&&(t+=r)}else t=this.azimuth;return this.computedAzimuth=t,t}minus(e){return{x:this.x-e.x,y:this.y-e.y,time:this.timestamp-e.timestamp}}static getMagnitude(e,t){return Math.sqrt(e*e+t*t)}}Object.defineEnum(tr,"Property",["X","Y","Z","PHASE","TIMESTAMP","PRESSURE","RADIUS_X","RADIUS_Y","ALTITUDE","AZIMUTH","ROTATION"]);class rr{constructor(e=[],t=[]){this.accumulatedAddition=e,this.lastPrediction=t,this.first=!1,this.last=!1}add(e,t,r=[]){e==S.Phase.BEGIN?this.reset(!0):e==S.Phase.END&&(this.last=!0),t&&this.accumulatedAddition.push(...t),this.lastPrediction=r}clone(){let e=new rr(this.accumulatedAddition.slice(),this.lastPrediction.slice());return e.first=this.first,e.last=this.last,e}reset(e=!1){this.first=e,this.last=!1,this.accumulatedAddition.clear(),this.lastPrediction.clear()}}const ir=[Kt.SMOOTHER,Kt.POLYGON_MERGER,Kt.POLYGON_SIMPLIFIER],sr=[Kt.SPLINE_PRODUCER,Kt.SPLINE_INTERPOLATOR,Kt.BRUSH_APPLIER,Kt.CONVEX_HULL_CHAIN_PRODUCER,Kt.POLYGON_MERGER,Kt.POLYGON_SIMPLIFIER];class nr{#p;constructor(){this.layout=[U.Property.X,U.Property.Y],this.pathSegment=new rr,this.pathProducer=new Rt(this.layout),this.smoother=new At(this.layout.length),this.splineProducer=new kt(this.layout),this.distanceInterpolator=new _t,this.curvatureInterpolator=new jt,this.brushApplier=new $t,this.polygonMerger=new Zt,this.polygonSimplifier=new qt,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 e={};return this.lastPipelineStage&&(this.smoother.keepAllData&&(e.smootherPoints=this.smoother.allData),this.splineInterpolator.keepAllData&&this.lastPipelineStage.value>Kt.SPLINE_INTERPOLATOR.value&&(e.interpolatedSpline=this.splineInterpolator.allData),this.brushApplier.keepAllData&&this.lastPipelineStage.value>Kt.BRUSH_APPLIER.value&&(e.shapesPath=this.brushApplier.allData),this.convexHullChainProducer.keepAllData&&this.lastPipelineStage.value>Kt.CONVEX_HULL_CHAIN_PRODUCER.value&&(e.convexPath=this.convexHullChainProducer.allData)),e}}),Object.defineProperty(this,"prediction",{get:()=>this.pathProducer.prediction,set:e=>this.pathProducer.prediction=e,enumerable:!0})}configure(e={}){if(this.reset(this.pointerID),e.onBuildComplete)throw new Error("[InkBuilderSettings] onBuildComplete property is deprecated. Use InkBuilder instance onComplete property to set callback.");if("mergePrediction"in e&&console.warn("[InkBuilderSettings] 'mergePrediction' property is deprecated. Do not affects PolygonMerger behaviour."),!e.brush)throw new Error("[InkBuilderSettings] brush property is required");if(e.excludedPipelineStages){if(!Array.isArray(e.excludedPipelineStages))throw new Error("Expected type of excludedPipelineStages is Array instance");let t=e.excludedPipelineStages.filter((e=>!ir.includes(e)));t.length>0&&console.warn(`[InkBuilderSettings] excludedPipelineStages property includes steps which cannot be excluded: ${t.map((e=>e.name)).join(", ")}`),this.excludedPipelineStages=e.excludedPipelineStages.slice()}if(!this.excludedPipelineStages.includes(Kt.SMOOTHER)&&e.movingAverageWindowSize&&(this.smoother.movingAverageWindowSize=e.movingAverageWindowSize),e.lastPipelineStage){if(!sr.includes(e.lastPipelineStage))throw new Error(`[InkBuilderSettings] lastPipelineStage property expects one of: ${sr.map((e=>e.name)).join(", ")}`);if(this.excludedPipelineStages.includes(e.lastPipelineStage))throw new Error(`[InkBuilderSettings] lastPipelineStage ${e.lastPipelineStage.name} is disabled, check excludedPipelineStages configuration`);if(e.brush instanceof rt&&e.lastPipelineStage!=Kt.SPLINE_INTERPOLATOR)throw new Error(`[InkBuilderSettings] lastPipelineStage ${e.lastPipelineStage.name} is not compatible with provided brush`);this.lastPipelineStage=e.lastPipelineStage}switch(this.brush=e.brush,this.brush instanceof $e&&(this.brushApplier.brush=this.brush),this.lastPipelineStage||(this.brush instanceof $e?(this.brush.spacing>1?this.lastPipelineStage=Kt.BRUSH_APPLIER:this.excludedPipelineStages.includes(Kt.POLYGON_SIMPLIFIER)&&this.excludedPipelineStages.includes(Kt.POLYGON_MERGER)?this.lastPipelineStage=Kt.CONVEX_HULL_CHAIN_PRODUCER:this.lastPipelineStage=Kt.POLYGON_MERGER,this.lastPipelineStage==Kt.POLYGON_MERGER&&(this.concatSegments=Boolean(e.concatSegments))):this.lastPipelineStage=Kt.SPLINE_INTERPOLATOR),this.lastPipelineStage==Kt.SPLINE_INTERPOLATOR||this.lastPipelineStage==Kt.BRUSH_APPLIER?(this.splineInterpolator=this.distanceInterpolator,this.splineInterpolator.spacing=this.brush.spacing,this.splineInterpolator.scattering=this.brush.scattering,this.splineInterpolator.calculateDerivates=this.brush instanceof rt):(this.splineInterpolator=this.curvatureInterpolator,this.splineInterpolator.errorThreshold=e.errorThreshold||.15),this.splineInterpolator.keepSplineParameters=!!e.keepSplineParameters,this.splineInterpolator.keepAllData=!1,this.brushApplier.keepAllData=!1,this.convexHullChainProducer.keepAllData=!1,this.polygonMerger.keepAllData=!1,this.polygonSimplifier.keepAllData=!1,this.lastPipelineStage){case Kt.SPLINE_PRODUCER:break;case Kt.SPLINE_INTERPOLATOR:this.splineInterpolator.keepAllData=!0;break;case Kt.BRUSH_APPLIER:this.brushApplier.keepAllData=!0;break;case Kt.CONVEX_HULL_CHAIN_PRODUCER:this.convexHullChainProducer.keepAllData=!0;break;case Kt.POLYGON_MERGER:this.polygonMerger.keepAllData=!0;break;case Kt.POLYGON_SIMPLIFIER:this.polygonSimplifier.keepAllData=!0;break;default:throw console.warn(this.lastPipelineStage),new Error("[InkBuilderSettings] Invalid lastPipelineStage found")}if(this.lastPipelineStage==Kt.POLYGON_SIMPLIFIER&&(console.warn("[InkBuilderSettings] Pipeline stage POLYGON_SIMPLIFIER is deprecated. POLYGON_MERGER stage is recommended as last stage."),this.polygonSimplifier.epsilon=e.epsilon||.1),e.keepAllData){e.keepAllData.includes(this.lastPipelineStage)&&(console.warn(`[InkBuilderSettings] keepAllData contains last pipeline stage ${this.lastPipelineStage}. Duplicate is dropped.`),e.keepAllData.remove(this.lastPipelineStage)),e.keepAllData.includes(Kt.PATH_PRODUCER)&&(console.warn(`[InkBuilderSettings] keepAllData contains stage ${Kt.PATH_PRODUCER}, sensor input is accessible through InputDevice output - SensorData. Dropped from keepAllData.`),e.keepAllData.remove(Kt.PATH_PRODUCER)),e.keepAllData.includes(Kt.SPLINE_PRODUCER)&&(console.warn(`[InkBuilderSettings] keepAllData contains stage ${Kt.SPLINE_PRODUCER}. Use getSpline() method to acceess spline data. Dropped from keepAllData.`),e.keepAllData.remove(Kt.SPLINE_PRODUCER));for(let t of e.keepAllData){if(this.excludedPipelineStages.includes(t))throw new Error(`[InkBuilderSettings] keepAllData contains stage ${t}, configured as stage in excludedPipelineStages.`);switch(t){case Kt.SMOOTHER:this.smoother.keepAllData=!0;break;case Kt.SPLINE_INTERPOLATOR:this.splineInterpolator.keepAllData=!0;break;case Kt.BRUSH_APPLIER:this.brushApplier.keepAllData=!0;break;case Kt.CONVEX_HULL_CHAIN_PRODUCER:this.convexHullChainProducer.keepAllData=!0;break;default:throw console.warn(t),new Error("Invalid stage found")}}this.#p=e.keepAllData}else this.#p=[];if(e.pathPointCalculator&&(this.calculator=e.pathPointCalculator,this.pathProducer.pathPointCalculator=e.pathPointCalculator),!e.layout)throw new Error("[InkBuilderSettings] layout property is required");{let t=e.pathPointProps||{};if(this.layout=e.layout,this.brush instanceof $e){if(this.layout.includes(U.Property.RED))throw new Error("RED layout channel is not supported for non particles strokes");if(this.layout.includes(U.Property.GREEN))throw new Error("GREEN layout channel is not supported for non particles strokes");if(this.layout.includes(U.Property.BLUE))throw new Error("BLUE layout channel is not supported for non particles strokes");if(this.layout.includes(U.Property.ALPHA))throw new Error("ALPHA layout channel is not supported for non particles strokes")}if(!this.layout.includes(U.Property.RED)&&isNaN(t.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(U.Property.GREEN)&&isNaN(t.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(U.Property.BLUE)&&isNaN(t.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(U.Property.ALPHA)&&isNaN(t.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=t}this.configured=!0}add(e,t){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(!e.phase)throw new Error("SensorPoint phase is not found");this.phase=e.phase;let r,i=new tr(e);t&&(this.prediction?r=new tr(t):console.warn("Prediction sensor point is available, but ignored, prediction is disabled")),this.device&&(this.phase==Rt.Phase.BEGIN&&this.device.openStream(e),this.device.add(i),this.phase==Rt.Phase.END&&(this.sensorData=this.device.closeStream()));let s=this.pathProducer.add(this.phase,i,r);this.pathSegment.add(this.phase,s.added,s.predicted)}ignore(e){if(!e.phase)throw new Error("SensorPoint phase is not found");this.device&&e&&e.phase==Rt.Phase.UPDATE&&this.device.add(new tr(e),!0)}build(){throw new Error("InkBuilderAbstract.build() is abstract and should be implemented")}processSegment(e,t,r){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.#p.length)return;let e={};for(let t of this.#p)switch(t){case Kt.SMOOTHER:e.smoother=this.smoother.allData;break;case Kt.SPLINE_INTERPOLATOR:e.interpolatedSpline=this.splineInterpolator.allData;break;case Kt.BRUSH_APPLIER:e.shapesPath=this.brushApplier.allData;break;case Kt.CONVEX_HULL_CHAIN_PRODUCER:e.convexPath=this.convexHullChainProducer.allData;break;default:throw console.warn(t),new Error("Invalid stage found")}return e}getInkPath(){let e;switch(this.lastPipelineStage){case Kt.SPLINE_PRODUCER:return void console.warn("Pipeline stage SPLINE_PRODUCER is configured as lastPipelineStage. Ink Path is a result from Spline processing.");case Kt.SPLINE_INTERPOLATOR:e=this.splineInterpolator.allData;break;case Kt.BRUSH_APPLIER:e=this.brushApplier.allData;break;case Kt.CONVEX_HULL_CHAIN_PRODUCER:e=this.convexHullChainProducer.allData;break;case Kt.POLYGON_MERGER:e=this.polygonMerger.allData;break;case Kt.POLYGON_SIMPLIFIER:e=this.polygonSimplifier.allData;break;default:throw console.warn(this.lastPipelineStage),new Error("Invalid lastPipelineStage found")}if(this.concatSegments){let t;this.lastPipelineStage!=Kt.POLYGON_MERGER&&this.lastPipelineStage!=Kt.POLYGON_SIMPLIFIER||(t=this.polygonMerger.process(e)),this.lastPipelineStage==Kt.POLYGON_SIMPLIFIER&&(t=this.polygonSimplifier.process(t)),t&&(e=new Gt(t))}return e}abort(){this.device&&this.device.closeStream(!0),this.reset()}reset(e){this.pointerID=e,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}}nr.Phase=Rt.Phase;class or extends nr{constructor(){super(),this.convexHullChainProducer=new Yt}build(){let e=this.buildSegment();return e.phase=this.phase,e.pointerID=this.pointerID,this.onComplete&&this.onComplete(e),this.phase==Jt.END&&(delete this.phase,delete this.pipeline),e}buildSegment(){let e={};return this.pathSegment.accumulatedAddition.length>0&&(e.added=this.processSegment(this.pathSegment.accumulatedAddition,Qt.ADDITION,this.pathSegment.last),e.pipeline=this.pipeline,e.added&&(e.added.segment=!0)),this.prediction&&this.pathSegment.lastPrediction.length>0&&(e.predicted=this.processSegment(this.pathSegment.lastPrediction,Qt.PREDICTION,this.pathSegment.last),e.predicted&&(e.predicted.segment=!0)),this.pathSegment.reset(),e}processSegment(e,t,r){if(this.excludedPipelineStages.includes(Kt.SMOOTHER)||(e=this.smoother.process(e,t,r)),e=this.splineProducer.process(e,t,r))return this.lastPipelineStage==Kt.SPLINE_PRODUCER?e:this.processSpline(e,t,r)}processSpline(e,t=Qt.PROCESSOR,r=!0){t==Qt.ADDITION&&(this.pipeline={}),t==Qt.ADDITION&&(this.pipeline.spline=e);let i,s=this.splineInterpolator.process(e,t,r);if(this.lastPipelineStage==Kt.SPLINE_INTERPOLATOR)return s;if(s)return t==Qt.ADDITION&&(this.pipeline.interpolatedSpline=s),s=this.brushApplier.process(s,t,r),this.lastPipelineStage==Kt.BRUSH_APPLIER?s:(t==Qt.ADDITION&&(this.pipeline.shapesPath=s),s=this.convexHullChainProducer.process(s,t,r),this.lastPipelineStage==Kt.CONVEX_HULL_CHAIN_PRODUCER?s:(t==Qt.ADDITION&&(this.pipeline.convexPath=s),t==Qt.PREDICTION?s:this.excludedPipelineStages.includes(Kt.POLYGON_MERGER)||(i=this.polygonMerger.process(s,t,r),this.lastPipelineStage!=Kt.POLYGON_MERGER)?(this.excludedPipelineStages.includes(Kt.POLYGON_SIMPLIFIER)||(i=this.polygonSimplifier.process(i,t,r)),new Gt(i)):new Gt(i)));if(t==Qt.PROCESSOR)throw new Error("InkBuilder processSpline failed for spline",e)}}class ar{constructor(){this.queue=Promise.resolve(),this.thenables=[]}then(e,t,r){return this.thenables.push(e),this.queue=this.queue.then(((...t)=>(this.thenables.shift(),e.canceled?Promise.resolve():e(...t)))),t&&this.then((e=>t(e,r))),this}catch(e){return this.queue=this.queue.catch(e),this}cancel(){this.thenables.forEach((e=>e.canceled=!0))}isEmpty(){return 0==this.thenables.length}static async serial(e,t){let r=new ar;return e.forEach(((e,i)=>r.then(e,t,i))),r.queue}}class lr extends nr{constructor(){super(),this.convexHullChainProducer=new Ht,Object.defineProperty(this,"closed",{get:()=>this.convexHullChainProducer.closed,enumerable:!0}),this.queue=new ar}async open(){await this.convexHullChainProducer.open()}close(){this.convexHullChainProducer.close()}onComplete(e){throw new Error("InkBuilderAbstract.onComplete(pathSegment) is abstract and should be implemented")}build(){if(this.buildPhase&&this.phase!=Jt.END)return;let e=this.phase;this.queue.then((()=>(this.buildPhase=e,this.buildSegment()))).then((t=>{this.buildPhase=null,t.phase=e,t.pointerID=this.pointerID,this.onComplete(t),e==Jt.END&&(delete this.phase,delete this.pipeline)}))}async buildChain(){let e=await this.buildSegment();return e.phase=this.phase,e.pointerID=this.pointerID,this.onComplete(e),this.phase==Jt.END&&delete this.phase,e}async buildSegment(){let e={};return this.pathSegment.accumulatedAddition.length>0&&(e.added=await this.processSegment(this.pathSegment.accumulatedAddition,Qt.ADDITION,this.pathSegment.last),e.pipeline=this.pipeline,e.added&&(e.added.segment=!0)),this.prediction&&this.pathSegment.lastPrediction.length>0&&(e.predicted=await this.processSegment(this.pathSegment.lastPrediction,Qt.PREDICTION,this.pathSegment.last),e.predicted&&(e.predicted.segment=!0)),this.pathSegment.reset(),e}async processSegment(e,t,r){if(this.excludedPipelineStages.includes(Kt.SMOOTHER)||(e=this.smoother.process(e,t,r)),e=this.splineProducer.process(e,t,r))return this.lastPipelineStage==Kt.SPLINE_PRODUCER?e:this.processSpline(e,t,r)}async processSpline(e,t=Qt.PROCESSOR,r=!0){t==Qt.ADDITION&&(this.pipeline={}),t==Qt.ADDITION&&(this.pipeline.spline=e);let i,s=this.splineInterpolator.process(e,t,r);if(this.lastPipelineStage==Kt.SPLINE_INTERPOLATOR)return s;if(s)return t==Qt.ADDITION&&(this.pipeline.interpolatedSpline=s),s=this.brushApplier.process(s,t,r),this.lastPipelineStage==Kt.BRUSH_APPLIER?s:(t==Qt.ADDITION&&(this.pipeline.shapesPath=s),s=await this.convexHullChainProducer.process(s,t,r),this.lastPipelineStage==Kt.CONVEX_HULL_CHAIN_PRODUCER?s:(t==Qt.ADDITION&&(this.pipeline.convexPath=s),t==Qt.PREDICTION?s:this.excludedPipelineStages.includes(Kt.POLYGON_MERGER)||(i=this.polygonMerger.process(s,t,r),this.lastPipelineStage!=Kt.POLYGON_MERGER)?(this.excludedPipelineStages.includes(Kt.POLYGON_SIMPLIFIER)||(i=this.polygonSimplifier.process(i,t,r)),new Gt(i)):new Gt(i)));if(t==Qt.PROCESSOR)throw new Error("InkBuilderAsync processSpline failed for spline",e)}abort(){this.buildPhase=null,this.queue.cancel(),super.abort()}}let hr,dr,cr,pr;class ur extends P{#t;#n;#u;#f;#m;#g=ur.RenderMode.SOURCE_OVER;#y;#b=ur.CompressionType.AUTO;constructor(e,t,r,i){super(t.id),t.id||(t.id=this.id),this.#f=i;let s=new Re(t.layout,t.pointProps);Object.defineProperty(this,"target",{get:()=>console.warn("Stroke 'target' property is deprecated. Do not affects Stroke behaviour."),set:e=>console.warn("Stroke 'target' property is deprecated. Do not affects Stroke behaviour.")});let n=!0;Object.defineProperty(this,"layout",{value:t.layout,enumerable:!0}),Object.defineProperty(this,"points",{get:()=>t.points,enumerable:!0}),Object.defineProperty(this,"pointProps",{value:t.pointProps,enumerable:!0}),Object.defineProperty(this,"style",{value:s.style,enumerable:!0}),Object.defineProperty(this,"ts",{value:t.ts,enumerable:!0}),Object.defineProperty(this,"tf",{value:t.tf,enumerable:!0}),Object.defineProperty(this,"stride",{value:t.stride,enumerable:!0}),Object.defineProperty(this,"length",{value:t.length,enumerable:!0}),Object.defineProperty(this,"segmentsCount",{value:t.segmentsCount,enumerable:!0}),Object.defineProperty(this,"color",{get:()=>s.style.color,set:e=>{t.color=e,this.#n&&(this.#n.color=e)},enumerable:!0}),Object.defineProperty(this,"sensorData",{get:()=>this.#f,set:e=>{if(this.#f)throw new Error("sensorData is immutable");this.#f=e}}),Object.defineProperty(this,"spline",{value:t,enumerable:!0}),Object.defineProperty(this,"path",{get:()=>(this.#n||this.buildPath(),this.#n),set:e=>{this.#n=e,this.#n instanceof Nt&&(this.#n.style=s.style),this.#u=null},enumerable:!0}),Object.defineProperty(this,"bounds",{get:()=>(this.#u||(this.#u=this.path.bounds),this.matrix?this.#u.transform(this.matrix).ceil():this.#u),set:e=>this.#u=e,enumerable:!0}),Object.defineProperty(this,"descriptor",{value:{brush:{}},enumerable:!0}),Object.defineProperty(this,"brush",{get:()=>(e||(e=this.descriptor.brush.value),e),set:r=>{if(n||(this.path=null),"string"==typeof r?r=new ce(r):r instanceof $e||r instanceof rt?r=new ce(r.name,r):r instanceof ce||(r=new ce(r.name,r.value)),r instanceof rt&&!t.randomSeed)throw new Error("Spline do not provides randomSeed. Raster rendering requires it.");e=null,this.descriptor.brush=r},enumerable:!0}),Object.defineProperty(this,"randomSeed",{get:()=>this.#m,set:e=>{if(this.#m)throw new Error("randomSeed is immutable");this.#m=e},enumerable:!0}),Object.defineProperty(this,"renderMode",{get:()=>this.#g,set:e=>{if(!e)throw new Error("Stroke renderMode is required");if(!M.isValidURL(e))throw new Error(`The renderMode ${e} is not a well formed URI`);this.#g=e}}),Object.defineProperty(this,"blendMode",{get:()=>ur.RenderMode.getBlendMode(this.#g),set:e=>{if(!this.blendMode)throw new Error(`Override user defined renderMode '${this.#g}' is not allowed.`);this.#g=ur.RenderMode.get(e)}}),Object.defineProperty(this,"precisionSchema",{get:()=>this.#y,set:e=>{if(this.#y)throw new Error("precisionSchema is immutable, precisionSchema.update(schema) is an alternative");if(e){if(!(e instanceof xt))throw new Error("Expected precisionSchema type is PrecisionSchema");this.#y=e,this.#b=ur.CompressionType.COMPUTED}else this.#b=ur.CompressionType.NONE}}),Object.defineProperty(this,"compressionType",{get:()=>this.#b,set:e=>{if(!e)throw new Error("Stroke compressionType is required");if(this.#b==ur.CompressionType.COMPUTED&&e==ur.CompressionType.NONE)throw new Error("compressionType NONE is not applicable for compressed stroke");this.#b=e}}),Object.defineProperty(this,"uri",{get:()=>(this.#t||(this.#t=K.createStrokeURI(this.id)),this.#t),enumerable:!0}),this.brush=e,this.path=r,this.sensorDataOffset=0,this.sensorDataMapping=[],n=!1}buildPath(){if(this.pathProceessInProgress)throw new Error("Init process in progress. Await init stroke.");hr||(hr=new or),hr.configure(this.buildInkBuilderSettings()),this.path=hr.processSpline(this.spline)}async init(e){if(this.pathProceessInProgress=!0,dr||(dr=new lr,dr.closed&&await dr.open()),dr.configure(this.buildInkBuilderSettings(e)),this.path=await dr.processSpline(this.spline),Object.keys(dr.allData).length>0){let{interpolatedSpline:e,shapesPath:t,convexPath:r}=dr.allData;this.pipeline={},e&&(this.pipeline.interpolatedSpline=e),t&&(this.pipeline.shapesPath=t),r&&(this.pipeline.convexPath=r)}delete this.pathProceessInProgress}buildInkBuilderSettings(e){return ur.onPipeline?ur.onPipeline(this):Object.assign({},{brush:this.brush,layout:this.layout,pathPointProps:this.pointProps},e)}invalidateBounds(){this.#u=null}clone(e=!0,t=!1){let r;this.#n&&(r=e?this.#n:this.#n.clone());let i=this.spline.clone();t&&(i.id=this.id);let s=new ur(this.descriptor.brush,i,r,this.sensorData);return s.randomSeed=this.#m,s.renderMode=this.#g,s.sensorDataOffset=this.sensorDataOffset,s.sensorDataMapping=this.sensorDataMapping.clone(),s}getSensorPoint(e){if(e>=this.length||e<0)throw new Error(`Index ${e} out of range - (0, ${this.length-1})`);let t;if(0==this.sensorDataOffset&&e>0&&e--,this.sensorData){let r=this.sensorData.inkStream;if(r){let i;this.sensorDataMapping.length>0?i=e>=this.sensorDataMapping.length?this.sensorDataMapping.last:this.sensorDataMapping[e]:(i=this.sensorDataOffset+e,i>=r.length&&(i=r.length-1)),t=r.get(i),t.index=i,t.timespan=t.timestamp,t.timestamp+=this.sensorData.created}}return t}getPoint(e){return this.spline.getPoint(e)}setPoint(e,t){let r=e*this.stride;this.layout.forEach(((e,i)=>this.points[r+i]=t.getProperty(e)))}pointAt(e){return this.getPoint(e)}getSegment(e){return this.spline.getSegment(e)}getAverageWidth(){let e=0;if(this.layout.includes(U.Property.SIZE)){let t=0;for(let e=0;e<this.length;e++)t+=this.getPointRef(e).size;e=t/this.length}else e=this.pointProps.size;return e}split(e){let t=e.map((e=>this.slice(e)));return t.includes(this)?void 0:t}slice(e){if(0==e.pointIndexStart&&e.pointIndexEnd+1==this.length&&e.ts==this.ts&&e.tf==this.tf)return this;{let t=this.spline.slice(e),r=new ur(this.descriptor.brush,t,void 0,this.sensorData);if(r.randomSeed=this.#m,r.renderMode=this.#g,this.sensorData){let t=e.pointIndexStart;if(0==this.sensorDataOffset&&e.pointIndexStart>0&&(t=e.pointIndexStart-1),r.sensorDataOffset=this.sensorDataOffset+t,this.sensorDataMapping.length>0){let i;i=e.pointIndexEnd>this.sensorDataMapping.length?this.sensorDataMapping.length:0==r.sensorDataOffset?e.pointIndexEnd:e.pointIndexEnd+1,r.sensorDataMapping=this.sensorDataMapping.slice(t,i)}else r.sensorDataMapping=[]}return r}}transform(e){if(e||(e=this.matrix,this.matrix=null),e){if(this.spline.transform(e),this.#n&&this.path.transform(e),this.pipeline){let{interpolatedSpline:t,shapesPath:r,convexPath:i}=this.pipeline;t&&t.transform(e),r&&r.transform(e),i&&i.transform(e)}this.#b!=ur.CompressionType.NONE&&(this.#y=void 0,this.#b=ur.CompressionType.AUTO),this.#u=null}}setTransform(e){this.matrix=e}static createInstance(e,t,r,i={},s,n=0,o=1){let a=i.id,l=i.color;a&&delete i.id,l&&(delete i.color,i=Object.assign({},i),r.includes(U.Property.RED)||(i.red=l.red),r.includes(U.Property.GREEN)||(i.green=l.green),r.includes(U.Property.BLUE)||(i.blue=l.blue),r.includes(U.Property.ALPHA)||(i.alpha=l.alpha));let h=Dt.createSharedInstance(r,t,i,n,o);h.id=a;let d=new ur(e,h);return d.randomSeed=s,d}static validatePath(e){if(!e)return!1;if(0==e.length)return!1;if(e instanceof Gt)return!0;if(Array.isArray(e))throw new Error("path should be instance of InkPath2D");let t=!1,r=0,i=!1,{size:s,red:n,green:o,blue:a,alpha:l}=e.pointProps;if(!(e instanceof Nt)){let t=e.points.length,s=e.layout.length;i=0==t||t<4*s,r=t%s}return 0!=r?console.error(`The points array (length: ${e.points.length}) does not refer to provided layout (${e.layout.map((e=>e.name)).join(", ")})`):i?console.error("Less than needed minimum of points passed (At least 4 points are needed to define a path)!"):!e.layout.includes(U.Property.SIZE)&&isNaN(s)?console.error("Either the size property must be set or the path layout must include a SIZE property"):!e.layout.includes(U.Property.RED)&&isNaN(n)?console.error("Either the color property must be set or the path layout must include a RED property"):!e.layout.includes(U.Property.GREEN)&&isNaN(o)?console.error("Either the color property must be set or the path layout must include a GREEN property"):!e.layout.includes(U.Property.BLUE)&&isNaN(a)?console.error("Either the color property must be set or the path layout must include a BLUE property"):!e.layout.includes(U.Property.ALPHA)&&isNaN(l)?console.error("Either the color property must be set or the path layout must include a ALPHA property"):t=!0,t}static decodeInkPath(e){if("InkPath2D"==e.type)return Gt.fromJSON(e);if("InterpolatedSpline"==e.type)return Nt.fromJSON(e);throw new Error(`Decode ink path faild. Cannot identify type: ${e.type}`)}}ur.RenderMode=Object.assign({},...Object.keys(Ve).map((e=>({[e]:`will://rasterization/3.0/blend-mode/${M.getPropName(e,!0)}`})))),ur.RenderMode.get=e=>ur.RenderMode[M.getEnumValueName(e.replace(/-/g,"_"))],ur.RenderMode.getBlendMode=e=>Ve[Object.keys(ur.RenderMode).filter((t=>ur.RenderMode[t]==e)).first],ur.Target={},Object.defineProperty(ur.Target,"2D",{get:()=>console.warn("Stroke 'Target[2D]' enum is deprecated")}),Object.defineProperty(ur.Target,"GL",{get:()=>console.warn("Stroke 'Target[GL]' enum is deprecated")}),Object.defineEnum(ur,"CompressionType",["AUTO","NONE","COMPUTED"]);class fr{constructor(){let e;this.statistics={},this.statisticCounts={},Object.defineProperty(this,"calculator",{get:()=>e,set:t=>{if(e&&!(e instanceof It))throw new Error("calculator should be instance of PrecisionCalculator");e=t},enumerable:!0})}determinePrecisions(e){this.reset();for(let t of e)this.updatePrecisionSchema(t);this.printStats()}updatePrecisionSchema(e){let t=this.determinePrecisionSchema(e);e.precisionSchema?e.precisionSchema.update(t):e.precisionSchema=t}determinePrecisionSchema(e){if(e.compressionType!=ur.CompressionType.AUTO)return;if(!this.calculator)throw new Error("PrecisionDetector calculator property is required");let t=Number.MAX_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER,i=Number.MAX_SAFE_INTEGER,s=Number.MAX_SAFE_INTEGER,n=Number.MAX_SAFE_INTEGER;for(let o of e.layout){let a,l=e.spline.getChannelData(o),h=this.calculator.calculatePrecision(l,o);switch(o){case U.Property.X:case U.Property.Y:case U.Property.Z:a=fr.StatType.POSITION,t=Math.min(h,t);break;case U.Property.SIZE:a=fr.StatType.SIZE,r=Math.min(h,r);break;case U.Property.ROTATION:a=fr.StatType.ROTATION,i=Math.min(h,i);break;case U.Property.SCALE_X:case U.Property.SCALE_Y:case U.Property.SCALE_Z:a=fr.StatType.SCALE,s=Math.min(h,s);break;case U.Property.OFFSET_X:case U.Property.OFFSET_Y:case U.Property.OFFSET_Z:a=fr.StatType.OFFSET,n=Math.min(h,n);break;default:continue}if(this.debug){let e=vt.calculateError(l,h);this.addSampleStatistics(a,h,e,Math.min(...l),Math.max(...l))}}t==Number.MAX_SAFE_INTEGER&&(t=0),r==Number.MAX_SAFE_INTEGER&&(r=0),i==Number.MAX_SAFE_INTEGER&&(i=0),s==Number.MAX_SAFE_INTEGER&&(s=0),n==Number.MAX_SAFE_INTEGER&&(n=0);let o=xt.encode({position:t,size:r,rotation:i,scale:s,offset:n});return new xt(o)}addSampleStatistics(e,t,r,i,s){if(!this.debug)return;e!=fr.StatType.TOTAL&&this.addSampleStatistics(fr.StatType.TOTAL,t,r,i,s);let n=e.name;n in this.statistics||(this.statistics[n]={},this.statisticCounts[n]=0),t in this.statistics[n]||(this.statistics[n][t]={samplesCount:0,totalError:0,minError:Number.MAX_SAFE_INTEGER,maxError:0,sampleMinVal:Number.MAX_SAFE_INTEGER,sampleMaxVal:Number.MIN_SAFE_INTEGER}),this.statistics[n][t].samplesCount+=1,this.statistics[n][t].totalError+=r,this.statistics[n][t].minError=Math.min(this.statistics[n][t].minError,r),this.statistics[n][t].maxError=Math.max(this.statistics[n][t].maxError,r),this.statistics[n][t].sampleMinVal=Math.min(this.statistics[n][t].sampleMinVal,i),this.statistics[n][t].sampleMaxVal=Math.max(this.statistics[n][t].sampleMaxVal,s),this.statisticCounts[n]+=1}printStats(){this.debug&&(Object.keys(this.statistics).forEach((e=>{Object.values(this.statistics[e]).forEach((t=>{t.meanTotalError=t.samplesCount>0?t.totalError/t.samplesCount:NaN,t.usage=this.statisticCounts[e]>0?t.samplesCount/this.statisticCounts[e]*100:NaN}));let t=Object.keys(this.statistics[e]).sort(((e,t)=>e>t));console.log("***********************************************************************"),t.forEach((t=>{let r=this.statistics[e][t];console.log(`Stat Type: ${e} | Precision: ${t}`),console.log(` -> Count: ${r.samplesCount} (${r.usage}%)`),console.log(` -> Min/Max Error: ${r.minError} / ${r.maxError}`),console.log(` -> Sample Min/Max Value: ${r.sampleMinVal} / ${r.sampleMaxVal}`),console.log(` -> TotalError: ${r.totalError} / ${r.meanTotalError} (mean)`)}))})),console.log("***********************************************************************"))}reset(){this.statistics={},this.statisticCounts={}}}Object.defineEnum(fr,"StatType",["TOTAL","POSITION","SIZE","ROTATION","SCALE","OFFSET"]);class mr{constructor(e,t=mr.Type.UNKNOWN,r={}){this.uri=e,this.type=t,this.ontologyType,this.instance,this.internalID=r.internalID,this.externalModelID=r.modelID,this.isGloballyUnique=!!r.isGloballyUnique,this.belongsToCurrentModel=!!r.belongsToCurrentModel,this.triples=[],this.referencedEntities=[],this.referencedByEntities=[]}printDebugInfo(e=""){console.log(`${e}----------------------------------------------------------------`),console.log(`${e}EntityURI: ${this.uri}`),console.log(`${e}Type: ${this.type}`),console.log(`${e}OntologyType: ${this.ontologyType}`),console.log(`${e}InternalEntityID: ${this.internalID}`),console.log(`${e}ExternalModelID: ${this.externalModelID}`),console.log(`${e}EntityInstance:`,this.instance),console.log(`${e}IsGloballyUnique: ${this.isGloballyUnique}`),console.log(`${e}BelongsToCurrentModel: ${this.belongsToCurrentModel}`),console.log(`${e}ReferencedEntities: ${this.referencedEntities.length}`),this.referencedEntities.forEach((t=>console.log(`${e} -> ${t.uri}`))),console.log(`${e}ReferencedByEntities: ${this.referencedByEntities.length}`),this.referencedByEntities.forEach((t=>console.log(`${e} -> ${t.uri}`)))}}Object.defineEnum(mr,"Type",["UNKNOWN","NODE","STROKE","NAMED_ENTITY"]);class gr{constructor(e){this.model=e,this.entities={},this.entityDetector={[mr.Type.NODE]:{regEx:new RegExp(/^(uim:node)(\/[a-zA-Z0-9-]{36})?(\/[a-zA-Z0-9-_]{1,})?\/([a-zA-Z0-9-]{36})(#chunk=[0-9]+,[0-9]+)?$/),entityIDGroupIndex:0,modelIDGroupIndex:2},[mr.Type.STROKE]:{regEx:new RegExp(/^(uim:stroke)(\/[a-zA-Z0-9-]{36})?(\/)([a-zA-Z0-9-]{36})$/),entityIDGroupIndex:4,modelIDGroupIndex:2},[mr.Type.NAMED_ENTITY]:{regEx:new RegExp(/^(uim:ne)(\/[a-zA-Z0-9-]{36})?(\/)([a-zA-Z0-9-]{36})$/),entityIDGroupIndex:0,modelIDGroupIndex:2}}}clean(){this.analyze(),this.cleanupInternals(),this.cleanupUnusedEntities()}analyze(){let e={};this.model.knowledgeGraph.forEach((t=>{let r=e[t.subject];r||(r=this.determineEntityBasedOnURI(t.subject),e[t.subject]=r),r.triples.includes(t)||r.triples.push(t)})),Object.values(e).forEach((e=>{if(e.internalID&&e.belongsToCurrentModel)switch(e.type){case mr.Type.NODE:e.instance=this.model.getNode(e.internalID);break;case mr.Type.STROKE:e.instance=this.model.getStroke(e.internalID)}})),Object.values(e).forEach((t=>{t.triples.forEach((r=>{let i=e[r.object];i&&(t.referencedEntities.includes(i)||t.referencedEntities.push(i),i.referencedByEntities.includes(t)||i.referencedByEntities.push(t))}));let r=t.triples.filter((e=>e.predicate==gr.CommonRDF.HAS_TYPE||"@"==e.predicate)).first;r&&(t.ontologyType=r.object)})),this.entities=e,this.debug&&this.printStats()}determineEntityBasedOnURI(e){let t=mr.Type.UNKNOWN,r={},i=Object.keys(this.entityDetector);for(let s of i){t=mr.Type[s];let i=this.entityDetector[s],n=i.regEx.exec(e);if(n){let e=n[i.entityIDGroupIndex],t=n[i.modelIDGroupIndex];if(!e)throw new Error("Failed to extract internal ID");t&&(t=t.substring(1)),r={internalID:e,externalModelId:t,isGloballyUnique:!!t,belongsToCurrentModel:!t||this.model.id&&this.model.id==t};break}}return new mr(e,t,r)}cleanupInternals(){let e=new Set,t=[mr.Type.NODE,mr.Type.STROKE];Object.values(this.entities).forEach((r=>{t.includes(r.type)&&r.belongsToCurrentModel&&!r.instance&&e.add(r.uri)})),e.size>0&&(this.debug&&console.log(`[KnowledgeGraphAnalyzer] Cleanup internals - ${e.size}: ${Array.from(e).join(", ")}`),this.model.knowledgeGraph.remove((t=>e.has(t.subject)||e.has(t.object))),this.analyze())}cleanupUnusedEntities(){let e=new Set;Object.values(this.entities).forEach((t=>{t.type!=mr.Type.NAMED_ENTITY||!t.belongsToCurrentModel||t.referencedByEntities.length>0||e.add(t.uri)})),e.size>0&&(this.debug&&console.log(`[KnowledgeGraphAnalyzer] Cleanup unused entities - ${e.size}: ${Array.from(e).join(", ")}`),this.model.knowledgeGraph.remove((t=>e.has(t.subject)||e.has(t.object))),this.analyze())}printStats(){let e=0,t=Object.values(this.entities);console.log(`[KnowledgeGraphAnalyzer] Print ${t.length} entities analysis`),t.forEach((r=>r.printDebugInfo(`[${++e}/${t.length}] `)))}}gr.CommonRDF={HAS_TYPE:"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",LOCALE:"http://ogp.me/ns#locale"},Object.defineProperty(globalThis,"DIGITAL_INK_DEBUG",{get:()=>cr,set:function(e){cr=e||{},B.debug=cr.InputListener,S.prototype.debug=cr.Pipeline,Xe.prototype.debug=cr.Pipeline,Ye.prototype.debug=cr.PathPointContext,ut.prototype.debug=cr.RTree,st.prototype.debug=cr.GL,yt.prototype.debug=cr.RIFF,Pt.prototype.debug=cr.RIFF,fr.prototype.debug=cr.PrecisionDetector,gr.prototype.debug=cr.KnowledgeGraphAnalyzer},enumerable:!0,configurable:!0});class yr extends zt{static WORKER_NAME="InkPathProvider";constructor(){super(yr.WORKER_NAME,yr.buildWorkerURL(),zt.WorkerType.CLASSIC),this.actions={}}static buildWorkerURL(){if(("undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("digital-ink-min.cjs",document.baseURI).href).contains("/wacom-src/"))return`/node_modules/digital-ink/workers/${yr.WORKER_NAME}.js`;if("function"!=typeof DedicatedWorkerGlobalScope){let e="undefined"==typeof __location?"undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("digital-ink-min.cjs",document.baseURI).href:__location;return e=e.substring(0,e.lastIndexOf("/")),e.endsWith("workers")||(e+="/workers"),e+=`/${yr.WORKER_NAME}`,"undefined"==typeof navigator?e+=".mjs":e+=".js",e}}async importBrushes(e){let t=this.nextID;return this.actions[t]={expected:this.workers.length},await this.broadcastMessage({action:"IMPORT_BRUSHES",actionID:t,brushes:e.map((e=>e.toJSON()))})}async build(e,t){if(0==e.length)return;let r=this.nextID;return this.actions[r]={settings:this.encodeSettings(t),strokes:e,queue:e.slice(),expected:e.length},this.updateProgress(0,e.length),await this.broadcast("BUILD",r)}encodeSettings(e){if(e)return(e=Object.assign({},e)).excludedPipelineStages&&(e.excludedPipelineStages=e.excludedPipelineStages.map((e=>e.name))),e.lastPipelineStage&&(e.lastPipelineStage=e.lastPipelineStage.name),e.keepAllData&&(e.keepAllData=e.keepAllData.map((e=>e.name))),e}buildRequestMessage(e,t){let r={action:e,actionID:t},i=this.actions[t];if("BUILD"!=e)throw new Error(`Unknow data action found: ${e}`);{let e=i.queue.shift();if(!e)return;e.spline.points.buffer instanceof ArrayBuffer&&this.transferables.push(e.spline.points.buffer),e.spline.encoding=de.Encoding.NONE,r.index=i.strokes.indexOf(e),r.brushName=e.brush.name,r.spline=e.spline.toJSON(),r.settings=i.settings}return r}recieve(e){let t=this.actions[e.actionID];switch(t.expected--,e.action){case"IMPORT_BRUSHES":break;case"BUILD":if(this.update(e.actionID,e.index,e.path,e.splineBuffer,e.pipeline),t.expected>0){let t=this.buildRequestMessage(e.action,e.actionID);t&&this.send(e.worker,t)}break;default:throw new Error(`Unknow data action found: ${e.action}`)}0==t.expected&&(delete this.actions[e.actionID],this.resolve(e.actionID))}update(e,t,r,i,s){let n=this.actions[e],o=n.strokes[t];i instanceof ArrayBuffer&&(o.spline.buffer=i),o.path=ur.decodeInkPath(r),s&&(s.interpolatedSpline&&(s.interpolatedSpline=Nt.fromJSON(s.interpolatedSpline)),s.shapesPath&&(s.shapesPath=Gt.fromJSON(s.shapesPath)),s.convexPath&&(s.convexPath=Gt.fromJSON(s.convexPath)),o.pipeline=s);let a=100*(n.strokes.length-n.expected)/n.strokes.length;this.updateProgress(a,n.expected,o)}updateProgress(e,t,r){}}class br extends Ze{get width(){return this.surface.width}get height(){return this.surface.height}constructor(e){super(),Object.defineProperty(this,"surface",{value:e.canvas,enumerable:!0}),Object.defineProperty(this,"ctx",{value:e,enumerable:!0}),Object.defineProperty(this,"renderingContext",{value:new ct(e),enumerable:!0}),Object.defineProperty(this,"bounds",{get:()=>new v(0,0,this.width,this.height),enumerable:!0}),this.ctx.getContextAttributes||(this.ctx.getContextAttributes=()=>({}))}clear(e,t){if(t){if(ve.isColor(e))throw new Error("`clear` first argument should be Rectangle")}else ve.isColor(e)&&(t=e,e=null);e||(e=this.bounds),this.ctx.clearRect(e.left,e.top,e.width,e.height),t&&(this.ctx.fillStyle=t.toString(),this.ctx.fillRect(e.left,e.top,e.width,e.height))}draw(e){return this.drawStroke(e.brush,e.path,e.color,e.matrix)}drawStroke(e,t,r,i){if(!ur.validatePath(t))return null;if(!(e instanceof $e))throw new Error("Incompatible brush found. It should be Brush2D instance.");i?this.matrix&&(i=this.matrix.multiply(i)):i=this.matrix;let s=t.bounds;if(s&&(i&&(s=s.transform(i)),s=s.ceil()),s=this.bounds.intersect(s),s){if(this.ctx.save(),i?this.ctx.setTransform(i.a,i.b,i.c,i.d,i.tx,i.ty):(this.ctx.rect(s.left,s.top,s.width,s.height),this.ctx.clip()),t instanceof Gt)this.renderingContext.fillShape(t,r),e.pattern&&this.renderingContext.fillShape(t,e.pattern);else{if(!(t instanceof Nt))throw new Error("drawStroke 'path' type missmatch, expected oneof(InkPath2D, InterpolatedSpline)");this.drawSpline(t,r)}this.ctx.restore()}return s}drawSpline(e,t){t||(t=e.color),this.ctx.fillStyle=`rgb(${t.red}, ${t.green}, ${t.blue})`;for(let t=0;t<e.length;t++){let r=e.getPointRef(t),i=r.size/2;this.ctx.beginPath(),this.ctx.arc(r.x,r.y,i,0,2*Math.PI),this.ctx.closePath(),this.ctx.fill()}}fill(e,t){let r;if(v.isRect(e))r=e;else{if("number"==typeof e[0]&&e.length%2==0&&(e=Le.createInstance(e)),e instanceof Le)e=new nt(e);else if(!(e instanceof nt))throw new Error("fill shape type missmatch, expected oneof(PolygonArray, Polygon, Rect)");r=e.bounds}return r=this.bounds.intersect(r),r&&(r=r.ceil(),v.isRect(e)?(this.ctx.fillStyle=t.toString(),this.ctx.fillRect(e.left,e.top,e.width,e.height)):(this.ctx.save(),this.ctx.rect(r.left,r.top,r.width,r.height),this.ctx.clip(),this.renderingContext.fillShape(e,t),this.ctx.restore())),r}blend(e,t={}){if(t.mode||(t.mode=Ve.SOURCE_OVER),t.transform&&t.destinationRect)throw new Error("`destinationRect` is not applicable with `transform`");if(t.sourceRect&&!t.destinationRect)throw new Error("With `sourceRect`, `destinationRect` is required");if(t.destinationRect&&!t.sourceRect)throw new Error("With `destinationRect`, `sourceRect`is required");t.rect&&(t.sourceRect=t.rect,t.destinationRect=t.rect),this.ctx.save(),t.transform?this.ctx.setTransform(t.transform.a,t.transform.b,t.transform.c,t.transform.d,t.transform.tx,t.transform.ty):t.clipRect&&(this.ctx.rect(t.clipRect.left,t.clipRect.top,t.clipRect.width,t.clipRect.height),this.ctx.clip()),this.ctx.globalCompositeOperation=t.mode,t.sourceRect&&t.destinationRect?this.ctx.drawImage(e.ctx.canvas,t.sourceRect.left,t.sourceRect.top,t.sourceRect.width,t.sourceRect.height,t.destinationRect.left,t.destinationRect.top,t.destinationRect.width,t.destinationRect.height):this.ctx.drawImage(e.ctx.canvas,0,0),this.ctx.restore()}createImageData(e,t,r){return new se(e,t,r)}getImageData(e){e||(e=this.bounds);let t=this.ctx.getImageData(e.x,e.y,e.width,e.height);return t.x=e.x,t.y=e.y,t}putImageData(e,t,r){if(!(e instanceof se))throw new Error("putImageData 'imageData' parameter is not instance of ImageData");(isNaN(t)||isNaN(r))&&(t=e.x||0,r=e.y||0),this.ctx.putImageData(e,t,r)}readPixels(e){return this.getImageData(e).data}writePixels(e,t){if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray))throw new Error("writePixels 'data' parameter is not instance of Uint8Array or Uint8ClampedArray");t||(t=this.bounds),e instanceof Uint8Array&&(e=new Uint8ClampedArray(e.buffer)),this.putImageData(this.createImageData(e,t.width,t.height),t.x,t.y)}getExportCanvas(e){let t=this.surface;return e&&(e=e.intersect(this.bounds).ceil(),t=new ne(e.width,e.height),t.getContext("2d").putImageData(this.getImageData(e),0,0)),t}resize(e,t){this.surface.width=e,this.surface.height=t}}class Er extends br{constructor(e){super(e)}createLayer(e,t){let r;r=e&&t?{width:e,height:t}:e&&e.width&&e.height?e:Er.getDefaultSize(this.width,this.height);let i=new ne(r.width,r.height);return new br(i.getContext("2d",this.ctx.getContextAttributes()))}static createInstance(e,t,r,i){if(!e||"function"!=typeof e.getContext)throw new Error("CanvasRenderingContext2D context provider is required");if(t>0&&r>0&&(e.width=t,e.height=r),!(e.width>0&&e.height>0))throw new Error("width and height are required and should be positive whole numbers");return new Er(e.getContext("2d",i))}}class Pr{constructor(e,t){this.canvas=e,this.options=t,this.layer=e.createLayer(t),this.preliminaryLayer=void 0,this.restart=!0,this.runtime=!1,this.brush=void 0,this.color=void 0,this.backgroundColor=ve.TRANSPERENT,this.blendMode=Ve.SOURCE_OVER,this.matrix=void 0,this.strokeBounds=void 0,this.updatedArea=void 0,Object.defineProperty(this,"settings",{get:()=>({brush:this.brush,color:this.color,backgroundColor:this.backgroundColor,blendMode:this.blendMode,matrix:this.matrix,randomSeed:this.initialRandomSeed}),enumerable:!0})}requestComposeLayer(){if(!this.restart)throw new Error("Operation is not supported for incomplete composition");let e=this.layer;return this.layer=this.canvas.createLayer(this.options),this.matrix&&this.layer.setTransform(this.matrix),this.reset(!0),e}configure(e){e.brush&&(this.brush=e.brush),e.color&&(this.color=e.color),e.backgroundColor&&(this.backgroundColor=e.backgroundColor),e.blendMode&&(this.blendMode=e.blendMode),"transform"in e&&this.setTransform(e.transform),this.restart=!0}setTransform(e){this.matrix=e,this.layer.setTransform(e),this.preliminaryLayer&&this.preliminaryLayer.setTransform(e)}draw(e,t=!1){e instanceof ur?(this.reset(!1),this.drawStroke(e),this.restart=!0):(this.restart&&this.reset(!0),this.drawSegment(e,t),t&&(this.restart=!0))}drawStroke(e){throw new Error("StrokeRenderer.drawStroke(stroke) should be implemented")}drawSegment(e,t=!1){throw new Error("StrokeRenderer.drawSegment(path, endStroke) should be implemented")}drawPreliminary(e){throw new Error("StrokeRenderer.drawPreliminary(path) should be implemented")}abort(){this.restart=!0}reset(e=!1){this.runtime=e,this.incompleteStrokeBounds=null,this.strokeBounds=null,this.updatedArea=null,this.preliminaryDirtyArea=null,this.layer.clear(this.backgroundColor),this.preliminaryLayer&&this.preliminaryLayer.clear(this.backgroundColor),this.restart=!1}validate(e){if(!this.brush)throw new Error("StrokeRenderer requires 'brush' to be configured");return e&&e.length>0}blendUpdatedArea(e){throw new Error("StrokeRenderer.blendUpdatedArea(layer) should be implemented")}blendStroke(e,t,r){throw new Error("StrokeRenderer.blendStroke(layer, dirtyArea, blendMode) should be implemented")}toStroke(e,t){throw new Error("StrokeRenderer.toStroke(builder) should be implemented")}}G.typeGL==G.TypeGL.STACK&&(G.commonJS?pr=require("gl"):console.warn(`Current env - ${G.type.name}, do not provides WebGL support`));var Ir=pr;var Sr=Ir?class{constructor(e=300,t=150){this.width=e,this.height=t}getContext(e="webgl",t){if(!this.context){let e=this.width,r=this.height;this.context=Ir(e,r,t),this.context.canvas=this;let i=this.context.getExtension("STACKGL_resize_drawingbuffer");Object.defineProperty(this,"width",{get:()=>e,set:t=>{e=t,i.resize(e,r)},enumerable:!0}),Object.defineProperty(this,"height",{get:()=>r,set:t=>{r=t,i.resize(e,r)},enumerable:!0})}return this.context}destroy(){if(this.context){this.context.getExtension("STACKGL_destroy_context").destroy(),delete this.context}}}:void 0;class wr{constructor(e){this.randomSeed=e||parseInt(Date.now()/1e3)}copyTo(e){e.randomSeed=this.randomSeed}}class xr extends We{constructor(e,t){super(e.inkGLContext,t),Object.defineProperty(this,"inkContext",{value:e,enumerable:!0}),Object.defineProperty(this,"bounds",{get:()=>v.fromGLRect(this.graphicsBounds),enumerable:!0})}clear(e,t){if(t){if(ve.isColor(e))throw new Error("`clear` first argument should be Rect")}else ve.isColor(e)?(t=e,e=null):t=ve.TRANSPERENT;let r;if(v.isRect(e)){if(!e.intersect(this.bounds))return;r=v.fromRect(e).toGLRect()}Array.isArray(e)||e instanceof Float32Array?this.fill(e,t,!1):(this.inkContext.setTarget(this,r),this.inkContext.clearColor(t)),r&&this.inkContext.disableTargetClipRect()}draw(e){let t,r=e.brush;return r instanceof rt?isFinite(e.randomSeed)&&(t=new wr(e.randomSeed)):t=e.color,this.drawStroke(r,e.path,t)}drawStroke(e,t,r){if(!ur.validatePath(t))return null;this.inkContext.setTarget(this);let i=this.inkContext.drawStroke(e,t,r);return v.fromGLRect(i)}fill(e,t,r=!0){if(v.isRect(e))e=Le.fromRect(e),e=new nt(e);else if("number"==typeof e[0]&&e.length%2==0&&(e=Le.createInstance(e)),e instanceof Le)e=new nt(e);else if(!(e instanceof nt))throw new Error("fill shape type missmatch, expected oneof(PolygonArray, Polygon, Rect)");this.inkContext.setTarget(this);let i=this.inkContext.fill(e,t,r);return v.fromGLRect(i)}blend(e,t={}){if(t.mode||(t.mode=Ve.SOURCE_OVER),t.rect&&!t.transform&&(t.sourceRect=t.rect,t.destinationRect=t.rect),t.transform&&t.destinationRect)throw new Error("`destinationRect` is not applicable with `transform`");if(t.sourceRect&&!t.destinationRect)throw new Error("With `sourceRect`, `destinationRect` is required");if(t.destinationRect&&!t.sourceRect)throw new Error("With `destinationRect`, `sourceRect`is required");if(this.inkContext.setTarget(this,v.isRect(t.clipRect)?v.fromRect(t.clipRect).toGLRect():void 0),"boolean"==typeof t.flipY&&(e.flipY=t.flipY),t.transform&&t.rect){let r=v.fromRect(t.rect).toGLRect().toQuad(),i=v.fromRect(t.rect).toGLRect().toQuad(t.transform);this.inkContext.drawLayer(e,r,i,t.mode)}else t.transform?this.inkContext.drawLayerWithTransform(e,t.transform,t.mode):t.sourceRect&&t.destinationRect?this.inkContext.drawLayer(e,v.fromRect(t.sourceRect).toGLRect().toQuad(),v.fromRect(t.destinationRect).toGLRect().toQuad(),t.mode):this.inkContext.drawLayerWithTransform(e,null,t.mode)}createImageData(e,t,r){return e instanceof Uint8Array&&(e=new Uint8ClampedArray(e.buffer)),new se(e,t,r)}getImageData(e,t=!1){e||(e=this.bounds);let r=this.createImageData(this.readPixels(e,t),e.width,e.height);return r.x=e.x,r.y=e.y,r}putImageData(e,t,r){if(!(e instanceof se))throw new Error("putImageData 'imageData' parameter is not instance of ImageData");(isNaN(t)||isNaN(r))&&(t=e.x||0,r=e.y||0),this.writePixels(e.data,new v(t,r,e.width,e.height))}readPixels(e,t){e&&(e=v.fromRect(e).toGLRect()),this.inkContext.setTarget(this);let r=this.inkContext.readPixels(e);if(t)for(let e=0;e<r.length;e+=4){let t=r[e+3];r[e]=parseInt(255*r[e]/t),r[e+1]=parseInt(255*r[e+1]/t),r[e+2]=parseInt(255*r[e+2]/t)}return r}writePixels(e,t){if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray))throw new Error("writePixels 'data' parameter is not instance of Uint8Array or Uint8ClampedArray");t&&(t=v.fromRect(t).toGLRect()),this.inkContext.setTarget(this),this.inkContext.writePixels(t,e)}getExportCanvas(e){e=e?e.intersect(this.bounds).ceil():this.bounds;let t=new ne(e.width,e.height);return t.getContext("2d").putImageData(this.getImageData(e,!0),0,0),t}}class vr extends xr{constructor(e){super(e,{display:!0,width:e.inkGLContext.gl.canvas.width,height:e.inkGLContext.gl.canvas.height,flipY:G.typeGL==G.TypeGL.WEB}),Object.defineProperty(this,"surface",{value:e.inkGLContext.gl.canvas,enumerable:!0}),Object.defineProperty(this,"ctx",{value:e.inkGLContext.gl,enumerable:!0}),Object.defineProperty(this,"MAX_SIZE",{value:this.ctx.getParameter(this.ctx.MAX_TEXTURE_SIZE),enumerable:!0});let t=this.ctx.getContextAttributes();if("function"==typeof requestAnimationFrame&&!t.preserveDrawingBuffer){let e=this.createLayer();Object.defineProperty(this,"backbuffer",{value:e,enumerable:!0});let t=r=>{this.present&&(delete this.present,super.blend(e,{mode:Ve.COPY})),this.frameID=requestAnimationFrame(t)};this.frameID=requestAnimationFrame(t)}}createLayer(e={}){let t=e.width,r=e.height;if(t&&r){if(t>this.MAX_SIZE)throw new Error(`Max width exceeded: ${t} found, ${this.MAX_SIZE} allowed`);if(r>this.MAX_SIZE)throw new Error(`Max height exceeded: ${r} found, ${this.MAX_SIZE} allowed`)}else{let t=vr.getDefaultSize(this.width,this.height);e.width=t.width,e.height=t.height}return new xr(this.inkContext,e)}clear(e,t){this.backbuffer?(this.backbuffer.clear(e,t),this.present=!0):super.clear(e,t)}draw(e,t){let r;return this.backbuffer?(r=this.backbuffer.draw(e,t),this.present=!0):r=super.draw(e,t),r}drawStroke(e,t,r){let i;return this.backbuffer?(i=this.backbuffer.drawStroke(e,t,r),this.present=!0):i=super.drawStroke(e,t,r),i}fill(e,t,r){let i;return this.backbuffer?(i=this.backbuffer.fill(e,t,r),this.present=!0):i=super.fill(e,t,r),i}blend(e,t){this.backbuffer?(this.backbuffer.blend(e,t),this.present=!0):super.blend(e,t)}readPixels(e,t){return this.backbuffer?this.backbuffer.readPixels(e,t):super.readPixels(e,t)}writePixels(e,t){this.backbuffer?(this.backbuffer.writePixels(e,t),this.present=!0):super.writePixels(e,t)}async toBlob(e=this.bounds,t,r){return this.backbuffer?await this.backbuffer.toBlob(e,t,r):await super.toBlob(e,t,r)}resize(e,t){super.resize(e,t),this.surface.width=e,this.surface.height=t}destroy(){this.delete(),he.instance&&he.instance.items.forEach((e=>{e instanceof rt&&e.ctx==this.ctx&&e.delete()}));let e=this.ctx.getExtension("WEBGL_lose_context");e&&e.loseContext()}delete(){"number"==typeof this.frameID&&cancelAnimationFrame(this.frameID),super.delete(),this.backbuffer&&this.backbuffer.delete()}deleteLater(){return super.deleteLater(),this.backbuffer&&this.backbuffer.deleteLater(),this}static createInstance(e,t,r,i){if(!e||"function"!=typeof e.getContext)throw new Error("WebGL context provider is required");if(t>0&&r>0&&(e.width=t,e.height=r),!(e.width>0&&e.height>0))throw new Error("width and height are required and should be positive whole numbers");let s=new st(e,i);return new vr(s)}}class Rr{constructor(e,t,r){let i,s;this.listeners=[];let n=(e,t)=>{Object.defineProperty(this,e,{get:()=>t,set:r=>{if(!r&&"object"!=e)throw new Error(`SemanticTriple ${e} is required`);t=r,s=i,i=void 0,this.listeners.slice().forEach((e=>e(s,this)))},enumerable:!0})};n("subject",e),n("predicate",t),n("object",r),Object.defineProperty(this,"hashCode",{get:()=>(i||(i=b(this.toString())),i),enumerable:!0}),this.subject=e,this.predicate=t,this.object=r}equals(e){return this.subject==e.subject&&this.predicate==e.predicate&&this.object==e.object}subsets(e){if(!e||!e.subject&&!e.predicate&&!e.object)throw new Error("Illegal partialStatement found: at least onoeof(subject, predicate, object) is required");let t=!0;return e.subject&&(t=this.subject==e.subject),t&&e.predicate&&(t=this.predicate==e.predicate),t&&e.object&&(t=this.object==e.object),t}addListener(e){this.listeners.push(e)}removeListener(e){this.listeners.remove(e)}toString(){return`triple(${this.subject}, ${this.predicate}, ${this.object})`}toJSON(){return{subject:this.subject,predicate:this.predicate,object:this.object}}static hashCode(e){return e instanceof Rr?e.hashCode:b(Rr.prototype.toString.call(e))}}class Tr extends Array{static get[Symbol.species](){return Array}constructor(...e){super();let t={};Object.defineProperty(this,"items",{value:t}),Object.defineProperty(this,"update",{value:(e,r)=>{delete t[e],this.items.hasOwnProperty(r.hashCode)?(r.removeListener(this.update),super.remove(r)):t[r.hashCode]=r}}),this.add(...e)}add(...e){for(let t of e)t instanceof Rr?this.push(t):this.addTriple(t.subject,t.predicate,t.object)}addTriple(e,t,r){this.push(new Rr(e,t,r))}push(...e){if(e.length>1)return void this.add(...e);let t=e[0];if(t instanceof Rr){let e=t.hashCode;this.items.hasOwnProperty(e)||(this.items[e]=t,super.push(t),t.addListener(this.update))}else this.addTriple(t.subject,t.predicate,t.object)}remove(...e){"function"==typeof e[0]&&(e=this.filter(e[0])),(e=e.map((e=>e instanceof Rr?e:this.items[Rr.hashCode(e)]))).forEach((e=>{e&&(e.removeListener(this.update),delete this.items[e.hashCode])})),super.remove(...e)}clear(){super.clear(),Object.keys(this.items).forEach((e=>{this.items[e].removeListener(this.update),delete this.items[e]}))}clone(){let e=new Tr;return this.forEach((t=>e.addTriple(t.subject,t.predicate,t.object))),e}search(e){return console.warn("TripleStore search method is deprecated. Use filter instead."),this.filter((t=>{let r=!0;return Object.keys(e).forEach((i=>{r=r&&t[i]==e[i]})),r}))}}let Ar=g?g.default||globalThis.protobuf:{};class Cr{static reservedViewNames=["main","sdm","hwr","ner"];constructor(e=Cr.Type.STROKE,t){if(e==Cr.Type.SENSOR_DATA)throw new Error("Sensor data trees are not supported yet");if(t){let e=/^[a-zA-Z][a-zA-Z0-9-_]{1,62}[a-zA-Z0-9]$/;if(!e.test(t))throw new Error(`Ink tree name "${t}" is not valid. Allowed symbols are ${e.toString()}.`)}else t=e==Cr.Type.STROKE?"main":"sdm";Object.defineProperty(this,"type",{value:e}),Object.defineProperty(this,"name",{get:()=>t,set:e=>{if(Cr.reservedViewNames.includes(t))throw new Error(`Tree name ${t} update is not allowed. Reserved names are immutable.`);if(Cr.reservedViewNames.includes(e))throw new Error(`Tree name ${e} is not allowed. It is reserved.`);let r=K.createNodeURISchema(this),i=K.createNodeURISchema(this,e);this.model.knowledgeGraph.forEach((e=>{e.subject.startsWith(r)&&(e.subject=e.subject.replace(r,i)),e.object.startsWith(r)&&(e.object=e.object.replace(r,i))})),this.model.views[e]=this.model.views[t],delete this.model.views[t],t=e},enumerable:!0}),Object.defineProperty(this,"uri",{get:()=>K.createTreeURI(t)})}}Object.defineEnum(Cr,"Type",["STROKE","SENSOR_DATA"]);class Or{static encodePathPointProperties(e,t){const r=t.$type;for(let i in r.fields){let r;if("color"==i)r=Or.rgba(e.red,e.green,e.blue,e.alpha);else{if(("size"==i||i.startsWith("scale"))&&1==e[i])continue;r=e[i]}isFinite(r)&&(t[i]=r)}return t}static decodePathPointProperties(e,t){if(!e)return;if(!t)throw new Error("Color property requires layout");const r=e.$type;let i={};for(let s in r.fields)if("color"==s){let r=Or.fromRGBA(e.color);t.includes(U.Property.RED)||(i.red=r.red),t.includes(U.Property.GREEN)||(i.green=r.green),t.includes(U.Property.BLUE)||(i.blue=r.blue),t.includes(U.Property.ALPHA)||(i.alpha=r.alpha)}else if(e.hasOwnProperty(s)){if(s.startsWith("scale")&&1==e[s])continue;i[s]=e[s]}return i}static rgba(e=0,t=0,r=0,i=0){return(255&e)<<24|(255&t)<<16|(255&r)<<8|255&(i=Math.round(255*i))}static fromRGBA(e=0){return{red:e>>24&255,green:e>>16&255,blue:e>>8&255,alpha:(255&e)/255}}}const Dr={evolution:["3.0.0","3.1.0"],"3.1.0":{schema:{nested:{UIM_3_1_0:{options:{optimize_for:"SPEED",java_multiple_files:!1,java_package:"com.wacom.ink.protobuf",java_outer_classname:"UIM_3_1_0",csharp_namespace:"Protobuf.WILL_3_1_0",swift_prefix:"WILL3_1_0"},nested:{BlendMode:{values:{SOURCE_OVER:0,DESTINATION_OVER:1,DESTINATION_OUT:2,LIGHTER:3,COPY:4,MIN:5,MAX:6}},Rectangle:{fields:{x:{type:"float",id:1},y:{type:"float",id:2},width:{type:"float",id:3},height:{type:"float",id:4}}},Matrix:{fields:{m00:{type:"float",id:1},m01:{type:"float",id:2},m02:{type:"float",id:3},m03:{type:"float",id:4},m10:{type:"float",id:5},m11:{type:"float",id:6},m12:{type:"float",id:7},m13:{type:"float",id:8},m20:{type:"float",id:9},m21:{type:"float",id:10},m22:{type:"float",id:11},m23:{type:"float",id:12},m30:{type:"float",id:13},m31:{type:"float",id:14},m32:{type:"float",id:15},m33:{type:"float",id:16}}},Interval:{fields:{fromIndex:{type:"uint32",id:1},toIndex:{type:"uint32",id:2},fromTValue:{type:"float",id:3},toTValue:{type:"float",id:4},id:{type:"bytes",id:100}}},PathPointProperties:{fields:{color:{type:"sint32",id:1},size:{type:"float",id:2},rotation:{type:"float",id:3},scaleX:{type:"float",id:4},scaleY:{type:"float",id:5},scaleZ:{type:"float",id:6},offsetX:{type:"float",id:7},offsetY:{type:"float",id:8},offsetZ:{type:"float",id:9}}},Property:{fields:{name:{type:"string",id:1},value:{type:"string",id:2}}},InkState:{values:{PLANE:0,HOVERING:1,IN_VOLUME:2,VOLUME_HOVERING:3}},InkSensorMetricType:{values:{LENGTH:0,TIME:1,FORCE:2,ANGLE:3,NORMALIZED:4,LOGICAL:5,DIMENSIONLESS:6}},InkInputProviderType:{values:{PEN:0,TOUCH:1,MOUSE:2,CONTROLLER:3}},InputContext:{fields:{id:{type:"bytes",id:1},environmentID:{type:"bytes",id:2},sensorContextID:{type:"bytes",id:3}}},Environment:{fields:{id:{type:"bytes",id:1},properties:{rule:"repeated",type:"Property",id:2}}},InkInputProvider:{fields:{id:{type:"bytes",id:1},type:{type:"InkInputProviderType",id:2},properties:{rule:"repeated",type:"Property",id:3}}},InputDevice:{fields:{id:{type:"bytes",id:1},properties:{rule:"repeated",type:"Property",id:2}}},SensorContext:{fields:{id:{type:"bytes",id:1},sensorChannelsContext:{rule:"repeated",type:"SensorChannelsContext",id:2}}},SensorChannelsContext:{fields:{id:{type:"bytes",id:1},channels:{rule:"repeated",type:"SensorChannel",id:2},samplingRateHint:{type:"uint32",id:3},latency:{type:"uint32",id:4},inkInputProviderID:{type:"bytes",id:5},inputDeviceID:{type:"bytes",id:6}}},SensorChannel:{fields:{id:{type:"bytes",id:1},type:{type:"string",id:2},metric:{type:"InkSensorMetricType",id:3},resolution:{type:"double",id:4},min:{type:"float",id:5},max:{type:"float",id:6},precision:{type:"uint32",id:7}}},InputContextData:{fields:{inputContexts:{rule:"repeated",type:"InputContext",id:1},inkInputProviders:{rule:"repeated",type:"InkInputProvider",id:2},inputDevices:{rule:"repeated",type:"InputDevice",id:3},environments:{rule:"repeated",type:"Environment",id:4},sensorContexts:{rule:"repeated",type:"SensorContext",id:5}}},ChannelData:{fields:{sensorChannelID:{type:"bytes",id:1},values:{rule:"repeated",type:"sint32",id:2}}},SensorData:{fields:{id:{type:"bytes",id:1},inputContextID:{type:"bytes",id:2},state:{type:"InkState",id:3},timestamp:{type:"uint64",id:4},dataChannels:{rule:"repeated",type:"ChannelData",id:5}}},InputData:{fields:{inputContextData:{type:"InputContextData",id:1},sensorData:{rule:"repeated",type:"SensorData",id:2}}},RotationMode:{values:{NONE:0,RANDOM:1,TRAJECTORY:2}},BrushPrototype:{fields:{coordX:{rule:"repeated",type:"float",id:1},coordY:{rule:"repeated",type:"float",id:2},coordZ:{rule:"repeated",type:"float",id:3},indices:{rule:"repeated",type:"uint32",id:4},shapeURI:{type:"string",id:5},size:{type:"float",id:6}}},VectorBrush:{fields:{name:{type:"string",id:1},prototype:{rule:"repeated",type:"BrushPrototype",id:2},spacing:{type:"float",id:3}}},RasterBrush:{fields:{name:{type:"string",id:1},spacing:{type:"float",id:2},scattering:{type:"float",id:3},rotationMode:{type:"RotationMode",id:4},shapeTexture:{rule:"repeated",type:"bytes",id:5},shapeTextureURI:{rule:"repeated",type:"string",id:6},fillTexture:{type:"bytes",id:7},fillTextureURI:{type:"string",id:8},fillWidth:{type:"float",id:9},fillHeight:{type:"float",id:10},randomizeFill:{type:"bool",id:11},blendMode:{type:"BlendMode",id:12}}},Brushes:{fields:{vectorBrushes:{rule:"repeated",type:"VectorBrush",id:1},rasterBrushes:{rule:"repeated",type:"RasterBrush",id:2}}},Stroke:{oneofs:{data:{oneof:["splineData","splineCompressed"]},properties:{oneof:["propertiesIndex","propertiesValue"]},brushURI:{oneof:["brushURIIndex","brushURIValue"]},renderModeURI:{oneof:["renderModeURIIndex","renderModeURIValue"]}},fields:{id:{type:"bytes",id:1},precisions:{type:"sint32",id:2},startParameter:{type:"float",id:3},endParameter:{type:"float",id:4},splineData:{type:"SplineData",id:5},splineCompressed:{type:"SplineCompressed",id:6},propertiesIndex:{type:"uint32",id:7},propertiesValue:{type:"PathPointProperties",id:8},brushURIIndex:{type:"uint32",id:9},brushURIValue:{type:"string",id:10},renderModeURIIndex:{type:"uint32",id:11},renderModeURIValue:{type:"string",id:12},randomSeed:{type:"uint32",id:13},sensorDataOffset:{type:"uint32",id:14},sensorDataID:{type:"bytes",id:15},sensorDataMapping:{rule:"repeated",type:"uint32",id:16}},nested:{SplineData:{fields:{splineX:{rule:"repeated",type:"float",id:1},splineY:{rule:"repeated",type:"float",id:2},splineZ:{rule:"repeated",type:"float",id:3},red:{rule:"repeated",type:"uint32",id:4},green:{rule:"repeated",type:"uint32",id:5},blue:{rule:"repeated",type:"uint32",id:6},alpha:{rule:"repeated",type:"uint32",id:7},size:{rule:"repeated",type:"float",id:8},rotation:{rule:"repeated",type:"float",id:9},scaleX:{rule:"repeated",type:"float",id:10},scaleY:{rule:"repeated",type:"float",id:11},scaleZ:{rule:"repeated",type:"float",id:12},offsetX:{rule:"repeated",type:"float",id:13},offsetY:{rule:"repeated",type:"float",id:14},offsetZ:{rule:"repeated",type:"float",id:15}}},SplineCompressed:{fields:{splineX:{rule:"repeated",type:"sint32",id:1},splineY:{rule:"repeated",type:"sint32",id:2},splineZ:{rule:"repeated",type:"sint32",id:3},red:{rule:"repeated",type:"uint32",id:4},green:{rule:"repeated",type:"uint32",id:5},blue:{rule:"repeated",type:"uint32",id:6},alpha:{rule:"repeated",type:"uint32",id:7},size:{rule:"repeated",type:"sint32",id:8},rotation:{rule:"repeated",type:"sint32",id:9},scaleX:{rule:"repeated",type:"sint32",id:10},scaleY:{rule:"repeated",type:"sint32",id:11},scaleZ:{rule:"repeated",type:"sint32",id:12},offsetX:{rule:"repeated",type:"sint32",id:13},offsetY:{rule:"repeated",type:"sint32",id:14},offsetZ:{rule:"repeated",type:"sint32",id:15}}}}},InkData:{fields:{strokes:{rule:"repeated",type:"Stroke",id:1},unitScaleFactor:{type:"float",id:2},transform:{type:"Matrix",id:3},brushURIs:{rule:"repeated",type:"string",id:4},renderModeURIs:{rule:"repeated",type:"string",id:5},properties:{rule:"repeated",type:"PathPointProperties",id:6}}},TripleStore:{fields:{statements:{rule:"repeated",type:"SemanticTriple",id:1}},nested:{SemanticTriple:{fields:{subject:{type:"string",id:1},predicate:{type:"string",id:2},object:{type:"string",id:3}}}}},Properties:{fields:{properties:{rule:"repeated",type:"Property",id:1}}},StructureType:{values:{STROKE:0,SENSOR_DATA:1}},Node:{oneofs:{id:{oneof:["groupID","index"]}},fields:{depth:{type:"uint32",id:1},groupID:{type:"bytes",id:2},index:{type:"uint32",id:3},interval:{type:"Interval",id:4},bounds:{type:"Rectangle",id:5}}},InkTree:{fields:{name:{type:"string",id:1},tree:{rule:"repeated",type:"Node",id:2}}},InkStructure:{fields:{type:{type:"StructureType",id:1},inkTree:{type:"InkTree",id:2},views:{rule:"repeated",type:"InkTree",id:3}}},PathFragment:{fields:{id:{type:"bytes",id:1},pointIndexStart:{type:"uint32",id:2},pointIndexEnd:{type:"uint32",id:3},ts:{type:"float",id:4},tf:{type:"float",id:5}}},Path:{fields:{layout:{type:"uint32",id:1},pointProps:{type:"PathPointProperties",id:2},data:{rule:"repeated",type:"float",id:3}}},Polygon:{fields:{shape:{type:"Path",id:1},holes:{rule:"repeated",type:"Path",id:2}}},PolygonArray:{fields:{data:{rule:"repeated",type:"Polygon",id:1}}},InkPath:{oneofs:{data:{oneof:["path","polygons"]}},fields:{path:{type:"Path",id:1},polygons:{type:"PolygonArray",id:2},spline:{type:"Path",id:3}}},InkStroke:{fields:{path:{type:"Stroke",id:1},ink:{type:"InkPath",id:2}}},Style:{fields:{color:{type:"sint32",id:1},brushURI:{type:"string",id:2},randomSeed:{type:"uint32",id:3},renderModeURI:{type:"string",id:4}}},InkSegment:{fields:{ink:{type:"InkPath",id:1},complete:{type:"bool",id:2}}},StrokesContext:{fields:{context:{rule:"repeated",type:"bytes",id:1}}},Intersection:{fields:{strokeID:{type:"bytes",id:1},fragments:{rule:"repeated",type:"PathFragment",id:2}}},Replacement:{fields:{strokeID:{type:"bytes",id:1},strokes:{rule:"repeated",type:"InkStroke",id:2}}},InkOperation:{oneofs:{operation:{oneof:["compose","add","remove","update","replace","split","select","updateSelection","transform"]}},fields:{compose:{type:"Compose",id:1},add:{type:"Add",id:2},remove:{type:"Remove",id:3},update:{type:"Update",id:4},replace:{type:"Replace",id:5},split:{type:"Split",id:6},select:{type:"Select",id:7},updateSelection:{type:"UpdateSelection",id:8},transform:{type:"Transform",id:9}},nested:{Compose:{oneofs:{stage:{oneof:["style","segment","abort"]}},fields:{style:{type:"Style",id:1},segment:{type:"InkSegment",id:2},abort:{type:"bool",id:3},pointerID:{type:"uint32",id:4},strokeID:{type:"bytes",id:5}}},Add:{fields:{strokes:{rule:"repeated",type:"InkStroke",id:1}}},Remove:{fields:{context:{type:"StrokesContext",id:1}}},Update:{fields:{context:{type:"StrokesContext",id:1},style:{type:"Style",id:2}}},Replace:{fields:{replacements:{rule:"repeated",type:"Replacement",id:1}}},Split:{fields:{intersections:{rule:"repeated",type:"Intersection",id:1},affectedArea:{type:"Rectangle",id:2}}},Select:{oneofs:{stage:{oneof:["selector","selection","abort"]}},fields:{selector:{type:"InkStroke",id:1},selection:{type:"StrokesContext",id:2},abort:{type:"bool",id:3}}},UpdateSelection:{oneofs:{stage:{oneof:["transform","complete"]}},fields:{transform:{type:"Matrix",id:1},complete:{type:"bool",id:2}}},Transform:{fields:{context:{type:"StrokesContext",id:1},matrix:{type:"Matrix",id:2}}}}},Range:{fields:{min:{type:"float",id:1},max:{type:"float",id:2},remapURI:{type:"string",id:3}}},PathPointContext:{fields:{statics:{type:"PathPointProperties",id:1},dynamics:{type:"PathPointSettings",id:2},colorMask:{type:"uint32",id:3}}},PathPointSettings:{fields:{size:{type:"PropertySettings",id:1},red:{type:"PropertySettings",id:2},green:{type:"PropertySettings",id:3},blue:{type:"PropertySettings",id:4},alpha:{type:"PropertySettings",id:5},rotation:{type:"PropertySettings",id:6},scaleX:{type:"PropertySettings",id:7},scaleY:{type:"PropertySettings",id:8},scaleZ:{type:"PropertySettings",id:9},offsetX:{type:"PropertySettings",id:11},offsetY:{type:"PropertySettings",id:12},offsetZ:{type:"PropertySettings",id:13}}},PropertySettings:{fields:{value:{type:"Range",id:1},velocity:{type:"Range",id:2},pressure:{type:"Range",id:3},altitude:{type:"Range",id:4},radiusX:{type:"Range",id:5},radiusY:{type:"Range",id:6},resolveURI:{type:"string",id:7},dependencies:{type:"uint32",id:8}}},InkTool:{oneofs:{brush:{oneof:["vectorBrush","rasterBrush"]}},fields:{vectorBrush:{type:"VectorBrush",id:1},rasterBrush:{type:"RasterBrush",id:2},blendMode:{type:"BlendMode",id:3},context:{type:"PathPointContext",id:4}}}}}}},root:"UIM_3_1_0",messages:{InputContext(e){e.id=E.toBytes(E.format(e.id)),e.environmentID=E.toBytes(E.format(e.environmentID)),e.sensorContextID=E.toBytes(E.format(e.sensorContextID))},Environment(e){e.id=E.toBytes(E.format(e.id))},InkInputProvider(e){e.id=E.toBytes(E.format(e.id))},InputDevice(e){e.id=E.toBytes(E.format(e.id))},SensorContext(e){e.id=E.toBytes(E.format(e.id))},SensorChannelsContext(e){e.id=E.toBytes(E.format(e.id)),e.inputDeviceID=E.toBytes(E.format(e.inputDeviceID)),e.inkInputProviderID&&(e.inkInputProviderID=E.toBytes(E.format(e.inkInputProviderID))),e.samplingRateHint&&(e.samplingRateHint=e.samplingRateHint.value),e.latency&&(e.latency=e.latency.value)},SensorChannel(e){e.id=E.toBytes(E.format(e.id))},ChannelData(e){e.sensorChannelID=E.toBytes(E.format(e.sensorChannelID))},SensorData(e){e.id=E.toBytes(e.id),e.inputContextID=E.toBytes(E.format(e.inputContextID))},InputData(e){let t=[],r={};e.sensorData.forEach(((e,i)=>{r[e.id]?t.push(i):0==e.dataChannels.length?(console.warn(`Not found corresponding data channels for sensor data with id: ${e.id}. Invalid sensor data is discarded.`),t.push(i)):r[e.id]=e})),t.reverse().forEach((t=>e.sensorData.removeAt(t)))},View(e){e.name.startsWith("will://")&&(e.name=e.name.toLowerCase()),e.name=e.name.substring(e.name.lastIndexOf("/")+1)},Node(e,t){let r=Dr["3.0.0"].format;e.chunkToIndex>e.chunkFromIndex&&(e.interval={fromIndex:e.chunkFromIndex,toIndex:e.chunkToIndex,fromTValue:0,toTValue:1}),e.update={nodeID:e.id},e.type==r.NodeType.STROKE_GROUP||e.type==r.NodeType.SENSOR_DATA_GROUP?(E.validate(e.id)||(e.id=E.generate(),e.update.id=e.id),e.groupID=E.toBytes(e.id),e.id="groupID"):(e.type==r.NodeType.STROKE?e.update.id=t.context.inkData.strokes[e.index].id:e.update.id=t.context.inputData.sensorData[e.index].id,e.id="index"),Object.defineProperty(e,"bounds",{get:()=>e.groupBoundingBox,configurable:!0})},InkData(e,t){e.brushURIs=[],e.renderModeURIs=[],e.properties=[],e.unitScaleFactor=1,e.transform=t.context.transform},Stroke(e,t){let r=Dr["3.1.0"].format,i=Dr["3.1.0"].messages.PathPointProperties;e.data="splineData",e.splineData={splineX:e.splineX,splineY:e.splineY,splineZ:e.splineZ,red:e.red.map((e=>Math.round(255*e))),green:e.green.map((e=>Math.round(255*e))),blue:e.blue.map((e=>Math.round(255*e))),alpha:e.red.map((e=>Math.round(255*e))),size:e.size,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,scaleZ:e.scaleZ,offsetX:e.offsetX,offsetY:e.offsetY,offsetZ:e.offsetZ},e.id=E.toBytes(e.id),e.sensorDataID&&(e.sensorDataID=E.toBytes(e.sensorDataID)),e.randomSeed=e.style.particlesRandomSeed,e.brushURI="brushURIValue",e.renderModeURI="renderModeURIValue",e.properties="propertiesValue",e.brushURIValue=e.style.brushURI,e.style.renderModeURI&&(e.renderModeURIValue=e.style.renderModeURI),i(e.style.properties,t,!1),e.propertiesValue=Or.encodePathPointProperties(e.style.properties,r.PathPointProperties.create())},PathPointProperties(e,t,r=!0){if(r)return;let i=Dr["3.0.0"].format;for(let t in i.PathPointProperties.fields)if(e[t]){let r=e[t].value;"red"!=t&&"green"!=t&&"blue"!=t||(r=Math.round(255*r)),e[t]=r}else e[t]=void 0},TripleStore(e,t){let r=Dr["3.0.0"].format,i=[],s=[{tree:t.context.inkTree},...t.context.views],n=t.context.inkTree.first.type,o=n==r.NodeType.STROKE_GROUP?Cr.Type.STROKE:Cr.Type.SENSOR_DATA;s.forEach((e=>{if(e.tree.first.type!=n){let t=e.tree.first.type==r.NodeType.STROKE_GROUP?Cr.Type.STROKE:Cr.Type.SENSOR_DATA;throw new Error(`Inconsistent view found: ${t.name} Expected: ${o.name}`)}let t=new Cr(o,e.name);t.tree=e.tree,i.push(t)})),i.forEach((t=>{t.tree.forEach((r=>((t,r,i,s)=>{let n=`uim:node/${r}`,o=i||r;e.statements.forEach((e=>{e.subject==n&&(e.subject=K.createNodeURI(t,o,s)),e.object==n&&(e.object=K.createNodeURI(t,o,s))}))})(t,r.update.nodeID,r.update.id,r.interval)))}))}}},"3.0.0":{schema:{nested:{WacomInkFormat3:{options:{optimize_for:"SPEED",java_multiple_files:!1,java_package:"com.wacom.ink.protobuf",java_outer_classname:"Will3_0_0",csharp_namespace:"Protobuf.WILL_3_0_0"},nested:{Rectangle:{fields:{x:{type:"float",id:1},y:{type:"float",id:2},width:{type:"float",id:3},height:{type:"float",id:4}}},Matrix4:{fields:{m00:{type:"float",id:1},m01:{type:"float",id:2},m02:{type:"float",id:3},m03:{type:"float",id:4},m10:{type:"float",id:5},m11:{type:"float",id:6},m12:{type:"float",id:7},m13:{type:"float",id:8},m20:{type:"float",id:9},m21:{type:"float",id:10},m22:{type:"float",id:11},m23:{type:"float",id:12},m30:{type:"float",id:13},m31:{type:"float",id:14},m32:{type:"float",id:15},m33:{type:"float",id:16}}},Range:{fields:{min:{type:"float",id:1},max:{type:"float",id:2},remapURI:{type:"string",id:3}}},Float32:{fields:{value:{type:"float",id:1}}},Uint32:{fields:{value:{type:"uint32",id:1}}},Property:{fields:{name:{type:"string",id:1},value:{type:"string",id:2}}},SemanticTriple:{fields:{subject:{type:"string",id:1},predicate:{type:"string",id:2},object:{type:"string",id:3}}},InkState:{values:{PLANE:0,HOVERING:1,IN_VOLUME:2,VOLUME_HOVERING:3}},InkSensorMetricType:{values:{LENGTH:0,TIME:1,FORCE:2,ANGLE:3,NORMALIZED:4,LOGICAL:5,DIMENSIONLESS:6}},InkInputProviderType:{values:{PEN:0,TOUCH:1,MOUSE:2,CONTROLLER:3}},InputContext:{fields:{id:{type:"string",id:1},environmentID:{type:"string",id:2},sensorContextID:{type:"string",id:3}}},Environment:{fields:{id:{type:"string",id:1},properties:{rule:"repeated",type:"Property",id:2}}},InkInputProvider:{fields:{id:{type:"string",id:1},type:{type:"InkInputProviderType",id:2},properties:{rule:"repeated",type:"Property",id:3}}},InputDevice:{fields:{id:{type:"string",id:1},properties:{rule:"repeated",type:"Property",id:2}}},SensorContext:{fields:{id:{type:"string",id:1},sensorChannelsContext:{rule:"repeated",type:"SensorChannelsContext",id:2}}},SensorChannelsContext:{fields:{id:{type:"string",id:1},channels:{rule:"repeated",type:"SensorChannel",id:2},samplingRateHint:{type:"Uint32",id:3},latency:{type:"Uint32",id:4},inkInputProviderID:{type:"string",id:5},inputDeviceID:{type:"string",id:6}}},SensorChannel:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},metric:{type:"InkSensorMetricType",id:3},resolution:{type:"double",id:4},min:{type:"float",id:5},max:{type:"float",id:6},precision:{type:"uint32",id:7}}},InputContextData:{fields:{inputContexts:{rule:"repeated",type:"InputContext",id:1},inkInputProviders:{rule:"repeated",type:"InkInputProvider",id:2},inputDevices:{rule:"repeated",type:"InputDevice",id:3},environments:{rule:"repeated",type:"Environment",id:4},sensorContexts:{rule:"repeated",type:"SensorContext",id:5}}},ChannelData:{fields:{sensorChannelID:{type:"string",id:1},values:{rule:"repeated",type:"sint32",id:2}}},SensorData:{fields:{id:{type:"string",id:1},inputContextID:{type:"string",id:2},state:{type:"InkState",id:3},timestamp:{type:"uint64",id:4},dataChannels:{rule:"repeated",type:"ChannelData",id:5}}},Stroke:{fields:{id:{type:"string",id:1},startParameter:{type:"float",id:2},endParameter:{type:"float",id:3},splineX:{rule:"repeated",type:"float",id:4},splineY:{rule:"repeated",type:"float",id:5},splineZ:{rule:"repeated",type:"float",id:6},red:{rule:"repeated",type:"float",id:7},green:{rule:"repeated",type:"float",id:8},blue:{rule:"repeated",type:"float",id:9},alpha:{rule:"repeated",type:"float",id:10},size:{rule:"repeated",type:"float",id:11},rotation:{rule:"repeated",type:"float",id:12},scaleX:{rule:"repeated",type:"float",id:13},scaleY:{rule:"repeated",type:"float",id:14},scaleZ:{rule:"repeated",type:"float",id:15},offsetX:{rule:"repeated",type:"float",id:16},offsetY:{rule:"repeated",type:"float",id:17},offsetZ:{rule:"repeated",type:"float",id:18},sensorDataOffset:{type:"uint32",id:19},sensorDataID:{type:"string",id:20},sensorDataMapping:{rule:"repeated",type:"uint32",id:21},style:{type:"Style",id:22}}},RotationMode:{values:{NONE:0,RANDOM:1,TRAJECTORY:2}},BlendMode:{values:{SOURCE_OVER:0,DESTINATION_OVER:1,DESTINATION_OUT:2,LIGHTER:3,COPY:4,MIN:5,MAX:6}},BrushPrototype:{fields:{coordX:{rule:"repeated",type:"float",id:1},coordY:{rule:"repeated",type:"float",id:2},coordZ:{rule:"repeated",type:"float",id:3},indices:{rule:"repeated",type:"uint32",id:4},shapeURI:{type:"string",id:5},size:{type:"float",id:6}}},VectorBrush:{fields:{name:{type:"string",id:1},prototype:{rule:"repeated",type:"BrushPrototype",id:2},spacing:{type:"float",id:3}}},RasterBrush:{fields:{name:{type:"string",id:1},spacing:{type:"float",id:2},scattering:{type:"float",id:3},rotationMode:{type:"RotationMode",id:4},shapeTexture:{rule:"repeated",type:"bytes",id:5},shapeTextureURI:{rule:"repeated",type:"string",id:6},fillTexture:{type:"bytes",id:7},fillTextureURI:{type:"string",id:8},fillWidth:{type:"float",id:9},fillHeight:{type:"float",id:10},randomizeFill:{type:"bool",id:11},blendMode:{type:"BlendMode",id:12}}},NodeType:{values:{STROKE_GROUP:0,SENSOR_DATA_GROUP:1,STROKE:2,SENSOR_DATA:3}},Node:{fields:{id:{type:"string",id:1},depth:{type:"uint32",id:2},index:{type:"uint32",id:3},type:{type:"NodeType",id:4},groupBoundingBox:{type:"Rectangle",id:5},chunkFromIndex:{type:"uint32",id:6},chunkToIndex:{type:"uint32",id:7}}},View:{fields:{name:{type:"string",id:1},tree:{rule:"repeated",type:"Node",id:2}}},PathPointProperties:{fields:{size:{type:"Float32",id:1},red:{type:"Float32",id:2},green:{type:"Float32",id:3},blue:{type:"Float32",id:4},alpha:{type:"Float32",id:5},rotation:{type:"Float32",id:6},scaleX:{type:"Float32",id:7},scaleY:{type:"Float32",id:8},scaleZ:{type:"Float32",id:9},offsetX:{type:"Float32",id:11},offsetY:{type:"Float32",id:12},offsetZ:{type:"Float32",id:13}}},Style:{fields:{properties:{type:"PathPointProperties",id:1},brushURI:{type:"string",id:2},particlesRandomSeed:{type:"uint32",id:3},renderModeURI:{type:"string",id:4}}},InputData:{fields:{inputContextData:{type:"InputContextData",id:1},sensorData:{rule:"repeated",type:"SensorData",id:2}}},InkData:{fields:{strokes:{rule:"repeated",type:"Stroke",id:1}}},Brushes:{fields:{vectorBrushes:{rule:"repeated",type:"VectorBrush",id:1},rasterBrushes:{rule:"repeated",type:"RasterBrush",id:2}}},TripleStore:{fields:{statements:{rule:"repeated",type:"SemanticTriple",id:1}}},Tool:{oneofs:{brush:{oneof:["vectorBrush","rasterBrush"]}},fields:{vectorBrush:{type:"VectorBrush",id:1},rasterBrush:{type:"RasterBrush",id:2},blendMode:{type:"BlendMode",id:3},context:{type:"PathPointContext",id:4}}},PathPointContext:{fields:{statics:{type:"PathPointProperties",id:1},dynamics:{type:"PathPointSettings",id:2}}},PathPointSettings:{fields:{size:{type:"PropertySettings",id:1},red:{type:"PropertySettings",id:2},green:{type:"PropertySettings",id:3},blue:{type:"PropertySettings",id:4},alpha:{type:"PropertySettings",id:5},rotation:{type:"PropertySettings",id:6},scaleX:{type:"PropertySettings",id:7},scaleY:{type:"PropertySettings",id:8},scaleZ:{type:"PropertySettings",id:9},offsetX:{type:"PropertySettings",id:11},offsetY:{type:"PropertySettings",id:12},offsetZ:{type:"PropertySettings",id:13}}},PropertySettings:{fields:{value:{type:"Range",id:1},velocity:{type:"Range",id:2},pressure:{type:"Range",id:3},altitude:{type:"Range",id:4},radiusX:{type:"Range",id:5},radiusY:{type:"Range",id:6},resolveURI:{type:"string",id:7},dependencies:{rule:"repeated",type:"InputPropertyType",id:8}}},InputPropertyType:{values:{PRESSURE:0,RADIUS_X:1,RADIUS_Y:2,AZIMUTH:3,ALTITUDE:4,ROTATION:5}},InkObject:{fields:{inputData:{type:"InputData",id:1},inkData:{type:"InkData",id:2},brushes:{type:"Brushes",id:3},inkTree:{rule:"repeated",type:"Node",id:4},views:{rule:"repeated",type:"View",id:5},knowledgeGraph:{type:"TripleStore",id:6},transform:{type:"Matrix4",id:7},properties:{rule:"repeated",type:"Property",id:8}}}}}}},root:"WacomInkFormat3",messages:{}}};Dr.evolution.forEach((e=>{let t=Dr[e].root;Object.defineProperty(Dr[e],"format",{get:function(){return this.value||(this.value=Ar.Root.fromJSON(this.schema.nested[t])),this.value}})})),Object.defineProperty(Dr,"latest",{value:Dr[Dr.evolution.last].format,enumerable:!0});const{Namespace:kr,Message:Nr}=Ar;class Mr{constructor(){this.format=Dr.latest}static encode(e){return e.constructor.encode(e).finish()}static decode(e,t){if(!(t instanceof kr))throw new Error("Expected 'Type' to be instance of 'Namespace'");return e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Uint8Array?t.decode(e):e instanceof Nr?e:t.fromObject(e)}}const{Namespace:Lr,Message:_r}=Ar;class Fr{constructor(){Object.defineProperty(this,"format",{value:Dr.latest})}decodeInkObject(e,t){if("3.0.0"==t){let r=this.decode("InkObject",e.data,t);return{Properties:new _r({properties:r.properties}),KnowledgeGraph:r.knowledgeGraph,InputData:r.inputData,Brushes:r.brushes,InkData:r.inkData,InkStructure:new _r({type:Dr.latest.StructureType.STROKE,inkTree:{tree:r.inkTree},views:r.views})}}return{Properties:this.decode("Properties",e.prps,t),KnowledgeGraph:this.decode("TripleStore",e.knwg,t),InputData:this.decode("InputData",e.inpt,t),Brushes:this.decode("Brushes",e.brsh,t),InkData:this.decode("InkData",e.inkd,t),InkStructure:this.decode("InkStructure",e.inks,t)}}decode(e,t,r="latest"){if(!t)return;let i=Dr[r].format[e].decode(t),s=Dr.evolution.slice();for(;s.first!=r;)s=s.slice(1);return this.evolution=s.slice(1),this.evolution.length>0&&(this.state={context:i},this.resolve(i),delete this.state),i}resolve(e){let t=e.constructor.name;this.evolution.forEach((r=>{let i=Dr[r].messages[t];i&&i(e,this.state)})),Object.values(e).forEach((e=>{e instanceof _r?this.resolve(e):Array.isArray(e)&&e.length>0&&e.first instanceof _r&&e.forEach((e=>{e instanceof _r&&this.resolve(e)}))}))}}class Br extends Mr{constructor(){super(),this.precisionDetector=new fr,Object.defineProperty(this,"precisionCalculator",{get:()=>this.precisionDetector.calculator,set:e=>this.precisionDetector.calculator=e,enumerable:!0})}encode(e,t=1,r){if(0==e.length)return;let i=this.buildStrokesIndex(e);this.state={index:i.index},this.precisionDetector.calculator&&this.precisionDetector.reset();let s=this.format.InkData.create({strokes:e.map((e=>this.encodeStroke(e))),unitScaleFactor:t,transform:this.encodeMatrix(r),brushURIs:i.brushURIs,renderModeURIs:i.renderModeURIs,properties:i.properties.map((e=>Or.encodePathPointProperties(e,this.format.PathPointProperties.create())))});return this.reset(),this.precisionDetector.calculator&&this.precisionDetector.printStats(),Mr.encode(s)}buildStrokesIndex(e){let t=[],r=[],i=[],s={},n={};return e.forEach((e=>{let o=[];for(let t in this.format.PathPointProperties.fields)"color"==t?(o.push("red",e.pointProps.red||0),o.push("green",e.pointProps.green||0),o.push("blue",e.pointProps.blue||0),o.push("alpha",(e.pointProps.alpha||0).toFixed(2))):o.push(t,(e.pointProps[t]||0).toFixed(2));o=o.join("_");let a=t.indexOf(e.brush.name),l=e.renderMode!=ur.RenderMode.SOURCE_OVER?r.indexOf(e.renderMode):void 0,h=i.indexOf(o);-1==a&&(a=t.push(e.brush.name)-1),-1==l&&(l=r.push(e.renderMode)-1),-1==h&&(h=i.push(o)-1,s[o]=e.pointProps),n[e.id]={brushURI:a,renderModeURI:l,pathPointProperties:h}})),{properties:i.map((e=>s[e])),brushURIs:t,renderModeURIs:r,index:n}}decode(e,t={},r=[]){if(!e)return;let i=Mr.decode(e,this.format.InkData),s={brushes:t,brushURIs:i.brushURIs,sensorPaths:Object.assign({},...r.map((e=>({[e.id]:e})))),renderModeURIs:i.renderModeURIs,properties:i.properties},n={strokes:i.strokes.map((e=>this.decodeStroke(e,s))),unitScaleFactor:i.unitScaleFactor||1,transform:this.decodeMatrix(i.transform)};return this.reset(),n}encodeStroke(e){let t=this.state?this.state.index[e.id]:void 0,r=this.format.Stroke.create({id:E.toBytes(e.id),startParameter:e.ts,endParameter:e.tf,randomSeed:e.randomSeed});if(t?(r.brushURIIndex=t.brushURI+1,r.propertiesIndex=t.pathPointProperties+1,isFinite(t.renderModeURI)&&(r.renderModeURIIndex=t.renderModeURI+1)):(r.brushURIValue=e.brush.name,r.propertiesValue=Or.encodePathPointProperties(e.pointProps,this.format.PathPointProperties.create()),e.renderMode!=ur.RenderMode.SOURCE_OVER&&(r.renderModeURIValue=e.renderMode)),this.precisionDetector.calculator&&e.compressionType==ur.CompressionType.AUTO&&this.precisionDetector.updatePrecisionSchema(e),e.precisionSchema?(r.precisions=e.precisionSchema.precisions,r.splineCompressed=this.encodeSplineCompressed(e.spline,e.precisionSchema)):r.splineData=this.encodeSpline(e.spline),e.sensorData&&!this.ignoreSensorData){if(!t)throw new Error("Model-less strokes sensor data persistance is not supported");r.sensorDataID=E.toBytes(e.sensorData.id),r.sensorDataOffset=e.sensorDataOffset,r.sensorDataMapping=e.sensorDataMapping}return r}decodeStroke(e,t={}){let r="splineCompressed"==e.data,i=e[e.data];if(0==i.splineX.length||0==i.splineY.length)throw new Error("Incomplete path definition");let s=[U.Property.X,U.Property.Y];i.splineZ.length>0&&s.push(U.Property.Z),i.red&&i.red.length>0&&s.push(U.Property.RED),i.green.length>0&&s.push(U.Property.GREEN),i.blue.length>0&&s.push(U.Property.BLUE),i.alpha.length>0&&s.push(U.Property.ALPHA),i.size.length>0&&s.push(U.Property.SIZE),i.rotation.length>0&&s.push(U.Property.ROTATION),i.scaleX.length>0&&s.push(U.Property.SCALE_X),i.scaleY.length>0&&s.push(U.Property.SCALE_Y),i.scaleZ.length>0&&s.push(U.Property.SCALE_Z),i.offsetX.length>0&&s.push(U.Property.OFFSET_X),i.offsetY.length>0&&s.push(U.Property.OFFSET_Y),i.offsetZ.length>0&&s.push(U.Property.OFFSET_Z);let n,o,a=i.splineX.length,l=s.length,h=Float32Array.createSharedInstance(a*l);r?(n=new xt(e.precisions),this.decodeSplineCompressed(i,s,h,n)):this.decodeSpline(i,s,h),e.renderModeURI&&(o="renderModeURIValue"==e.renderModeURI?e.renderModeURIValue:t.renderModeURIs[e.renderModeURIIndex-1]);let d,c="propertiesValue"==e.properties?Or.decodePathPointProperties(e.propertiesValue,s):Or.decodePathPointProperties(t.properties[e.propertiesIndex-1],s),p="brushURIValue"==e.brushURI?e.brushURIValue:t.brushURIs[e.brushURIIndex-1],u=(t.brushes?t.brushes[p]:void 0)||p;t.sensorPaths&&e.sensorDataID&&(d=t.sensorPaths[E.fromBytes(e.sensorDataID)]);let f=e.startParameter,m=e.endParameter;1==f&&(console.warn(`Invalid ts = 1 found on spline deserializtion, ts is set to 0.99999. Stroke ${E.fromBytes(e.id)} is affected.`),f=.99999),0==m&&(console.warn(`Invalid tf = 1 found on spline deserializtion, tf is set to 0.00001. Stroke ${E.fromBytes(e.id)} is affected.`),m=1e-5);let g=Dt.createSharedInstance(s,h,c,f,m);g.id=this.cloneStroke?E.generate():E.fromBytes(e.id);let y=new ur(u,g,t.inkPath,d);return y.randomSeed=e.randomSeed,y.precisionSchema=n,o&&(y.renderMode=o),d&&(y.sensorDataOffset=e.sensorDataOffset,y.sensorDataMapping=e.sensorDataMapping),y}encodeSpline(e){let t=this.format.Stroke.SplineData.create();for(let r=0;r<e.length;r++){let i=e.getPointRef(r);e.layout.forEach((e=>{switch(e){case U.Property.X:t.splineX.push(i.x);break;case U.Property.Y:t.splineY.push(i.y);break;case U.Property.Z:t.splineZ.push(i.z);break;case U.Property.RED:t.red.push(i.red);break;case U.Property.GREEN:t.green.push(i.green);break;case U.Property.BLUE:t.blue.push(i.blue);break;case U.Property.ALPHA:t.alpha.push(Math.round(255*i.alpha));break;case U.Property.SIZE:t.size.push(i.size);break;case U.Property.ROTATION:t.rotation.push(i.rotation);break;case U.Property.SCALE_X:t.scaleX.push(i.scaleX);break;case U.Property.SCALE_Y:t.scaleY.push(i.scaleY);break;case U.Property.SCALE_Z:t.scaleZ.push(i.scaleZ);break;case U.Property.OFFSET_X:t.offsetX.push(i.offsetX);break;case U.Property.OFFSET_Y:t.offsetY.push(i.offsetY);break;case U.Property.OFFSET_Z:t.offsetZ.push(i.offsetZ);break;default:throw new Error(`Invalid layout property provided: ${e}`)}}))}return t}decodeSpline(e,t,r){let i=t.length;for(let s=0;s<r.length;s++)t.forEach(((t,n)=>{let o;switch(t){case U.Property.X:o=e.splineX[s];break;case U.Property.Y:o=e.splineY[s];break;case U.Property.Z:o=e.splineZ[s];break;case U.Property.RED:o=e.red[s];break;case U.Property.GREEN:o=e.green[s];break;case U.Property.BLUE:o=e.blue[s];break;case U.Property.ALPHA:o=e.alpha[s]/255;break;case U.Property.SIZE:o=e.size[s];break;case U.Property.ROTATION:o=e.rotation[s];break;case U.Property.SCALE_X:o=e.scaleX[s];break;case U.Property.SCALE_Y:o=e.scaleY[s];break;case U.Property.SCALE_Z:o=e.scaleZ[s];break;case U.Property.OFFSET_X:o=e.offsetX[s];break;case U.Property.OFFSET_Y:o=e.offsetY[s];break;case U.Property.OFFSET_Z:o=e.offsetZ[s];break;default:throw new Error(`Invalid layout property provided: ${t.name}`)}r[s*i+n]=o}))}encodeSplineCompressed(e,t){let r=this.format.Stroke.SplineCompressed.create(),i=t.factors,s={},n=(e,r,n)=>{let o;if((n=Math.round(n*i[e]))>Number.MAX_INT32||n<-Number.MAX_INT32)throw new Error(`Int32 precision exceeded ${n} for precision with type ${e} and value ${t[e]}. This value is not applicable.`);return o=r in s?n-s[r]:n,s[r]=n,o};for(let t=0;t<e.length;t++){let i=e.getPointRef(t);e.layout.forEach(((e,t)=>{switch(e){case U.Property.X:r.splineX.push(n("position","x",i.x));break;case U.Property.Y:r.splineY.push(n("position","y",i.y));break;case U.Property.Z:r.splineZ.push(n("position","z",i.z));break;case U.Property.RED:r.red.push(i.red);break;case U.Property.GREEN:r.green.push(i.green);break;case U.Property.BLUE:r.blue.push(i.blue);break;case U.Property.ALPHA:r.alpha.push(Math.round(255*i.alpha));break;case U.Property.SIZE:r.size.push(n("size","size",i.size));break;case U.Property.ROTATION:r.rotation.push(n("rotation","rotation",i.rotation));break;case U.Property.SCALE_X:r.scaleX.push(n("scale","scaleX",i.scaleX));break;case U.Property.SCALE_Y:r.scaleY.push(n("scale","scaleY",i.scaleY));break;case U.Property.SCALE_Z:r.scaleZ.push(n("scale","scaleZ",i.scaleZ));break;case U.Property.OFFSET_X:r.offsetX.push(n("offset","offsetX",i.offsetX));break;case U.Property.OFFSET_Y:r.offsetY.push(n("offset","offsetY",i.offsetY));break;case U.Property.OFFSET_Z:r.offsetZ.push(n("offset","offsetZ",i.offsetZ));break;default:throw new Error(`Invalid layout property provided: ${e}`)}}))}return r}decodeSplineCompressed(e,t,r,i){let s=t.length,n=i.factors,o={},a=(e,t,r)=>(t in o&&(r+=o[t]),o[t]=r,r/n[e]);for(let i=0;i<r.length;i++)t.forEach(((t,n)=>{let o;switch(t){case U.Property.X:o=a("position","x",e.splineX[i]);break;case U.Property.Y:o=a("position","y",e.splineY[i]);break;case U.Property.Z:o=a("position","z",e.splineZ[i]);break;case U.Property.RED:o=e.red[i];break;case U.Property.GREEN:o=e.green[i];break;case U.Property.BLUE:o=e.blue[i];break;case U.Property.ALPHA:o=e.alpha[i]/255;break;case U.Property.SIZE:o=a("size","size",e.size[i]);break;case U.Property.ROTATION:o=a("rotation","rotation",e.rotation[i]);break;case U.Property.SCALE_X:o=a("scale","scaleX",e.scaleX[i]);break;case U.Property.SCALE_Y:o=a("scale","scaleY",e.scaleY[i]);break;case U.Property.SCALE_Z:o=a("scale","scaleZ",e.scaleZ[i]);break;case U.Property.OFFSET_X:o=a("offset","offsetX",e.offsetX[i]);break;case U.Property.OFFSET_Y:o=a("offset","offsetY",e.offsetY[i]);break;case U.Property.OFFSET_Z:o=a("offset","offsetZ",e.offsetZ[i]);break;default:throw new Error(`Invalid layout property provided: ${t.name}`)}r[i*s+n]=o}))}encodeMatrix(e){if(e&&!e.isIdentity)return this.format.Matrix.create({m00:e.m11,m01:e.m12,m02:e.m13,m03:e.m14,m10:e.m21,m11:e.m22,m12:e.m23,m13:e.m24,m20:e.m31,m21:e.m32,m22:e.m33,m23:e.m34,m30:e.m41,m31:e.m42,m32:e.m43,m33:e.m44})}decodeMatrix(e){if(e)return N.fromMatrix([e.m00,e.m01,e.m02,e.m03,e.m10,e.m11,e.m12,e.m13,e.m20,e.m21,e.m22,e.m23,e.m30,e.m31,e.m32,e.m33])}reset(){this.state=void 0,this.ignoreSensorData=!1,this.cloneStroke=!1}}class Ur extends Mr{constructor(){super()}encode(e){if(0==e.length)return;let t={},r={},i={},s={},n={};e.forEach((e=>{let o=e.context;t[o.id]||(t[o.id]=o,n[o.environment.id]||(n[o.environment.id]=o.environment),r[o.sensorContext.id]||(r[o.sensorContext.id]=o.sensorContext,o.sensorContext.channelsContexts.forEach((e=>{i[e.device.id]||(i[e.device.id]=e.device),e.inkProvider&&(s[e.inkProvider.id]||(s[e.inkProvider.id]=e.inkProvider))}))))}));let o=this.format.InputData.create({sensorData:e.map((e=>this.encodeSensorData(e))),inputContextData:this.format.InputContextData.create({inputContexts:Object.values(t).map((e=>this.format.InputContext.create({id:E.toBytes(E.format(e.id)),environmentID:E.toBytes(E.format(e.environment.id)),sensorContextID:E.toBytes(E.format(e.sensorContext.id))}))),sensorContexts:Object.values(r).map((e=>this.format.SensorContext.create({id:E.toBytes(E.format(e.id)),sensorChannelsContext:e.channelsContexts.map((e=>this.format.SensorChannelsContext.create({id:E.toBytes(E.format(e.id)),channels:e.channels.map((e=>this.format.SensorChannel.create({id:E.toBytes(E.format(e.id)),type:e.type,metric:this.format.InkSensorMetricType[e.metric.name],resolution:e.resolution,min:e.min,max:e.max,precision:e.precision}))),samplingRateHint:e.samplingRate,latency:e.latency,inkInputProviderID:e.inkProvider?E.toBytes(E.format(e.inkProvider.id)):void 0,inputDeviceID:E.toBytes(E.format(e.device.id))})))}))),inkInputProviders:Object.values(s).map((e=>this.format.InkInputProvider.create({id:E.toBytes(E.format(e.id)),type:this.format.InkInputProviderType[e.type.name],properties:this.encodeProperties(e.props)}))),inputDevices:Object.values(i).map((e=>this.format.InputDevice.create({id:E.toBytes(E.format(e.id)),properties:this.encodeProperties(e.props)}))),environments:Object.values(n).map((e=>this.format.Environment.create({id:E.toBytes(E.format(e.id)),properties:this.encodeProperties(e.props)})))})});return Mr.encode(o)}decode(e){if(!e)return[];let t=Mr.decode(e,this.format.InputData),r={},i={},s={},n={},o={};return t.inputContextData.environments.forEach((e=>{let t=new Y;this.decodeProperties(e.properties,t.props),Object.freeze(t),t.id!=E.fromBytes(e.id).replace(/-/g,"")&&console.warn(`Environment decode id missmatch - found ${E.fromBytes(e.id).replace(/-/g,"")}, expected ${t.id}`),o[t.id]=t})),t.inputContextData.inkInputProviders.forEach((e=>{let t=this.decodeProperties(e.properties),r=new I(I.Type[this.format.InkInputProviderType[e.type]],t);Object.freeze(r),r.id!=E.fromBytes(e.id).replace(/-/g,"")&&console.warn(`InkInputProvider decode id missmatch - found ${E.fromBytes(e.id).replace(/-/g,"")}, expected ${r.id}`),n[r.id]=r})),t.inputContextData.inputDevices.forEach((e=>{let t=new ee;this.decodeProperties(e.properties,t.props),Object.freeze(t),t.id!=E.fromBytes(e.id).replace(/-/g,"")&&console.warn(`InputDevice decode id missmatch - found ${E.fromBytes(e.id).replace(/-/g,"")}, expected ${t.id}`),s[t.id]=t})),t.inputContextData.sensorContexts.forEach((e=>{let t=new q;e.sensorChannelsContext.forEach((e=>{let r=new Z(s[E.fromBytes(e.inputDeviceID).replace(/-/g,"")],n[E.fromBytes(e.inkInputProviderID).replace(/-/g,"")]);e.samplingRateHint&&(r.samplingRate=e.samplingRateHint),e.latency&&(r.latency=e.latency),e.channels.forEach((e=>{let t=H.Metric[this.format.InkSensorMetricType[e.metric]],i=new H(e.type,t,e.resolution,e.min,e.max);i.precision=e.precision,r.add(i),i.id!=E.fromBytes(e.id).replace(/-/g,"")&&console.warn(`SensorChannel decode id missmatch - found ${E.fromBytes(e.id).replace(/-/g,"")}, expected ${i.id}`)})),t.addContext(r),r.id!=E.fromBytes(e.id).replace(/-/g,"")&&console.warn(`SensorChannelsContext decode id missmatch - found ${E.fromBytes(e.id).replace(/-/g,"")}, expected ${r.id}`)})),Object.freeze(t),i[t.id]=t,t.id!=E.fromBytes(e.id).replace(/-/g,"")&&console.warn(`SensorContext decode id missmatch - found ${E.fromBytes(e.id).replace(/-/g,"")}, expected ${t.id}`)})),t.inputContextData.inputContexts.forEach((e=>{let t=new W(o[E.fromBytes(e.environmentID).replace(/-/g,"")],i[E.fromBytes(e.sensorContextID).replace(/-/g,"")]);Object.freeze(t),t.id!=E.fromBytes(e.id).replace(/-/g,"")&&console.warn(`InputContext decode id missmatch - found ${E.fromBytes(e.id).replace(/-/g,"")}, expected ${t.id}`),r[t.id]=t})),t.sensorData.map((e=>this.decodeSensorData(e,r[E.fromBytes(e.inputContextID).replace(/-/g,"")])))}encodeSensorData(e){let t=this.format.SensorData.create({id:E.toBytes(e.id),inputContextID:E.toBytes(E.format(e.context.id)),state:this.format.InkState[e.inkState.name],timestamp:e.created});return e.streams.forEach((e=>{let r={};e.channels.forEach((e=>r[e.id]=[]));for(let t=0;t<e.length;t++){let i=e.get(t);e.channels.forEach((e=>{r[e.id].push(i[M.getPropName(e.name)])}))}e.channels.forEach((e=>{if(!("precision"in e))throw new Error(`Precision not found for channel with id: ${e.id}`);let i=r[e.id];if(0==i.length)return;let s=10**e.precision,n=Math.round(i[0]*s),o=this.format.ChannelData.create({sensorChannelID:E.toBytes(E.format(e.id))});o.values.push(n);for(let e=1;e<i.length;e++){let t=Math.round(i[e]*s);o.values.push(t-n),n=t}t.dataChannels.push(o)}))})),t}decodeSensorData(e,t){if(0==e.dataChannels.length)throw new Error(`Not found corresponding data channels for sensor data with id: ${E.fromBytes(e.id)}`);let r=new J(t,E.fromBytes(e.id));r.created=parseInt(c.default.fromValue(e.timestamp).toString()),r.inkState=J.InkState[this.format.InkState[e.state]];let i={};return e.dataChannels.forEach((e=>{let r=E.fromBytes(e.sensorChannelID).replace(/-/g,"");if(0==e.values.length)return void(i[r]=[]);let s=t.sensorContext.getContextByChannelID(r);if(!s)throw new Error(`Not found corresponding channel context for data with channelID ${r}`);let n=10**s.get(r).precision,o=e.values[0],a=[];a.push(o/n);for(let t=1;t<e.values.length;t++){let r=o+e.values[t];a.push(r/n),o=r}i[r]=a})),t.sensorContext.channelsContexts.forEach((e=>{let t=new Q(e.channels),s=i[e.channels.first.id];if(s){let r=s.length;for(let s=0;s<r;s++)e.channels.forEach((e=>{let r=i[e.id];if(!r)throw new Error(`Not found corresponding data for channel ${e.type} with id: ${e.id}`);t.data.push(r[s])}))}else{if(t.ink)throw new Error("Empty ink stream is not allowed");{let t=0;if(e.channels.forEach((e=>{i[e.id]&&(t+=i[e.id].length)})),t>0)throw new Error(`Un-alligned channels context is not valid, found with id: ${e.id}`)}}r.add(t)})),r}encodeProperties(e){return Object.keys(e).map((t=>this.format.Property.create({name:t,value:e[t]})))}decodeProperties(e,t={}){return Object.assign(t,...e.map((e=>({[e.name]:e.value}))))}}class jr extends Mr{constructor(){super()}async encode(e){if(0==e.length)return;let t=this.format.Brushes.create();for(let r of e)if(r instanceof $e){let e=this.encodeBrush2D(r);t.vectorBrushes.push(e)}else{let e=await this.encodeBrushGL(r);t.rasterBrushes.push(e)}return Mr.encode(t)}decode(e){if(!e)return{};let t=Mr.decode(e,this.format.Brushes),r={};return t.vectorBrushes.forEach((e=>r[e.name]=this.decodeBrush2D(e))),t.rasterBrushes.forEach((e=>r[e.name]=this.decodeBrushGL(e))),r}encodeBrush2D(e){if(!e.name)throw new Error("Encode Brush2D failed. name property is required.");let t=this.format.VectorBrush.create({name:e.name,spacing:e.spacing}),r=Array.isArray(e.shape)?e.shape:[e.shape];for(let e of r){let r=this.format.BrushPrototype.create({size:e.size});if(e.descriptor.shape.name)r.shapeURI=e.descriptor.shape.name;else{let t=e.shape;for(let e=0;e<t.shape.length;e++)r.coordX.push(t.shape.getPointX(e)),r.coordY.push(t.shape.getPointY(e))}t.prototype.push(r)}return t}decodeBrush2D(e){let t=he.instance?he.instance.get(e.name):null;if(t){if(t instanceof $e)return t;throw new Error(`URI conflict detected, ${e.name} expected Brush2D, found ${t.constructor.name}`)}let r=[];return e.prototype.forEach((e=>{let t;if(e.shapeURI)t=e.shapeURI;else{t=Float32Array.createSharedInstance(2*e.coordX.length);for(let r=0;r<t.length/2;r++)t[2*r]=e.coordX[r],t[2*r+1]=e.coordY[r]}r.push(new _e(t,e.size))})),new $e(e.name,r,e.spacing)}async encodeBrushGL(e){if(!e.name)throw new Error("Encode BrushGL failed. name property is required.");let t={shape:[],shapeURI:[],fill:void 0,filleURI:void 0};if(Array.isArray(e.shape)){let r=e.descriptor.shape.map((e=>e.name)).filter((e=>e));if(r.length>0){if(r.length!=e.shape.length)throw new Error(`Brush ${e.name} shape names length do not match with brush mipmap`);t.shapeURI=r}}else e.descriptor.shape.name&&t.shapeURI.push(e.descriptor.shape.name);if(t.fillURI=e.descriptor.fill.name,0==t.shapeURI.length||!t.fillURI){let r={shape:await e.getShapeBinary(),fill:await e.getFillBinary()};0==t.shapeURI.length&&(Array.isArray(e.shape)?t.shape=r.shape:t.shape.push(r.shape)),t.fillURI||(t.fill=r.fill)}let r=e.blendMode.replace(/-/g,"_").toUpperCase();return this.format.RasterBrush.create({name:e.name,spacing:e.spacing,scattering:e.scattering,blendMode:this.format.BlendMode[r],rotationMode:this.format.RotationMode[e.rotationMode.name],shapeTexture:t.shape,shapeTextureURI:t.shapeURI,fillTexture:t.fill,fillTextureURI:t.fillURI,fillWidth:e.fillTextureSize.width,fillHeight:e.fillTextureSize.height,randomizeFill:e.randomizeFill})}decodeBrushGL(e){let t,r,i=he.instance?he.instance.get(e.name):null;if(i){if(i instanceof rt)return i;throw new Error(`URI conflict detected, ${e.name} expected BrushGL, found ${i.constructor.name}`)}if(e.shapeTextureURI.length>0)t=1==e.shapeTextureURI.length?{name:e.shapeTextureURI.first}:e.shapeTextureURI.map((e=>({name:e})));else{if(!(e.shapeTexture.length>0))throw new Error("Decode BrushGL shape - insufficent data found");t=1==e.shapeTexture.length?{value:e.shapeTexture.first}:e.shapeTexture.map((e=>({value:e})))}if(e.fillTextureURI)r={name:e.fillTextureURI};else{if(!e.fillTexture)throw new Error("Decode BrushGL fill - insufficent data found");r={value:e.fillTexture}}return new rt(e.name,t,r,{spacing:e.spacing,scattering:e.scattering,blendMode:Ve[this.format.BlendMode[e.blendMode]],rotationMode:rt.RotationMode[e.rotationMode]},{randomize:e.randomizeFill,size:{width:e.fillWidth,height:e.fillHeight}})}}class Gr extends Mr{constructor(){super()}encode(e){if(!e||0==e.length)return;let t=this.format.TripleStore.create({statements:e.map((e=>this.format.TripleStore.SemanticTriple.create({subject:e.subject,predicate:e.predicate,object:e.object})))});return Mr.encode(t)}decode(e){if(!e)return;let t=Mr.decode(e,this.format.TripleStore);return new Tr(...t.statements)}}class $r extends P{constructor(e){super(e)}}class Yr extends $r{constructor(e){let t;super(e),Object.defineProperty(this,"bounds",{get:()=>(t||(t=this.getBounds()),t),set:e=>t=e,enumerable:!0}),Object.defineProperty(this,"boundsValue",{get:()=>t}),Object.defineProperty(this,"root",{get:function(){let e=this.parent,t=this;for(;e;)t=e,e=e.parent;return t},enumerable:!0})}getBounds(){throw new Error("getBounds is abstract, should be implemented")}invalidateBounds(){this.preventInvalidateBounds||(this.bounds=void 0,this.parent&&this.parent.invalidateBounds())}remove(){this.parent.removeChild(this)}}class Xr extends Yr{constructor(e){let t;super(e),this.children=[],Object.defineProperty(this,"uri",{get:()=>(t||(t=K.createNodeURI(this.root.model,this.id)),t),enumerable:!0}),Object.defineProperty(this,"type",{value:"GROUP",enumerable:!0}),Object.defineProperty(this,"content",{value:this.children,enumerable:!0})}getBounds(){let e;return this.children.forEach((t=>{e=e?e.union(t.bounds):t.bounds})),e}contains(e){if(!(e instanceof Yr))throw new Error(`Incompatible node found - ${e.constructor.name}. InkElement expected.`);let t=!1,r=e.parent;for(;r;){if(r==this){t=!0;break}r=r.parent}return t}indexOf(e){if(!(e instanceof Yr))throw new Error(`Incompatible node found - ${e.constructor.name}. InkElement expected.`);return this.children.indexOf(e)}appendChild(e,t){if(!(e instanceof Yr))throw new Error(`Incompatible node found - ${e.constructor.name}. InkElement expected.`);if(t<0)throw new Error("Index should be a positive number");let r=e.parent;if(r){if(this.root.id!=e.root.id)throw new Error("Moving nodes from one hierarchy to another is not allowed. Make sure root is common for this operation.");e.parent.children.remove(e),e.parent.invalidateBounds()}if(e.parent=this,isFinite(t)&&t<this.children.length?this.children.insert(e,t):this.children.push(e),!r){let r=this.root.model;r&&r.register(e,t)}return this.invalidateBounds(),e}removeChild(e){if(!this.children.includes(e))throw new Error("Node was not found");let t=this.root.model;t&&t.unregister(e),this.invalidateBounds(),this.children.remove(e)}remove(){this.parent?this.parent.removeChild(this):(this.model&&this.model.unregister(this),this.invalidateBounds())}}class zr extends Yr{constructor(e,t){super(),Object.defineProperty(this,"uri",{get:()=>this.id,enumerable:!0}),Object.defineProperty(this,"type",{value:"PATH",enumerable:!0}),Object.defineProperty(this,"index",{get:()=>this.parent?this.parent.indexOf(this):0,enumerable:!0}),Object.defineProperty(this,"content",{value:e,enumerable:!0}),Object.defineProperty(this,"fragment",{value:t,enumerable:!0})}buildURI(){return K.createNodeURI(this.root.model,this.content.id,this.fragment)}getBounds(){if(this.fragment){let e=this.content.slice(this.fragment);return e.brush instanceof $e&&e.buildPath({lastPipelineStage:Kt.BRUSH_APPLIER}),e.bounds}return this.content.bounds}split(e,t=1){if(this.content instanceof J)throw new Error("SensorData is immutable. Split is not applicable.");if(!this.parent)throw new Error("Dettached InkPath node split is not allowed. Attach to hierarchy first.");if(e<0||e>this.content.length-1)throw new Error(`Index out of range {0, ${this.content.length-1}}`);let r=this.fragment?this.fragment.pointIndexStart:0,i=this.fragment?this.fragment.pointIndexEnd:this.content.length-1,s=this.fragment?this.fragment.ts:this.content.ts,n=this.fragment?this.fragment.tf:this.content.tf,o=this.content.spline.getFragment(r,s,e+1,t-.05,!0),a=this.content.spline.getFragment(e-1,1==t?.05:t,i,n,!0);if(o.pointIndexEnd+1-o.pointIndexStart<4)throw new Error(`Invalid split index ${e} found - range {${o.pointIndexStart}, ${o.pointIndexEnd}} is invalid. At least 4 points are needed to define path fragment.`);if(a.pointIndexEnd+1-a.pointIndexStart<4)throw new Error(`Invalid split index ${e} found - range {${a.pointIndexStart}, ${a.pointIndexEnd}} is invalid. At least 4 points are needed to define path fragment.`);let l=new zr(this.content,o),h=new zr(this.content,a),d=this.index;return this.remove(),this.parent.appendChild(l,d),this.parent.appendChild(h,d+1),[l,h]}}class Vr extends Cr{constructor(e,t,r){super(t.type,e),this.model=t,this.root=this.createGroup(r),this.root.model=this,Object.defineProperty(this,"tree",{get:()=>(console.warn("View 'tree' property is deprecated. Use root instead."),this.root)}),this.register(this.root)}addPath(e,t){return t||(t=this.root),t.appendChild(this.createElement(e))}createElement(e,t){if(t&&!(t instanceof Ot))throw new Error("fragment expected type is SplineFragment");return this.model.createElement(e,this,t)}createGroup(e){return this.model.createGroup(e,this)}register(e){if(e instanceof Xr)e.children.forEach((e=>this.register(e)));else{if(!(e instanceof zr))throw new Error(`Register unknown node found: ${e.id}`);if(e.content instanceof ur){if(this.type!=Vr.Type.STROKE)throw new Error(`Incompatible element content found - ${e.content.constructor.name}. Content should be instance of Stroke.`)}else{if(!(e.content instanceof J))throw new Error(`Incompatible element content found - ${e.content.constructor.name}. Content should be ${this.type.name}.`);if(this.type!=Vr.Type.SENSOR_DATA)throw new Error(`Incompatible element content found - ${e.content.constructor.name}. Content should be instance of SensorData.`)}if(!this.model.content.includes(e.content))throw new Error(`Node content not found in underling ink model - ${e.content.id}`)}this.model.index(e),this.updateKnowledgeGraph(e)}unregister(e){e instanceof Xr&&e.children.forEach((e=>this.unregister(e))),delete this.model.registry.nodes[e.uri],this.updateKnowledgeGraph(e)}updateKnowledgeGraph(e){if(this.model.registry.nodes[e.uri]){if(!this.knowledgeGraph)return;this.knowledgeGraph.filter((t=>t.subject==e.uri||t.object==e.uri)).forEach((t=>{t.subject==e.uri&&t.object.startsWith("uim:ne/")&&this.model.knowledgeGraph.add(...this.knowledgeGraph.filter((e=>e.subject==t.object))),this.model.knowledgeGraph.add(t)}))}else this.model.knowledgeGraph.filter((t=>t.subject==e.uri||t.object==e.uri)).forEach((t=>{t.subject==e.uri&&t.object.startsWith("uim:ne/")&&this.model.knowledgeGraph.remove(...this.model.knowledgeGraph.filter((e=>e.subject==t.object))),this.model.knowledgeGraph.remove(t)}))}extractKnowledge(){let e=this.model.knowledgeGraph.filter((e=>e.subject.startsWith(K.createNodeURISchema(this)))),t=new Set(e.map((e=>e.object)));for(;t.size>0;){let r=this.model.knowledgeGraph.filter((r=>t.has(r.subject)&&!e.includes(r)));e.push(...r),t=new Set(r.map((e=>e.object)))}return e}}class Hr extends Cr{constructor(e=Hr.Type.STROKE,t){super(e),this.root=this.createGroup(t),this.root.model=this,Object.defineProperty(this,"tree",{get:()=>(console.warn("InkModel 'tree' property is deprecated. Use root instead."),this.root)}),this.props={},this.views={},this.unitScaleFactor=1,this.transform=void 0,this.knowledgeGraph=new Tr,this.knowledgeGraphAnalyzer=new gr(this),Object.defineProperty(this,"registry",{value:{nodes:{},content:{},brushes:{}},enumerable:!0}),this.type==Hr.Type.STROKE?this.registry.sensorData={}:Object.defineProperty(this.registry,"sensorData",{get:()=>this.content,enumerable:!0}),Object.defineProperty(this,"content",{value:[],enumerable:!0}),Object.defineProperty(this,"strokes",{get:()=>this.type==Hr.Type.STROKE?this.content.slice():[],enumerable:!0}),Object.defineProperty(this,"sensorData",{get:()=>{let e;if(this.type==Hr.Type.STROKE){let t={};if(this.disableSensorDataIntegrity)t=Object.assign(t,...Object.values(this.registry.sensorData).map((e=>({[e.id]:e}))));else for(let e of this.content)e.sensorData&&(t[e.sensorData.id]=e.sensorData);e=Object.values(t)}else e=this.content;return e},set:e=>{if(!(e instanceof J))throw new Error("Data type mismatch, expected SensorData");if(this.type==Hr.Type.SENSOR_DATA)throw new Error("For SensorData models use 'addPath' method instead");this.disableSensorDataIntegrity=!0,this.index(e)},enumerable:!0}),Object.defineProperty(this,"brushes",{get:()=>{if(this.type==Hr.Type.SENSOR_DATA)return[];let e={};for(let t of this.content)e[t.brush.name]=this.registry.brushes[t.brush.name]||t.brush;return Object.values(e)},set:e=>{for(let t of e)this.index(t)},enumerable:!0}),this.register(this.root),this.disableSensorDataIntegrity=!0}addPath(e,t){t||(t=this.root);let r=this.createElement(e);return e.sensorData&&this.index(e.sensorData),e.brush&&!this.registry.brushes[e.brush.id]&&this.index(e.brush),t.appendChild(r)}removePath(e){e.nodeID&&this.registry.nodes[e.nodeID].remove()}replacePath(e,t,r=!1){if(!e.nodeID)return;let i=this.getNode(e.nodeID),s=i.parent||this.root,n=t.map((e=>this.createElement(e))),o=s.children.indexOf(i);if(r){let e=s.appendChild(this.createGroup(),o);n.forEach((t=>e.appendChild(t)))}else n.forEach(((e,t)=>s.appendChild(e,o+t)));this.removePath(e)}createElement(e,t,r){if(!e)throw new Error("Element content not found");let i=t?t.type:this.type;switch(i){case Hr.Type.STROKE:if(!(e instanceof ur))throw new Error(`Incompatible element content found - ${e.constructor.name}. Content should be instance of Stroke.`);if(r&&!t)throw new Error("Main tree is not fragmentable. Fragments are applicable only in Views.");break;case Hr.Type.SENSOR_DATA:if(!(e instanceof J))throw new Error(`Incompatible element content found - ${e.constructor.name}. Content should be instance of SensorData.`);if(r)throw new Error("SensorData fragments are not supported");break;default:throw console.warn(i),new Error("Invalid ink model type found")}return new zr(e,r)}createGroup(e,t){return new Xr(e)}getItem(e){return console.warn("InkModel getItem method is deprecated. Use oneof(getNode(id), getStroke(id), getSensorData(id), getBrush(id))."),this.registry.nodes[e]||this.registry.content[e]||this.registry.sensorData[e]||this.registry.brushes[e]}getNode(e){let t;if(M.isValidURL(e))t=this.registry.nodes[e];else{let r=[this,...Object.values(this.views)];for(let i of r){let r=K.createNodeURI(i,e);if(t=this.registry.nodes[r],t)break}}return t}getPath(e){return this.registry.content[e]}getStroke(e){return this.type==Hr.Type.STROKE?this.registry.content[e]:void 0}getSensorData(e){return this.registry.sensorData[e]}getBrush(e){return this.registry.brushes[e]}register(e,t){if(e instanceof Xr)e.children.forEach((e=>this.register(e)));else{if(!(e instanceof zr))throw new Error(`Register unknown node found: ${e.id}`);if(e.content instanceof ur){if(this.type!=Hr.Type.STROKE)throw new Error(`Incompatible element content found - ${e.content.constructor.name}. Content should be instance of Stroke.`)}else{if(!(e.content instanceof J))throw new Error(`Incompatible element content found - ${e.content.constructor.name}. Content should be ${this.type.name}.`);if(this.type!=Hr.Type.SENSOR_DATA)throw new Error(`Incompatible element content found - ${e.content.constructor.name}. Content should be instance of SensorData.`)}Object.defineProperty(e.content,"nodeID",{value:e.id,enumerable:!0,configurable:!0}),isFinite(t)&&t<this.content.length?this.content.insert(e.content,t):this.content.push(e.content),this.index(e.content)}this.index(e),this.resetViews()}index(e){let t,r=e.id;if(e instanceof $r){r=e.uri,t="nodes";let i=this.type.name;e instanceof Xr&&(i=`ol<${i}>`),Object.defineProperty(e,"dataType",{value:i,enumerable:!0})}else e instanceof ur?t="content":e instanceof J?t=this.type==Hr.Type.SENSOR_DATA?"content":"sensorData":e instanceof pe&&(t="brushes");if(!t)throw new Error("Expected item type is oneof(InkNode, Stroke, SensorData, Brush)");{let i=this.registry[t];if(i[r]){if(i[r]!=e)throw new Error(`Cannot register ${t} item with id ${r}. Already is available item with such identifier.`)}else i[r]=e}}unregister(e){this.resetViews(),e instanceof Xr?e.children.forEach((e=>this.unregister(e))):e instanceof zr&&(delete e.content.nodeID,delete this.registry.content[e.content.id],this.content.remove(e.content)),e==this.root?e.children.clear():delete this.registry.nodes[e.uri]}createView(e,t,r){let i=new Vr(e,this,t);return this.views[e]=i,r&&(i.knowledgeGraph=r,i.updateKnowledgeGraph(i.root)),i}resetViews(){if(!this.keepViews){for(let e in this.views)this.views[e].root.remove(),delete this.views[e];this.knowledgeGraph.length>0&&this.knowledgeGraphAnalyzer.clean()}}clear(){delete this.version,delete this.transform,this.unitScaleFactor=1,this.knowledgeGraphAnalyzer.clean(),this.knowledgeGraph.clear(),this.content.clear(),this.views={},this.registry.nodes={},this.registry.content={},this.registry.brushes={},this.registry.sensorData&&(this.registry.sensorData={}),this.root=this.createGroup(this.root.id),this.root.model=this,this.register(this.root)}clone(){let e=new Hr(this.type,this.root.id);if(e.id=this.id,e.props=this.props,e.transform=this.transform,e.unitScaleFactor=this.unitScaleFactor,e.knowledgeGraph=this.knowledgeGraph.clone(),this.type!=Hr.Type.STROKE)throw new Error("SENSOR_DATA model copy is not supported yet");Object.values(this.registry.sensorData).forEach((t=>e.index(t))),Object.values(this.registry.brushes).forEach((t=>e.index(t))),e.keepViews=!0,this.#E(this.root,e.root),delete e.keepViews;let t=Object.values(this.views);for(let r of t){let t=e.createView(r.name,r.root.id);this.#E(r.root,t.root)}return e}#E(e,t){let r=t.root.model;for(let i of e.children)if("PATH"==i.type){let e=r.model?r.model.getPath(i.content.id):i.content.clone(!0,!0),s=r.createElement(e,i.fragment);t.appendChild(s)}else{if("GROUP"!=i.type)throw new Error(`Unknown node type found: ${i.type}`);{let e=r.createGroup(i.id);t.appendChild(e),this.#E(i,e)}}}}class Zr extends Mr{constructor(){super()}encode(e){let t=this.format.InkStructure.create({type:this.format.StructureType[e.type.name],inkTree:this.format.InkTree.create({tree:this.encodeNodeTree(e)}),views:Object.values(e.views).map((e=>this.encodeView(e)))});return Mr.encode(t)}decode(e,t,r){if(!e)return;let i=Mr.decode(e,this.format.InkStructure),s=i.type==this.format.StructureType.STROKE?Hr.Type.STROKE:Hr.Type.SENSOR_DATA,n=s==Hr.Type.STROKE?t:r,o=new Hr(s,E.fromBytes(i.inkTree.tree.first.groupID)),a=i.inkTree.tree.first.bounds;if(a&&(o.root.bounds=new v(a.x,a.y,a.width,a.height)),this.decodeNodeTree(o,i.inkTree.tree.slice(1),n),i.views.forEach((e=>this.decodeView(e,o,n))),s==Hr.Type.STROKE)for(let e of r)o.index(e);return o}encodeView(e){return this.format.InkTree.create({name:e.name,tree:this.encodeNodeTree(e)})}decodeView(e,t,r,i){let s=e.tree.first,n=E.fromBytes(s.groupID);if(!t.views[e.name]||t.views[e.name].root.id!=n){let s=t.createView(e.name,n,i),o=e.tree.first.bounds;o&&(s.root.bounds=new v(o.x,o.y,o.width,o.height)),this.decodeNodeTree(s,e.tree.slice(1),r),s.invalid&&(console.warn(`Drop view ${s.uri} due to invalid structure`),delete t.views[s.name],t.knowledgeGraphAnalyzer.clean())}}encodeNodeTree(e){let t=[];return t.push(this.encodeNode(e.root,0)),this.addChildren(t,e,e.root.children,1),t}addChildren(e,t,r,i){r.forEach((r=>{let s=r instanceof zr?(t.model||t).content.indexOf(r.content):void 0;e.push(this.encodeNode(r,i,s)),r instanceof Xr&&this.addChildren(e,t,r.children,i+1)}))}encodeNode(e,t,r){let i=this.format.Node.create({depth:t,bounds:e.boundsValue});return e instanceof Xr?i.groupID=E.toBytes(e.id):i.index=r,e.fragment&&(i.interval=this.format.Interval.create({fromIndex:e.fragment.pointIndexStart,toIndex:e.fragment.pointIndexEnd,fromTValue:e.fragment.ts,toTValue:e.fragment.tf})),i}decodeNodeTree(e,t,r){if(e.invalid)return;let i=e.root,s=0,n={};for(let o of t){for(;s>=o.depth;)i=i.parent,s--;if(i.preventInvalidateBounds=!0,"groupID"==o.id){if(!(i instanceof Xr))throw new Error("Incorrect tree structure, a tree node is not a InkGroup instance and cannot contain child nodes.");i=i.appendChild(e.createGroup(E.fromBytes(o.groupID))),o.bounds&&(i.bounds=new v(o.bounds.x,o.bounds.y,o.bounds.width,o.bounds.height))}else{let t;if(o.interval){if(e instanceof Hr)throw new Error("Intervals are not applicable for InkModel, only View allow intervals");if(e.type==Hr.Type.STROKE){let i=r[o.index];try{t=i.spline.getFragment(o.interval.fromIndex,o.interval.fromTValue,o.interval.toIndex,o.interval.toTValue,!0),n[i.id]?n[i.id].forEach((e=>{if(t.overlaps(e))throw new Error(`Overlapped fragments are not allowed. ${t} overlaps ${e}`)})):n[i.id]=[],n[i.id].push(t)}catch(t){if(Hr.reservedViewNames.includes(e.name))return console.warn(`invalid path fragment content id: ${i.id} - ${t.message}`),void(e.invalid=!0);throw t}}else console.warn(`Intervals are not applicable for SensorData models, only Stroke models allow intervals. Model ${e.name} discards interval.`)}if(e.type==Hr.Type.STROKE&&Hr.reservedViewNames.includes(e.name)){let i=r[o.index],s=K.createNodeURI(e,i.id,t);if((e.model||e).getNode(s))return console.warn(`duplicate path node ${s}`),void(e.invalid=!0)}let s=e.createElement(r[o.index],t);i=i.appendChild(s)}delete i.parent.preventInvalidateBounds,s=o.depth}}}class qr extends Mr{constructor(){super()}encode(e={}){let t=this.format.Properties.create({properties:Object.keys(e).map((t=>this.format.Property.create({name:t,value:e[t]})))});return 0==t.properties.length?void 0:Mr.encode(t)}decode(e){if(!e)return;let t=Mr.decode(e,this.format.Properties);return Object.assign({},...t.properties.map((e=>({[e.name]:e.value}))))}}class Wr extends Mr{constructor(){super(),this.brushesCodec=new jr}async encode(e,t={},r={},i=Ve.SOURCE_OVER){let s=[];isFinite(r.red)&&s.push(Wr.ColorIndex.indexOf("RED")),isFinite(r.green)&&s.push(Wr.ColorIndex.indexOf("GREEN")),isFinite(r.blue)&&s.push(Wr.ColorIndex.indexOf("BLUE")),isFinite(r.alpha)&&s.push(Wr.ColorIndex.indexOf("ALPHA"));let n=M.encodeBitMask(s),o=this.format.InkTool.create({vectorBrush:e instanceof $e?this.brushesCodec.encodeBrush2D(e):void 0,rasterBrush:e instanceof rt?await this.brushesCodec.encodeBrushGL(e):void 0,context:this.format.PathPointContext.create({statics:Or.encodePathPointProperties(r,this.format.PathPointProperties.create()),dynamics:this.encodePathPointSettings(t),colorMask:n})});if(i!=Ve.SOURCE_OVER){let e=i.replace(/-/g,"_").toUpperCase();o.blendMode=this.format.BlendMode[e]}return Mr.encode(o)}decode(e){if(!e)return;let t=Mr.decode(e,this.format.InkTool),r=M.decodeBitMask(t.context.colorMask).map((e=>U.Property[Wr.ColorIndex[e]])),i=[U.Property.RED,U.Property.GREEN,U.Property.BLUE,U.Property.ALPHA].filter((e=>!r.includes(e)));return{brush:"vectorBrush"==t.brush?this.brushesCodec.decodeBrush2D(t.vectorBrush):this.brushesCodec.decodeBrushGL(t.rasterBrush),blendMode:Ve[this.format.BlendMode[t.blendMode]],statics:Or.decodePathPointProperties(t.context.statics,i),dynamics:this.decodePathPointSettings(t.context.dynamics)}}encodePathPointSettings(e){let t=this.format.PathPointSettings.create();for(let r in this.format.PathPointSettings.fields)e[r]&&!e[r].disabled&&(t[r]=this.encodePropertySettings(r,e[r]));return t}decodePathPointSettings(e){if(!e)return;let t={};for(let r in this.format.PathPointSettings.fields)e[r]&&(t[r]=this.decodePropertySettings(e[r]));return t}encodePropertySettings(e,t){let r=t=>{if(t)return this.format.Range.create({min:t.min,max:t.max,remapURI:this.getActionDescriptorName(e,"Remap",t.remap)})};return this.format.PropertySettings.create({value:r(t.value),velocity:r(t.velocity),pressure:r(t.pressure),altitude:r(t.altitude),radiusX:r(t.radiusX),radiusY:r(t.radiusY),resolveURI:this.getActionDescriptorName(e,"Resolve",t.resolve),dependencies:M.encodeBitMask((t.dependencies||[]).map((e=>Wr.InputPropertyTypeIndex.indexOf(H.getTypeName(e)))))||void 0})}getActionDescriptorName(e,t,r){if(r){if("function"==typeof r)throw new Error(`Encode '${e}' property failed. ${t} action name property is required. Please provide ActionDescriptor for it's definition.`);if("string"==typeof r)return r;if(r.name)return r.name;throw new Error(`Encode '${e}' property failed. ${t} action name property is required. Please provide ActionDescriptor for it's definition.`)}}decodePropertySettings(e){let t={},r=(e,r)=>{r&&(t[e]={min:r.min,max:r.max,remap:r.remapURI})};r("value",e.value),r("velocity",e.velocity),r("pressure",e.pressure),r("altitude",e.altitude),r("radiusX",e.radiusX),r("radiusY",e.radiusY),t.resolve=e.resolveURI;let i=M.decodeBitMask(e.dependencies).map((e=>H.Type[Wr.InputPropertyTypeIndex[e]]));return i.length>0&&(t.dependencies=i),t}}Wr.InputPropertyTypeIndex=Object.freeze([void 0,"PRESSURE","RADIUS_X","RADIUS_Y","AZIMUTH","ALTITUDE","ROTATION"]),Wr.ColorIndex=Object.freeze([void 0,"RED","GREEN","BLUE","ALPHA"]);let Kr=new TextEncoder;const Jr=3,Qr=1,ei=0,ti={extension:"uim",contentType:"application/vnd.wacom-ink.model",description:"Universal Ink Model",fourCC:{format:Kr.encode("UINK"),InkObject:Kr.encode("DATA"),Properties:Kr.encode("PRPS"),InputData:Kr.encode("INPT"),Brushes:Kr.encode("BRSH"),InkData:Kr.encode("INKD"),InkStructure:Kr.encode("INKS"),TripleStore:Kr.encode("KNWG")}};Object.defineProperty(ti,"version",{value:`${Jr}.${Qr}.${ei}`}),Object.defineProperty(ti,"serial",{value:new Uint8Array([Jr,Qr,ei])});class ri{#e;constructor(e,t,r,i,s,n,o,a){this.strokeID=e,t<i&&1==r&&(t++,r=0),i>t&&0==s&&(i--,s=1),this.segmentIndexStart=t,this.segmentIndexEnd=i,this.ts=r,this.tf=s,Object.defineProperty(this,"id",{get:()=>(this.#e||(this.#e=`${e}::${t}-${i}::${r.toFixed(5)}-${s.toFixed(5)}`),this.#e)}),this.bounds=n,this.shapesPath=a,this.splineParameters=o}toString(){return`node[${this.strokeID}](${this.segmentIndexStart}, ${this.ts}, ${this.segmentIndexEnd}, ${this.tf}) - ${this.bounds.toString()}`}toJSON(){return{strokeID:this.strokeID,segmentIndexStart:this.segmentIndexStart,segmentIndexEnd:this.segmentIndexEnd,ts:this.ts,tf:this.tf}}static fromJSON(e,t,r,i){return new ri(e.strokeID,e.segmentIndexStart,e.ts,e.segmentIndexEnd,e.tf,t,r,i)}}class ii{constructor(e){this.tree=e,this.brushAppliers={},this.splineInterpolator=new jt(!1,!0)}getBrushApplier(e){return this.brushAppliers[e.name]||(this.brushAppliers[e.name]=new $t(e)),this.brushAppliers[e.name]}buildStrokeNodes(e){let t,r,i=[],s=0,n=0,o=0,a=0,l=0,{interpolatedSpline:h,shapesPath:d}=e.pipeline||{};if(delete e.pipeline,!h||!d){let t=this.getBrushApplier(e.brush);h=this.splineInterpolator.process(e.spline),d=t.process(h)}if(0==d.length)return i;let c=[],p=[];for(let u=0;u<d.length;u++){let f=h.splineParameters[u],m=d[u].bounds;0==s?(n=f.segmentIndex,a=f.t,r=m):this.mustEndCurrentGroup(s,m,r)?(i.push(new ri(e.id,n,a,o,l,r,c,p)),c=[c.last],p=[p.last],n=o,a=l,r=m.union(t),s=1):r=this.fragmentBounds,c.push(f),p.push(d[u]),s++,t=m,o=f.segmentIndex,l=f.t}return i.push(new ri(e.id,n,a,o,l,r,c,p)),this.tree.load(i),i}mustEndCurrentGroup(e,t,r){if(delete this.fragmentBounds,e>50)return!0;let i=t.union(r);return e>1&&i.area>1e4||(!!(e>20&&ii.isTooSquare(i))||(this.fragmentBounds=i,!1))}static isTooSquare(e){let t=e.width/e.height;return t>.2&&t<5}}class si{constructor(){this.tree=new ut,this.nodeProducer=new ii(this.tree),this.strokes={},this.nodes={}}getNodes(e){return this.nodes[e]}getStroke(e){return this.strokes[e]}getBrushApplier(e){return this.nodeProducer.getBrushApplier(this.strokes[e].brush)}add(e){if(!(e.brush instanceof rt)){if(this.strokes[e.id])throw new Error(`SpatialContext stroke with id ${e.id} is already available`);this.strokes[e.id]=e,this.nodes[e.id]=this.nodeProducer.buildStrokeNodes(e)}}reload(e){this.tree.unload(this.nodes[e.id]),this.nodes[e.id]=this.nodeProducer.buildStrokeNodes(e)}remove(e){let t="string"==typeof e?e:e.id;this.tree.unload(this.nodes[t]),delete this.nodes[t],delete this.strokes[t]}replace(e,t){t.forEach((e=>this.add(e))),this.remove(e)}clone(e){let t=new si;t.nodeProducer.brushAppliers=this.nodeProducer.brushAppliers;let r=[];for(let i in this.strokes){let s=e.getStroke(i);if(!s)throw new Error(`Provided ink model do not provides stroke with id ${i}`);t.strokes[i]=s,t.nodes[i]=this.nodes[i].slice(),r=r.concat(t.nodes[i])}return t.tree.load(r),t}reset(){this.strokes={},this.nodes={},this.tree.clear()}}class ni{constructor(e,t,r){this.splineParameter=e,this.segmentIndex=t,this.on=r}toString(){return`SplineSplitPoint: ${this.splineParameter.segmentIndex} T:${this.splineParameter.t} -> ${this.on?"ON":"OFF"}, split by ${this.segmentIndex}`}toJSON(){return{splineParameter:this.splineParameter.toJSON(),segmentIndex:this.segmentIndex,on:this.on}}static fromJSON(e){return new ni(Ct.fromJSON(e.splineParameter),e.segmentIndex,e.on)}static compare(e,t){return e.splineParameter.segmentIndex<t.splineParameter.segmentIndex?-1:e.splineParameter.segmentIndex>t.splineParameter.segmentIndex?1:e.splineParameter.t<t.splineParameter.t?-1:e.splineParameter.t>t.splineParameter.t?1:0}}class oi{constructor(e=!1){let t;this.splitStrokes=e,Object.defineProperty(this,"context",{get:()=>{if(!t)throw new Error("Spatial context not found. Set value first.");return t},set:e=>{if(!e)throw new Error("Spatial context value is required");t=e},enumerable:!0}),this.splineInterpolator=new jt}processStrokePart(e,t,r,i){let s=e.splineParameters,n=e.shapesPath;1==n.length&&n.push(n[0]);let o=s[0],a=n[0],l=a.bounds;for(let h=1;h<n.length;h++){let d=n[h].bounds;if(d.union(l).intersects(i)){n[h].union(a).intersects(t)&&(this.splitStrokes?this.split(e,t,r,a,n[h],o,s[h]):this.selected.add(e.strokeID))}o=s[h],a=n[h],l=d}}split(e,t,r,i,s,n,o){let a,l,h=this.context.getStroke(e.strokeID),d=h.spline,c=d.segmentsCount-1,p=i.intersects(t),u=s.intersects(t);if(p&&u)0==n.segmentIndex&&n.t==d.ts&&(a=n),o.segmentIndex==c&&o.t==d.tf&&(l=o);else if(p)0==n.segmentIndex&&n.t==d.ts&&(a=n),l=this.seekNonIntersectingPartFromEnd(h,t,s,n,o);else if(u)a=this.seekNonIntersectingPartFromStart(h,t,i,n,o),o.segmentIndex==c&&o.t==d.tf&&(l=o);else{let e=this.seekNonIntersectingPartFromStart(h,t,i,n,o),r=this.seekNonIntersectingPartFromEnd(h,t,s,e,o);(e.segmentIndex==r.segmentIndex&&e.t<r.t||e.segmentIndex<r.segmentIndex)&&(a=e,l=r)}if(a||l){let e=this.splitPoints[h.id];e||(e=[],this.splitPoints[h.id]=e),a&&e.push(new ni(a,r,!1)),l&&e.push(new ni(l,r,!0))}}seekNonIntersectingPartFromStart(e,t,r,i,s){let n=i,o=s,a=i,l=this.context.getBrushApplier(e.id);for(;Ct.areDistantEnough(n,o,this.splineParameterDistanceThreshold);){let i=Ct.calcMiddleOfSegment(n,o),s=this.splineInterpolator.calculateInterpolatedPoint(e.spline,i.segmentIndex,i.t);l.applyBrush(s).union(r).intersects(t)?o=i:(n=i,a=i)}return a}seekNonIntersectingPartFromEnd(e,t,r,i,s){let n=i,o=s,a=s,l=this.context.getBrushApplier(e.id);for(;Ct.areDistantEnough(n,o,this.splineParameterDistanceThreshold);){let i=Ct.calcMiddleOfSegment(n,o),s=this.splineInterpolator.calculateInterpolatedPoint(e.spline,i.segmentIndex,i.t);l.applyBrush(s).union(r).intersects(t)?n=i:(o=i,a=i)}return a}reset(e){e&&(this.context=e),this.fragments={},this.selected=new Set,this.splitStrokes&&(this.splitPoints={}),this.context.tree.canvas&&this.context.tree.canvas.refresh()}}class ai extends oi{splineParameterDistanceThreshold=.01;constructor(e=ai.Mode.WHOLE_STROKE){super(e!=ai.Mode.WHOLE_STROKE),this.mode=e}async intersect(e,t){let r,i,s;if(e instanceof ur){let t=e.pipeline||{};t.shapesPath?s=t.shapesPath:(r=t.interpolatedSpline||this.splineInterpolator.process(e.spline),i=this.context.nodeProducer.getBrushApplier(e.brush))}else{if(!t)throw new Error("brush expected");if(!(t instanceof $e))throw new Error("brush should be Brush2D instance");if(e instanceof Nt)i=this.context.nodeProducer.getBrushApplier(t),r=e;else{if(!(e instanceof Dt))throw new Error("Expected input should be instance of Stroke, InterpolatedSpline, Spline");r=this.splineInterpolator.process(e),i=this.context.nodeProducer.getBrushApplier(t)}}return s||(s=i.process(r)),this.reset(),this.context.tree.canvas&&this.context.tree.canvas.fillShape(s),await this.processNodes(s),this.mode==ai.Mode.PARTIAL_STROKE&&this.buildFragments(),{type:"INTERSECTION",intersected:this.fragments,selected:Array.from(this.selected),length:Object.keys(this.fragments).length+this.selected.size}}async processNodes(e){if(0==e.length)return;1==e.length&&e.push(e[0]);let t=e[0],r=t.bounds,i={},s=this.mode==ai.Mode.PARTIAL_STROKE&&this.splitPointsProducer;for(let n=1;n<e.length;n++){let o=e[n].bounds,a=o.union(r),l=this.context.tree.search(a);if(l.length>0){let r=e[n].union(t),o=n-1;if(s)for(let e of l)i[e.id]||(i[e.id]=[]),i[e.id].push({node:e,eraserHull:r,eraserSegmentIndex:o,eraserSegmentBounds:a});else for(let e of l)this.processStrokePart(e,r,o,a)}t=e[n],r=o}if(s){let e=[];Object.values(i).forEach((t=>{let r=this.encodeNodeProcessingInfo(t);e.push(r)})),e.length>0&&(this.splitPoints=await this.splitPointsProducer.build(e))}}buildFragments(){for(let e in this.splitPoints){let t=this.context.getStroke(e),r=this.convertSplitPointsToFragments(t);0==r.length?this.selected.add(t.id):this.fragments[t.id]=r}}convertSplitPointsToFragments(e){let t=[],r=this.splitPoints[e.id];if(0==r.length)return t;r.sort(ni.compare);let i,s,n,o=new Set,a=e.spline,l=!0;r[0].on?(n=1,i=r[0].splineParameter):(n=0,i=new Ct(0,a.ts));for(let e=n;e<r.length;e++){let n=r[e];if(n.on)o.delete(n.segmentIndex),0==o.size&&(i=n.splineParameter,l=!0);else if(o.add(n.segmentIndex),l&&(s=n.splineParameter,l=!1,i.segmentIndex!=s.segmentIndex||i.t!=s.t)){let e=Ot.getInstance(a,i,s);t.push(e)}}if(l&&(s=new Ct(a.segmentsCount-1,a.tf),i.segmentIndex!=s.segmentIndex||i.t!=s.t)){let e=Ot.getInstance(a,i,s);t.push(e)}return t}encodeNodeProcessingInfo(e){let t={splineParameterDistanceThreshold:this.splineParameterDistanceThreshold,input:[]};for(let r of e){if(!t.target){let e=this.context.getStroke(r.node.strokeID);e.spline.id=e.id,t.target={stroke:{brush:e.brush.toJSON(),spline:e.spline.toJSON()},bounds:r.node.bounds.toJSON(),shapesPath:r.node.shapesPath.map((e=>e.toJSON())),splineParameters:r.node.splineParameters.map((e=>e.toJSON()))}}t.input.push({node:r.node.toJSON(),eraserHull:r.eraserHull.toJSON(),eraserSegmentIndex:r.eraserSegmentIndex,eraserSegmentBounds:r.eraserSegmentBounds.toJSON()})}return t}static decodeNodeProcessingInfo(e){let{target:t,input:r,splineParameterDistanceThreshold:i}=e,s=$e.fromJSON(t.stroke.brush),n=Dt.fromJSON(t.stroke.spline),o=new ur(s,n),a={bounds:v.fromRect(t.bounds),shapesPath:t.shapesPath.map((e=>Le.fromJSON(e))),splineParameters:t.splineParameters.map((e=>Ct.fromJSON(e)))};return r=r.map((e=>({node:ri.fromJSON(e.node,a.bounds,a.splineParameters,a.shapesPath),eraserHull:Le.fromJSON(e.eraserHull),eraserSegmentIndex:e.eraserSegmentIndex,eraserSegmentBounds:v.fromRect(e.eraserSegmentBounds)}))),{stroke:o,input:r,splineParameterDistanceThreshold:i}}}Object.defineEnum(ai,"Mode",["WHOLE_STROKE","PARTIAL_STROKE"]);class li{constructor(){this.contour,this.lastPointIndex,this.segmentIndex,this.p0,this.p1,Object.defineProperty(this,"bounds",{get:()=>v.ofEdges(this.p0.x,this.p0.y,this.p1.x,this.p1.y)})}reset(e){this.contour=e,this.segmentIndex=-1,this.lastPointIndex=e.length-1,this.p0=U.createInstance(e.layout),this.p1=U.createInstance(e.layout)}moveNext(){return this.segmentIndex++,this.segmentIndex<this.lastPointIndex?(this.p0.fill(this.segmentIndex,this.contour.points,this.contour.layout,this.contour.pointProps),this.p1.fill(this.segmentIndex+1,this.contour.points,this.contour.layout,this.contour.pointProps),!0):this.segmentIndex==this.lastPointIndex&&(this.p0.fill(this.segmentIndex,this.contour.points,this.contour.layout,this.contour.pointProps),this.p1.fill(0,this.contour.points,this.contour.layout,this.contour.pointProps),!0)}}class hi extends oi{constructor(e=hi.Mode.WHOLE_STROKE){super(e!=hi.Mode.WHOLE_STROKE),this.mode=e}select(e){let t;if(1==e.spline.segmentsCount)t=e.path;else{let r=new Le(e.spline);t=r.simplify(),0==t.length&&(t=new nt(r))}return this.selection=t,this.selectionBounds=t.bounds,this.reset(),this.context.tree.canvas&&this.context.tree.canvas.fillShape(t),this.splitStrokesWithSelectionContours(),this.mode!=hi.Mode.WHOLE_STROKE&&this.buildFragments(),this.fillStrokesEnclosedBySelection(),{type:"SELECTION",contours:this.selection,bounds:this.selectionBounds,intersected:this.fragments,selected:Array.from(this.selected),length:Object.keys(this.fragments).length+this.selected.size}}splitStrokesWithSelectionContours(){let e=new li,t=Le.createInstance([0,0,0,0]);for(let r of this.selection)for(e.reset(r.shape);e.moveNext();){t.shape.points[0]=e.p0.x,t.shape.points[1]=e.p0.y,t.shape.points[2]=e.p1.x,t.shape.points[3]=e.p1.y;let r=e.bounds,i=this.context.tree.search(r);for(let s of i)this.processStrokePart(s,t,e.segmentIndex,r)}}buildFragments(){for(let e in this.splitPoints){let t=this.context.getStroke(e);this.fragments[t.id]=this.convertSplitPointsToFragments(t)}this.markStrokeFragmentsInsideSelection(),this.mode!=hi.Mode.WHOLE_STROKE&&Object.keys(this.fragments).forEach((e=>this.updateFragments(e)))}convertSplitPointsToFragments(e){let t=[],r=this.splitPoints[e.id];if(0==r.length)return t;r.sort(ni.compare);let i=new Set,s=e.spline,n=new Ct(0,s.ts);for(let e of r){if(e.on&&i.delete(e.segmentIndex),0==i.size&&!e.splineParameter.equals(n)){let r=Ot.getInstance(s,n,e.splineParameter);e.on&&(r.overlapped=!0),t.push(r),n=e.splineParameter}e.on||i.add(e.segmentIndex)}let o=new Ct(s.segmentsCount-1,s.tf);if(!o.equals(n)){let e=Ot.getInstance(s,n,o);t.push(e)}return t}markStrokeFragmentsInsideSelection(){for(let e in this.fragments){let t=this.context.getStroke(e),r=this.fragments[e];for(let e of r)e.overlapped||this.isStrokeWithinSelectionContours(t,e)&&(e.inside=!0,this.selected.add(e.id))}}updateFragments(e){let t,r=[];for(let i of this.fragments[e])switch(this.mode){case hi.Mode.PARTIAL_STROKE:i.overlapped||r.push(i);break;case hi.Mode.PARTIAL_INCLUSIVE:t?i.inside?t=i.union(t):i.overlapped?(i=t.union(i),t=null,r.push(i)):(this.selected.add(t.id),r.push(t),t=null,r.push(i)):i.inside||i.overlapped?t=i:r.push(i);break;case hi.Mode.PARTIAL_EXCLUSIVE:t?i.inside?(r.push(t),r.push(i),t=null):t=t.union(i):i.inside?r.push(i):t=i;break;default:throw console.warn(this.strategy),new Error("Invalid strategy found")}if(t&&r.push(t),1==r.length&&this.mode!=hi.Mode.PARTIAL_STROKE)if(this.mode==hi.Mode.PARTIAL_EXCLUSIVE)delete this.fragments[e];else{let t=r.first;(t.overlapped||this.selected.has(t.id))&&(this.selected.delete(t.id),delete this.fragments[e],this.selected.add(e))}e in this.fragments&&(this.fragments[e]=r)}fillStrokesEnclosedBySelection(){let e=this.context.tree.search(this.selectionBounds);for(let t of e){if(t.strokeID in this.fragments)continue;if(this.selected.has(t.strokeID))continue;let e=this.context.getStroke(t.strokeID);this.isStrokeWithinSelectionContours(e)&&this.selected.add(t.strokeID)}}isStrokeWithinSelectionContours(e,t){t||(t=e.spline.getFragment());let r=new Ct(t.segmentIndexStart,t.ts),i=new Ct(t.segmentIndexEnd,t.tf),s=Ct.calcMiddleOfSegment(r,i),n=this.splineInterpolator.calculateInterpolatedPoint(e.spline,s.segmentIndex,s.t),o=this.context.getBrushApplier(e.id).applyBrush(n),a=hi.getConvexPolyInternalPoint(o);return this.isPointWithinSelectionContours(a)}isPointWithinSelectionContours(e){for(let t of this.selection)if(t.containsPoint(e))return!0;return!1}static getConvexPolyInternalPoint(e){let t=e.shape.getPoint(0),r=e.shape.getPoint(Math.floor(e.shape.length/2));return{x:.5*(t.x+r.x),y:.5*(t.y+r.y)}}}Object.defineEnum(hi,"Mode",["WHOLE_STROKE","PARTIAL_STROKE","PARTIAL_INCLUSIVE","PARTIAL_EXCLUSIVE"]);class di extends zt{static WORKER_NAME="SplitPointsProvider";constructor(){super(di.WORKER_NAME,di.buildWorkerURL(),zt.WorkerType.CLASSIC),this.actions={}}static buildWorkerURL(){if(("undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("digital-ink-min.cjs",document.baseURI).href).contains("/wacom-src/"))return`/node_modules/digital-ink/workers/${di.WORKER_NAME}.js`;if("function"!=typeof DedicatedWorkerGlobalScope){let e="undefined"==typeof __location?"undefined"==typeof document?new(require("url").URL)("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("digital-ink-min.cjs",document.baseURI).href:__location;return e=e.substring(0,e.lastIndexOf("/")),e.endsWith("workers")||(e+="/workers"),e+=`/${di.WORKER_NAME}`,"undefined"==typeof navigator?e+=".mjs":e+=".js",e}}async build(e){if(0==e.length)return;let t=this.nextID,r={};return this.actions[t]={splitPoints:r,queue:e.slice(),expected:e.length,total:e.length},this.updateProgress(0,e.length),await this.broadcast("BUILD",t),r}buildRequestMessage(e,t){let r={action:e,actionID:t},i=this.actions[t];if("BUILD"!=e)throw new Error(`Unknow data action found: ${e}`);{let e=i.queue.shift();if(!e)return;r.data=e}return r}recieve(e){let t=this.actions[e.actionID];if(t.expected--,"BUILD"!==e.action)throw new Error(`Unknow data action found: ${e.action}`);if(this.update(e.actionID,e.strokeID,e.splitPoints),t.expected>0){let t=this.buildRequestMessage(e.action,e.actionID);t&&this.send(e.worker,t)}0==t.expected&&(delete this.actions[e.actionID],this.resolve(e.actionID))}update(e,t,r){if(!r)return;r=r.map((e=>ni.fromJSON(e)));let i=this.actions[e];i.splitPoints[t]?i.splitPoints[t].push(...r):i.splitPoints[t]=r;let s=100*(i.total-i.expected)/i.total;this.updateProgress(s,i.expected)}updateProgress(e,t){}}const{PathProducer:ci,Smoother:pi,SplineProducer:ui,DistanceBasedInterpolator:fi,CurvatureBasedInterpolator:mi,BrushApplier:gi,ConvexHullChainProducer:yi,ConvexHullChainProducerAsync:bi,PolygonMerger:Ei,PolygonSimplifier:Pi}=er,Ii=Kt;exports.BlendMode=Ve,exports.Brush2D=$e,exports.BrushApplier=gi,exports.BrushGL=rt,exports.BrushPrototype=_e,exports.Color=ve,exports.ColorsBox=ot,exports.ConvexHullChainProducer=yi,exports.ConvexHullChainProducerAsync=bi,exports.CurvatureBasedInterpolator=mi,exports.DistanceBasedInterpolator=fi,exports.Environment=Y,exports.FixedValuePrecisionCalculator=class extends It{constructor(e=2,t=!1){super(),this.precision=e,this.autoAdjustOnIntegerOverflow=t}calculatePrecision(e,t){if(!this.autoAdjustOnIntegerOverflow)return this.precision;let r=this.precision,i=NaN;for(;isNaN(i);){if(i=vt.calculateError(e,r),0==r){if(isNaN(i))throw new Error("Can't calculate appropriate precision value for the provided float sequence.");break}r--}return r}},exports.InkBuilder=or,exports.InkBuilderAsync=lr,exports.InkCanvas2D=Er,exports.InkCanvasGL=vr,exports.InkCodec=class{constructor(){this.dataCodec=new Br,this.inputCodec=new Ur,this.brushesCodec=new jr,this.structureCodec=new Zr,this.tripleStoreCodec=new Gr,this.propsCodec=new qr,this.inkToolCodec=new Wr,this.compatibilityProvider=new Fr,this.riffEncoder=new yt(ti.fourCC.format,ti.serial),this.riffDecoder=new Pt,Object.defineProperty(this,"precisionCalculator",{get:()=>this.dataCodec.precisionCalculator,set:e=>this.dataCodec.precisionCalculator=e,enumerable:!0})}async encodeInkModel(e,t=gt.CompressionType.NONE){return this.riffEncoder.add(this.propsCodec.encode(e.props),{version:ti.serial,fourCC:ti.fourCC.Properties,contentType:gt.ContentType.PROTO,compressionType:t}),this.riffEncoder.add(this.inputCodec.encode(e.sensorData),{version:ti.serial,fourCC:ti.fourCC.InputData,contentType:gt.ContentType.PROTO,compressionType:t}),this.riffEncoder.add(await this.brushesCodec.encode(e.brushes),{version:ti.serial,fourCC:ti.fourCC.Brushes,contentType:gt.ContentType.PROTO,compressionType:t}),this.riffEncoder.add(this.dataCodec.encode(e.strokes,e.unitScaleFactor,e.transform),{version:ti.serial,fourCC:ti.fourCC.InkData,contentType:gt.ContentType.PROTO,compressionType:t}),this.riffEncoder.add(this.tripleStoreCodec.encode(e.knowledgeGraph),{version:ti.serial,fourCC:ti.fourCC.TripleStore,contentType:gt.ContentType.PROTO,compressionType:t}),this.riffEncoder.add(this.structureCodec.encode(e),{version:ti.serial,fourCC:ti.fourCC.InkStructure,contentType:gt.ContentType.PROTO,compressionType:t}),await this.riffEncoder.encode()}async decodeInkModel(e,t){e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=await this.riffDecoder.decode(e),i=r.asProps();return this.buildInkModel(i,r.version,t)}buildInkModel(e,t,r){let i=this.compatibilityProvider.decodeInkObject(e,t),s=this.tripleStoreCodec.decode(i.KnowledgeGraph);if(r){let e=(r.type==Hr.Type.STROKE?i.InkData.strokes:i.InputData.sensorData).map((e=>r.getPath(e.id)));i.InkStructure.views.forEach((t=>this.decodeView(t,r,e,s)))}else{let e=this.inputCodec.decode(i.InputData),n=this.brushesCodec.decode(i.Brushes),o=this.dataCodec.decode(i.InkData,n,e);(r=this.structureCodec.decode(i.InkStructure,o?o.strokes:[],e)).version=t,o&&(r.unitScaleFactor=o.unitScaleFactor,r.transform=o.transform,r.brushes=Object.values(n)),s&&(r.knowledgeGraph=s),i.Properties&&(r.props=this.propsCodec.decode(i.Properties))}return r}encodeInputData(e){return this.inputCodec.encode(e)}decodeInputData(e){return this.inputCodec.decode(e)}encodeInkData(e){return this.dataCodec.ignoreSensorData=!0,this.dataCodec.encode(e)}decodeInkData(e){this.dataCodec.cloneStroke=!0;let t=this.dataCodec.decode(e);return t?t.strokes:[]}async encodeBrushes(e){return await this.brushesCodec.encode(e)}decodeBrushes(e){return Object.values(this.brushesCodec.decode(e))}encodeProperties(e){return this.propsCodec.encode(e)}decodeProperties(e){return this.propsCodec.decode(e)}encodeTripleStore(e){return this.tripleStoreCodec.encode(e)}decodeTripleStore(e){return this.tripleStoreCodec.decode(e)}static async buildJSON(e,t="InkModel"){e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r={type:t},i={};if("InkModel"==t){let t=new Pt,s=await t.decode(e),n=s.asProps(),o=Dr[s.version].format,a=new TextDecoder;r.version=s.version,r.format=a.decode(ti.fourCC.format),n.data?i.InkObject=n.data:(n.inks&&(i.InkStructure=n.inks),n.inpt&&(i.InputData=n.inpt),n.inkd&&(i.InkData=n.inkd),n.brsh&&(i.Brushes=n.brsh),n.prps&&(i.Properties=n.prps),n.knwg&&(i.TripleStore=n.knwg));for(let e in i){let t=Mr.decode(i[e],o[e]);i[e]=t.toJSON()}}else{let s=Dr.latest,n=Mr.decode(e,s[t]);if(!n)throw new Error(`Build type missmatch - ${t}, expected oneof(InkModel, InputData, InkData, Brushes, Properties, TripleStore, InkTool, InkOperation)`);r.version=Dr.evolution.last,i=n.toJSON()}return{head:r,body:i}}decodeJSON(e){let t,{type:r,version:i}=e.head,s=e.body;if("InkModel"==r){let e={},r=new TextDecoder,n=Dr[i].format;for(let t in s){let i=Mr.decode(s[t],n[t]);e[r.decode(ti.fourCC[t]).toLowerCase()]=Mr.encode(i)}t=this.buildInkModel(e,i)}else{let e=Dr.latest,i=Mr.decode(s,e[r]);switch(r){case"InputData":t=this.decodeInputData(i);break;case"InkData":t=this.decodeInkData(i);break;case"Brushes":t=this.decodeBrushes(i);break;case"Properties":t=this.decodeProperties(i);break;case"TripleStore":t=this.decodeTripleStore(i);break;case"InkTool":t=this.inkToolCodec.decode(i);break;case"InkOperation":if(!this.inkOperationCodec)throw new Error("InkCodec.inkOperationCodec property is not found");this.inkOperationCodec.decode(void 0,i);break;default:throw new Error(`input type missmatch - ${r}, expected oneof(InkModel, InputData, InkData, Brushes, Properties, TripleStore, InkTool, InkOperation)`)}}return t}},exports.InkController=y,exports.InkInputProvider=I,exports.InkModel=Hr,exports.InkObjectFormat=ti,exports.InkOperation=class extends Mr{constructor(){super(),this.dataCodec=new Br}composeStyle(e,t=0,r){let i=this.format.InkOperation.create({compose:this.format.InkOperation.Compose.create({style:this.encodeStyle(e),pointerID:t,strokeID:r?E.toBytes(r):void 0})});return Mr.encode(i)}composeSegment(e,t=!1,r=0,i){if(!e||0==e.length)return;let s=this.format.InkOperation.create({compose:this.format.InkOperation.Compose.create({segment:this.format.InkSegment.create({ink:this.encodeInkPath(e),complete:t}),pointerID:r,strokeID:i?E.toBytes(i):void 0})});return Mr.encode(s)}composeAbort(e=0,t){let r=this.format.InkOperation.create({compose:this.format.InkOperation.Compose.create({abort:!0,pointerID:e,strokeID:t?E.toBytes(t):void 0})});return Mr.encode(r)}add(e){e instanceof ur&&(e=[e]);let t=this.format.InkOperation.create({add:this.format.InkOperation.Add.create({strokes:e.map((e=>this.encodeInkStroke(e)))})});return Mr.encode(t)}remove(e){let t=this.buildStrokesContext(e);if(!t)return;let r=this.format.InkOperation.create({remove:this.format.InkOperation.Remove.create({context:t})});return Mr.encode(r)}update(e,t){let r=this.buildStrokesContext(e);if(!r)return;let i=this.format.InkOperation.create({update:this.format.InkOperation.Update.create({context:r,style:this.encodeStyle(t,!0)})});return Mr.encode(i)}replace(e){let t=Object.keys(e);if(0==t.length)return;let r=this.format.InkOperation.create({replace:this.format.InkOperation.Replace.create({replacements:t.map((t=>this.format.Replacement.create({strokeID:E.toBytes(t),strokes:e[t].map((e=>this.encodeInkStroke(e)))})))})});return Mr.encode(r)}split(e,t){let r=Object.keys(e);if(0==r.length)return;let i=this.format.InkOperation.create({split:this.format.InkOperation.Split.create({intersections:r.map((t=>this.encodeIntersection(t,e[t]))),affectedArea:t})});return Mr.encode(i)}selectSelector(e){let t=this.format.InkOperation.create({select:this.format.InkOperation.Select.create({selector:this.encodeInkStroke(e)})});return Mr.encode(t)}selectSelection(e){let t=this.buildStrokesContext(e);if(!t)return this.selectAbort();let r=this.format.InkOperation.create({select:this.format.InkOperation.Select.create({selection:t})});return Mr.encode(r)}selectAbort(){let e=this.format.InkOperation.create({select:this.format.InkOperation.Select.create({abort:!0})});return Mr.encode(e)}updateSelectionTransform(e){if(e.isIdentity)return;let t=this.format.InkOperation.create({updateSelection:this.format.InkOperation.UpdateSelection.create({transform:this.dataCodec.encodeMatrix(e)})});return Mr.encode(t)}updateSelectionComplete(){let e=this.format.InkOperation.create({updateSelection:this.format.InkOperation.UpdateSelection.create({complete:!0})});return Mr.encode(e)}transform(e,t){let r=this.buildStrokesContext(e);if(!r)return;if(t.isIdentity)return;let i=this.format.InkOperation.create({transform:this.format.InkOperation.Transform.create({context:r,matrix:this.dataCodec.encodeMatrix(t)})});return Mr.encode(i)}decode(e,t){let r=Mr.decode(t,this.format.InkOperation),i=r.operation;switch(r=r[i],i){case"compose":{let t,i=r.pointerID;switch(r.strokeID.length>0&&(t=E.fromBytes(r.strokeID)),r.stage){case"style":return this.onComposeStyle(e,this.decodeStyle(r.style,!1),i,t);case"segment":return this.onComposeSegment(e,this.decodeInkPath(r.segment.ink),r.segment.complete,i,t);case"abort":return this.onComposeAbort(e,i,t);default:throw new Error(`Unknown compose stage found: ${r.stage}`)}}case"add":return this.onAdd(e,r.strokes.map((e=>this.decodeInkStroke(e))));case"remove":return this.onRemove(e,this.getContextStrokes(r.context));case"update":return this.onUpdate(e,this.getContextStrokes(r.context),this.decodeStyle(r.style,!0));case"replace":{let t={};return r.replacements.forEach((e=>{let r=E.fromBytes(e.strokeID);t[r]=e.strokes.map((e=>this.decodeInkStroke(e)))})),this.onReplace(e,t)}case"split":{let t={},i=new v(r.affectedArea.x,r.affectedArea.y,r.affectedArea.width,r.affectedArea.height);return r.intersections.forEach((e=>{let r=this.decodeIntersection(e);t[r.id]=r.fragments})),this.onSplit(e,t,i)}case"select":switch(r.stage){case"selector":return this.onSelectSelector(e,this.decodeInkStroke(r.selector));case"selection":return this.onSelectSelection(e,this.getContextStrokes(r.selection));case"abort":return this.onSelectAbort(e);default:throw new Error(`Unknown select stage found: ${r.stage}`)}case"updateSelection":switch(r.stage){case"transform":return this.onUpdateSelectionTransform(e,this.dataCodec.decodeMatrix(r.transform));case"complete":return this.onUpdateSelectionComplete(e);default:throw new Error(`Unknown selection update found: ${r.stage}`)}case"transform":return this.onTransform(e,this.getContextStrokes(r.context),this.dataCodec.decodeMatrix(r.matrix));default:throw new Error(`Unknown ink operation found: ${i}`)}}buildStrokesContext(e){if(e&&(Array.isArray(e)||(e=[e]),0!=e.length))return this.format.StrokesContext.create({context:e.map((e=>"string"==typeof e?E.toBytes(e):E.toBytes(e.id)))})}getContextStrokes(e){return e.context.map((e=>{let t=E.fromBytes(e),r=this.getStroke(t);return r||console.warn(`Stroke with id ${t} is not provided from getStroke implementation`),r}))}traceDecode(){this.debug||(this.debug=!0,this.onComposeStyle=console.log.bind(console,"onComposeStyle"),this.onComposeSegment=console.log.bind(console,"onComposeSegment"),this.onComposeAbort=console.log.bind(console,"onComposeAbort"),this.onAdd=console.log.bind(console,"onAdd"),this.onRemove=console.log.bind(console,"onRemove"),this.onUpdate=console.log.bind(console,"onUpdate"),this.onReplace=console.log.bind(console,"onReplace"),this.onSplit=console.log.bind(console,"onSplit"),this.onSelectSelector=console.log.bind(console,"onSelectSelector"),this.onSelectSelection=console.log.bind(console,"onSelectSelection"),this.onSelectAbort=console.log.bind(console,"onSelectAbort"),this.onUpdateSelectionTransform=console.log.bind(console,"onUpdateSelectionTransform"),this.onUpdateSelectionComplete=console.log.bind(console,"onUpdateSelectionComplete"),this.onTransform=console.log.bind(console,"onTransform"))}getStroke(e){throw new Error("InkOperation.getStroke(id) is abstract and should be implemented")}onComposeStyle(e,t,r,i){throw new Error("InkOperation.onComposeStyle(user, style, pointerID, strokeID) should be implemented")}onComposeSegment(e,t,r,i,s){throw new Error("InkOperation.onComposeSegment(user, segment, endStroke, pointerID, strokeID) should be implemented")}onComposeAbort(e,t,r){throw new Error("InkOperation.onComposeAbort(user, pointerID, strokeID) should be implemented")}onAdd(e,t){throw new Error("InkOperation.onAdd(user, strokes) should be implemented")}onRemove(e,t){throw new Error("InkOperation.onRemove(user, strokes) should be implemented")}onUpdate(e,t,r,i){throw new Error("InkOperation.onUpdate(user, strokes, style, edit) should be implemented")}onReplace(e,t){throw new Error("InkOperation.onReplace(user, replacements) should be implemented")}onSplit(e,t,r){throw new Error("InkOperation.onSplit(user, intersections, affectedArea) should be implemented")}onSelectSelector(e,t){throw new Error("InkOperation.onSelectSelector(user, selector) should be implemented")}onSelectSelection(e,t){throw new Error("InkOperation.onSelectSelection(user, strokes) should be implemented")}onSelectAbort(e){throw new Error("InkOperation.onSelectAbort(user) should be implemented")}onUpdateSelectionTransform(e,t){throw new Error("InkOperation.onUpdateSelectionTransform(user, transform) should be implemented")}onUpdateSelectionComplete(e){throw new Error("InkOperation.onUpdateSelectionComplete(user) should be implemented")}onTransform(e,t,r){throw new Error("InkOperation.onTransform(user, strokes, transform) should be implemented")}encodeStyle(e,t=!1){let r=this.format.Style.create();if(e.color)r.color=Or.rgba(e.color.red,e.color.green,e.color.blue,e.color.alpha);else if(!t)throw new Error("Style property color is required");if(e.brush){if(r.brushURI=e.brush.name,e.brush instanceof rt)if(e.randomSeed){if(t)throw new Error("Style property randomSeed is not applicable for update, it is immutable");r.randomSeed=e.randomSeed}else if(!t)throw new Error("Style property randomSeed is required")}else if(!t)throw new Error("Style property brush is required");if(e.renderMode)e.renderMode!=ur.RenderMode.SOURCE_OVER&&(r.renderModeURI=e.renderMode);else if(e.blendMode)e.blendMode!=Ve.SOURCE_OVER&&(r.renderModeURI=ur.RenderMode.get(e.blendMode));else if(!t)throw new Error("Style property oneof(renderMode, blendMode) is required");return r}decodeStyle(e,t=!1){let r={};if(e.color&&(r.color=ve.fromColor(Or.fromRGBA(e.color))),e.brushURI){let i=new ce(e.brushURI);if(r.brush=i.value,r.brush instanceof rt)if(e.randomSeed)t?console.warn("Style property randomSeed is not applicable for update, it is immutable"):r.randomSeed=e.randomSeed;else if(!t)throw new Error("Style property randomSeed is required")}return e.renderModeURI&&(r.renderMode=e.renderModeURI),r}encodeInkStroke(e){return this.format.InkStroke.create({path:this.dataCodec.encodeStroke(e),ink:this.encodeInkPath(e.path)})}decodeInkStroke(e){return this.dataCodec.decodeStroke(e.path,{inkPath:e.ink?this.decodeInkPath(e.ink):void 0})}encodeInkPath(e,t){let r=this.format.InkPath.create();if(e instanceof Gt)r.polygons=this.format.PolygonArray.create({data:e.map((e=>this.format.Polygon.create({shape:this.format.Path.create({data:e.shape.points}),holes:e.holes.map((e=>this.format.Path.create({data:e.points})))})))});else if(e instanceof Nt)r.path=this.format.Path.create({layout:M.encodeBitMask(e.layout.map((e=>e.value+1))),pointProps:Or.encodePathPointProperties(e.pointProps,this.format.PathPointProperties.create()),data:e.points});else{if(!(e instanceof Dt))throw new Error("Expected path type - oneof(InkPath2D, InterpolatedSpline, Spline), not found");if(t)throw new Error("spline already provided through path property");t=e}return t&&(r.spline=this.format.Path.create({layout:M.encodeBitMask(t.layout.map((e=>e.value+1))),pointProps:Or.encodePathPointProperties(t.pointProps,this.format.PathPointProperties.create()),data:t.points})),r}decodeInkPath(e){let t;if("polygons"==e.data)t=new Gt(...e.polygons.data.map((e=>Le.createInstance(e.shape.data,e.holes.map((e=>e.data))))));else if("path"==e.data){let r=M.decodeBitMask(e.path.layout).map((e=>U.Property[e-1])),i=Or.decodePathPointProperties(e.path.pointProps,r);t=Nt.createSharedInstance(r,e.path.data,i)}if(e.spline){let r=M.decodeBitMask(e.spline.layout).map((e=>U.Property[e-1])),i=Or.decodePathPointProperties(e.spline.pointProps,r),s=Dt.createSharedInstance(r,e.spline.data,i);t?t.spline=s:t=s}return t}encodeIntersection(e,t){return this.format.Intersection.create({strokeID:E.toBytes(e),fragments:t.map((e=>this.format.PathFragment.create({id:E.toBytes(e.id),pointIndexStart:e.pointIndexStart,pointIndexEnd:e.pointIndexEnd,ts:e.ts,tf:e.tf})))})}decodeIntersection(e){let t=E.fromBytes(e.strokeID),r=this.getStroke(t);if(!r)throw new Error(`Stroke with id ${t} is not provided from getStroke implementation`);return{id:E.fromBytes(e.strokeID),fragments:e.fragments.map((e=>{let t=r.spline.getFragment(e.pointIndexStart,e.ts,e.pointIndexEnd,e.tf,!0);return t.id=E.fromBytes(e.id),t}))}}},exports.InkPath2D=Gt,exports.InkPathProducer=yr,exports.InkToolCodec=Wr,exports.InputContext=W,exports.InputDevice=ee,exports.InputListener=B,exports.InterpolatedSpline=Nt,exports.Intersector=ai,exports.Matrix=N,exports.OffscreenCanvasGL=Sr,exports.Path=Ae,exports.PathPoint=U,exports.PathPointContext=Ye,exports.PathProducer=ci,exports.PathSegment=rr,exports.Pipeline=er,exports.PipelineStage=Ii,exports.Point=w,exports.PointerData=tr,exports.Polygon=Le,exports.PolygonArray=nt,exports.PolygonMerger=Ei,exports.PolygonSimplifier=Pi,exports.PrecisionCalculator=It,exports.PrecisionSchema=xt,exports.RIFFDecoder=Pt,exports.RIFFEncoder=yt,exports.RIFFFormat=gt,exports.RMSEBasedPrecisionCalculator=class extends It{constructor(e=.5){super(),this.qualityFactor=e}calculatePrecision(e,t){let r=new Float32Array(9),i=0,s=NaN,n=vt.l2Norm(e);if(0==n)return 2;for(let t=0;t<9;t++){var o=vt.calculateError(e,t)/n;if(isNaN(o))break;if(!isNaN(s)&&s<=o)break;if(i=t,r[t]=o,vt.isZero(o))break;s=o}return Math.round(this.qualityFactor*i)}},exports.Rect=v,exports.RenderingContext2D=ct,exports.Scalar=z,exports.Selector=hi,exports.SemanticTriple=Rr,exports.SensorChannel=H,exports.SensorChannelsContext=Z,exports.SensorContext=q,exports.SensorData=J,exports.SensorStream=Q,exports.ShapeFactory=ue,exports.Smoother=pi,exports.SpatialContext=si,exports.Spline=Dt,exports.SplineProducer=ui,exports.SplitPointsProducer=di,exports.Stroke=ur,exports.StrokeRenderer2D=class extends Pr{constructor(e,t){super(e,t),this.alphaLayer=void 0}drawStroke(e){let t=e.blendMode;if(!(e.brush instanceof $e))throw new Error("Incompatible brush found. It should be Brush2D instance.");if(!t)return void console.warn(`Cannot process ${e.renderMode} render mode. Requres custom processing.`);this.blendMode=e.style.blendMode||t;let r=this.layer.draw(e);this.strokeBounds=r,this.updatedArea=r}drawSegment(e,t=!1){if(!this.color)throw new Error("StrokeRenderer requires 'color' to be configured");if(this.validate(e)){let t=this.layer.drawStroke(this.brush,e,this.color.toRGB(),e.matrix);t&&(this.incompleteStrokeBounds=t.union(this.incompleteStrokeBounds),this.strokeBounds=t.union(this.strokeBounds),this.updatedArea=this.incompleteStrokeBounds.union(this.preliminaryDirtyArea))}else this.updatedArea=this.preliminaryDirtyArea;this.blendWithPreliminaryLayer=!1,this.preliminaryDirtyArea=null}drawPreliminary(e){this.validate(e)&&(this.preliminaryLayer||(this.preliminaryLayer=this.canvas.createLayer(),this.preliminaryLayer.setTransform(this.matrix)),this.updatedArea&&this.preliminaryLayer&&(this.preliminaryLayer.clear(this.updatedArea),this.preliminaryLayer.blend(this.layer,{mode:Ve.SOURCE_OVER,rect:this.updatedArea})),this.preliminaryDirtyArea=this.preliminaryLayer.drawStroke(this.brush,e,this.color.toRGB(),e.matrix),this.updatedArea=v.union(this.preliminaryDirtyArea,this.updatedArea),this.preliminaryLayer&&(this.blendWithPreliminaryLayer=!0))}reset(e){super.reset(e),this.runtime&&this.color.alpha<1&&(this.alphaLayer?this.alphaLayer.resize(this.layer.width,this.layer.height):this.alphaLayer=this.canvas.createLayer(this.layer.width,this.layer.height))}blendUpdatedArea(e){if(!this.updatedArea)return;let t=e||this.canvas,r=this.blendWithPreliminaryLayer?this.preliminaryLayer:this.layer,i=t.bounds.intersect(this.updatedArea);i&&(this.color.alpha<1?(this.alphaLayer.clear(),this.alphaLayer.ctx.globalAlpha=1,this.alphaLayer.blend(t,{rect:i}),this.alphaLayer.ctx.globalAlpha=this.color.alpha,this.alphaLayer.blend(r,{mode:this.blendMode,rect:i}),t.clear(i),t.blend(this.alphaLayer,{rect:i})):t.blend(r,{mode:this.blendMode,rect:i})),this.incompleteStrokeBounds=null,this.updatedArea=null}blendStroke(e,t,r){if(!this.strokeBounds)return;r||(r=this.blendMode);let i=this.layer,s=e||this.canvas;(t=s.bounds.intersect(t||this.strokeBounds))&&(this.runtime&&this.color.alpha<1?(this.alphaLayer.clear(),this.alphaLayer.ctx.globalAlpha=this.color.alpha,this.alphaLayer.blend(i,{rect:t}),s.blend(this.alphaLayer,{mode:r,rect:t})):s.blend(i,{mode:r,rect:t}))}blendStrokes(e,t,r={},i){if(0==e.length)return;let s,n,o,a=e.first.renderMode,l=[],h=()=>{let e=ur.RenderMode.getBlendMode(a);this.strokeBounds=n,n=null,this.blendStroke(t,r.rect,e),s=this.strokeBounds.union(s),this.reset()},d=()=>{if(!i)throw new Error("strokeRendererGL should be provided for WebGL strokes rasterization");i.reset(),o=i.blendStrokes(l,t,r),s=o.union(s),l.clear()};i&&(i.layer.resize(this.layer.width,this.layer.height),i.setTransform(this.matrix)),this.reset();for(let t of e)t.brush instanceof $e?(l.length>0&&(d(),a=t.renderMode),a!=t.renderMode&&(h(),a=t.renderMode),n=t.bounds.union(n),this.drawStroke(t)):(n&&h(),l.push(t));return l.length>0?d():h(),this.restart=!0,s}toStroke(e,t){if(!this.brush)throw new Error("StrokeRenderer brush is not configured");!0===t&&(t=void 0,console.warn("StrokeRenderer2D.toStroke 'simplify' param is deprecated. Do not affects InkPath. InkBuilderSettings 'concatSegments' should be configured to affect ink path properly."));let r=e.getSensorData(),i=e.getSpline(),s=e.getInkPath(),n=e.getAllData();i.id=t;let o=new ur(this.brush,i,s,r);return r&&(o.sensorDataMapping=r.inkStream.getPipelineMapping()),n&&(o.pipeline=n),this.blendMode!=Ve.SOURCE_OVER&&(o.renderMode=ur.RenderMode.get(this.blendMode)),o}delete(){console.warn("Not applicable with 2D API")}},exports.StrokeRendererGL=class extends Pr{constructor(e,t){super(e,t),this.layerOptions=t,this.bitmapLayer=void 0,this.randomSeed=void 0,this.initialRandomSeed=void 0}configure(e){super.configure(e),this.brush instanceof rt&&isFinite(e.randomSeed)&&(this.initialRandomSeed=e.randomSeed)}draw(e,t=!1){if(this.layer.isDeleted())throw new Error("StrokeRenderer cannot draw, it is already deleted");super.draw(e,t)}drawStroke(e){let t=e.blendMode;if(!t)return void console.warn(`Cannot process ${e.renderMode} render mode. Requres custom processing.`);this.blendMode=e.style.blendMode||t;let r=this.layer.draw(e);this.strokeBounds=r,this.updatedArea=r}drawSegment(e,t=!1){if(this.validate(e)){e.color&&this.color&&!e.color.equals(this.color)&&(e.color=this.color);let t=this.brush instanceof rt?this.strokeLastRendererdDrawContext:this.color,r=this.layer.drawStroke(this.brush,e,t);r&&(this.incompleteStrokeBounds=r.union(this.incompleteStrokeBounds),this.strokeBounds=r.union(this.strokeBounds),this.updatedArea=this.incompleteStrokeBounds.union(this.preliminaryDirtyArea))}else this.updatedArea=this.preliminaryDirtyArea;this.blendWithPreliminaryLayer=!1,this.preliminaryDirtyArea=null}drawPreliminary(e){if(!this.validate(e))return;let t=null;this.brush instanceof rt?(this.strokeLastRendererdDrawContext.copyTo(this.strokePrelimLastRenderedDrawContext),t=this.strokePrelimLastRenderedDrawContext):t=this.color,this.preliminaryLayer||(this.preliminaryLayer=this.canvas.createLayer(this.layerOptions),this.preliminaryLayer.setTransform(this.matrix)),this.updatedArea&&this.preliminaryLayer&&this.preliminaryLayer.blend(this.layer,{mode:Ve.COPY,rect:this.updatedArea}),e.color&&this.color&&!e.color.equals(this.color)&&(e.color=this.color),this.preliminaryDirtyArea=this.preliminaryLayer.drawStroke(this.brush,e,t),this.updatedArea=v.union(this.preliminaryDirtyArea,this.updatedArea),this.preliminaryLayer&&(this.blendWithPreliminaryLayer=!0)}reset(){super.reset(),this.bitmapLayer&&(this.bitmapLayer.clear(this.backgroundColor),this.bitmapLayer.resize(this.layer.width,this.layer.height)),this.brush instanceof rt?(this.strokeLastRendererdDrawContext=new wr(this.initialRandomSeed),this.strokePrelimLastRenderedDrawContext||(this.strokePrelimLastRenderedDrawContext=new wr),delete this.initialRandomSeed,this.randomSeed=this.strokeLastRendererdDrawContext.randomSeed):delete this.randomSeed}blendUpdatedArea(e){if(!this.updatedArea)return;let t=this.blendWithPreliminaryLayer?this.preliminaryLayer:this.layer,r=e||this.canvas,i=r.bounds.intersect(this.updatedArea);if(i){if(r instanceof br)throw new Error("Runtime blendig requires OffscreenLayerGL target");r.blend(t,{mode:this.blendMode,rect:i})}this.incompleteStrokeBounds=null,this.updatedArea=null}blendStroke(e,t,r){if(!this.strokeBounds)return;r||(r=this.blendMode);let i=this.layer,s=e||this.canvas;(t=s.bounds.intersect(t||this.strokeBounds))&&(s instanceof br?this.blendStroke2D(s,{mode:r,rect:t}):s.blend(i,{mode:r,rect:t}))}blendStroke2D(e,t={}){let r=t.rect||t.sourceRect||this.layer.bounds,i=this.layer.getImageData(r,!0);if(!this.bitmapLayer){let e=new ne(this.layer.width,this.layer.height);this.bitmapLayer=new br(e.getContext("2d"))}this.bitmapLayer.putImageData(i,r.x,r.y),e.blend(this.bitmapLayer,t)}blendStrokes(e,t,r={}){if(0==e.length)return;let i,s,n=e.first.renderMode,o=()=>{let e=ur.RenderMode.getBlendMode(n);this.strokeBounds=s,s=null,this.blendStroke(t,r.rect,e),i=this.strokeBounds.union(i),this.reset()};this.reset();for(let t of e)(n!=t.renderMode||t.brush instanceof $e&&t!=e.first)&&(o(),n=t.renderMode),s=t.bounds.union(s),this.drawStroke(t);return o(),this.restart=!0,i}toStroke(e,t){let r=e.getSensorData(),i=e.getSpline(),s=e.getInkPath(),n=e.getAllData();i.id=t;let o=new ur(this.brush,i,s,r);return r&&(o.sensorDataMapping=r.inkStream.getPipelineMapping()),n&&(o.pipeline=n),o.randomSeed=this.randomSeed,this.blendMode!=Ve.SOURCE_OVER&&(o.renderMode=ur.RenderMode.get(this.blendMode)),o}delete(){this.layer.delete(),this.preliminaryLayer&&this.preliminaryLayer.delete()}},exports.TextTable=L,exports.TripleStore=Tr,exports.TypedArrayCodec=de,exports.URIResolver=he,exports.VarianceBasedPrecisionCalculator=class extends It{constructor(e=.5){super(),this.qualityFactor=e}calculatePrecision(e,t){let r=new Float32Array(e.length);r[0]=0;for(let t=1;t<e.length;t++)r[t]=(e[t]-e[t-1])%1;let i=vt.variance(r),s=i%1==0?0:-Math.floor(Math.log10(i));return s=Math.min(s,9),Math.round(this.qualityFactor*s)}},exports.fsx=Ge,exports.math=Ne,exports.utils=M,exports.uuid=E,exports.version="1.5.0";