/* COPYRIGHT Esri - https://js.arcgis.com/5.1.2/LICENSE.txt */
import e from"../../../../core/Error.js";import r from"../../../../core/Logger.js";import{e as t}from"../../../../chunks/earcut.js";import{set as o}from"../../../../core/libs/gl-matrix-2/math/vec2.js";import{create as n}from"../../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{convertFromPolyline as s,convertFromPolygon as i}from"../../../../layers/graphics/featureConversionUtils.js";import{i1616to32 as c}from"./number.js";import{BufferObject as a}from"../../../webgl/BufferObject.js";import{PrimitiveType as f}from"../../../webgl/enums.js";import{VertexBuffer as m}from"../../../webgl/VertexBuffer.js";const h=(e,r,t,o)=>{let n=0;for(let s=1;s<t;s++){const t=e[2*(r+s-1)],o=e[2*(r+s-1)+1];n+=(e[2*(r+s)]-t)*(e[2*(r+s)+1]+o)}return o?n>0:n<0},l=({coords:e,lengths:r},o)=>{const n=[];for(let s=0,i=0;s<r.length;i+=r[s],s+=1){const c=i,a=[];for(;s<r.length-1&&h(e,i+r[s],r[s+1],o);s+=1,i+=r[s])a.push(i+r[s]-c);const f=e.slice(2*c,2*(i+r[s])),m=t(f,a,2);for(const e of m)n.push(e+c)}return n};class u{constructor(e,r,t,o=!1){this.vertices=e,this.indices=r,this.primitiveType=t,this.isMapSpace=o,this._cache={}}static fromPath(e){const r=s({paths:e.path},!1,!1),t=r.coords,o=new Uint32Array(l(r,!0)),n=new Uint32Array(t.length/2);for(let s=0;s<n.length;s++)n[s]=c(Math.floor(t[2*s]),Math.floor(t[2*s+1]));return new u(n,o,f.TRIANGLES)}static fromGeometry(t,o){const n=o.geometry?.type;switch(n){case"polygon":return u.fromPolygon(t,o.geometry);case"extent":return u.fromMapExtent(t,o.geometry);default:return r.getLogger("esri.views.2d.engine.webgl.Mesh2D").error(new e("mapview-bad-type",`Unable to create a mesh from type ${n}`,o)),u.fromScreenExtent({xmin:0,ymin:0,xmax:1,ymax:1})}}static fromPolygon(e,r){const t=i(r,!1,!1),s=t.coords,a=new Uint32Array(l(t,!1)),m=new Uint32Array(s.length/2),h=n(),x=n();for(let n=0;n<m.length;n++)o(h,s[2*n],s[2*n+1]),e.toScreen(x,h),m[n]=c(Math.floor(x[0]),Math.floor(x[1]));return new u(m,a,f.TRIANGLES,!0)}static fromScreenExtent({xmin:e,xmax:r,ymin:t,ymax:o}){const n=new Uint32Array([c(e,t),c(r,t),c(e,o),c(e,o),c(r,t),c(r,o)]),s=new Uint32Array([0,1,2,3,4,5]);return new u(n,s,f.TRIANGLES)}static fromMapExtent(e,r){const[t,o]=e.toScreen([0,0],[r.xmin,r.ymin]),[n,s]=e.toScreen([0,0],[r.xmax,r.ymax]),i=new Uint32Array([c(t,o),c(n,o),c(t,s),c(t,s),c(n,o),c(n,s)]),a=new Uint32Array([0,1,2,3,4,5]);return new u(i,a,f.TRIANGLES)}destroy(){null!=this._cache.indexBuffer&&this._cache.indexBuffer.dispose(),this._cache.vertexBuffer?.dispose(),this._cache.indexBuffer=this._cache.vertexBuffer=null}getIndexBuffer(e,r=35044){return this._cache.indexBuffer??=a.createIndex(e,r,this.indices),this._cache.indexBuffer}getVertexBuffers(e,r){return this._cache.vertexBuffer??=new m(e,r,this.vertices),this._cache.vertexBuffer}}export{u as default};
