!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(t=t||self).Martini=i()}(this,(function(){"use strict";class t{constructor(t,i){const e=i.gridSize;if(t.length!==e*e)throw new Error(`Expected terrain data of length ${e*e} (${e} x ${e}), got ${t.length}.`);this.terrain=t,this.martini=i,this.errors=new Float32Array(t.length),this.update()}update(){const{numTriangles:t,numParentTriangles:i,coords:e,gridSize:r}=this.martini,{terrain:n,errors:s}=this;for(let o=t-1;o>=0;o--){const t=4*o,a=e[t+0],c=e[t+1],h=e[t+2],d=e[t+3],l=a+h>>1,u=c+d>>1,f=l+u-c,g=u+a-l,m=(n[c*r+a]+n[d*r+h])/2,w=u*r+l,p=Math.abs(m-n[w]);if(s[w]=Math.max(s[w],p),o>1)*r+(a+f>>1),i=(d+g>>1)*r+(h+f>>1);s[w]=Math.max(s[w],s[t],s[i])}}}getMesh(t=0){const{gridSize:i,indices:e}=this.martini,{errors:r}=this;let n=0,s=0;const o=i-1;function a(o,c,h,d,l,u){const f=o+h>>1,g=c+d>>1;Math.abs(o-l)+Math.abs(c-u)>1&&r[g*i+f]>t?(a(l,u,o,c,f,g),a(h,d,l,u,f,g)):(e[c*i+o]=e[c*i+o]||++n,e[d*i+h]=e[d*i+h]||++n,e[u*i+l]=e[u*i+l]||++n,s++)}e.fill(0),a(0,0,o,o,o,0),a(o,o,0,0,0,o);const c=new Uint16Array(2*n),h=new Uint32Array(3*s);let d=0;function l(n,s,o,a,u,f){const g=n+o>>1,m=s+a>>1;if(Math.abs(n-u)+Math.abs(s-f)>1&&r[m*i+g]>t)l(u,f,n,s,g,m),l(o,a,u,f,g,m);else{const t=e[s*i+n]-1,r=e[a*i+o]-1,l=e[f*i+u]-1;c[2*t]=n,c[2*t+1]=s,c[2*r]=o,c[2*r+1]=a,c[2*l]=u,c[2*l+1]=f,h[d++]=t,h[d++]=r,h[d++]=l}}return l(0,0,o,o,o,0),l(o,o,0,0,0,o),{vertices:c,triangles:h}}}return class{constructor(t=257){this.gridSize=t;const i=t-1;if(i&i-1)throw new Error(`Expected grid size to be 2^n+1, got ${t}.`);this.numTriangles=i*i*2-2,this.numParentTriangles=this.numTriangles-i*i,this.indices=new Uint32Array(this.gridSize*this.gridSize),this.coords=new Uint16Array(4*this.numTriangles);for(let t=0;t>=1)>1;){const t=r+s>>1,i=n+o>>1;1&e?(s=r,o=n,r=a,n=c):(r=s,n=o,s=a,o=c),a=t,c=i}const h=4*t;this.coords[h+0]=r,this.coords[h+1]=n,this.coords[h+2]=s,this.coords[h+3]=o}}createTile(i){return new t(i,this)}}}));