webgl-dsl
Version:
Thin functional WebGL wrapper with strong typed GLSL DSL
19 lines (18 loc) • 27.8 kB
JavaScript
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=(()=>{let n=0;return function(){return n++}})();exports.Type=(n=>(n.Scalar="float",n.Vector2="vec2",n.Matrix2="mat2",n.Vector3="vec3",n.Matrix3="mat3",n.Vector4="vec4",n.Matrix4="mat4",n.Boolean="bool",n.Sampler="sampler2D",n))(exports.Type||{});var ne=(n=>(n.High="highp",n.Medium="mediump",n.Low="lowp",n))(ne||{});(n=>{function e(i){switch(i){case"bool":case"float":case"sampler2D":return 1;case"vec2":case"mat2":return 2;case"vec3":case"mat3":return 3;case"vec4":case"mat4":return 4}}n.size=e;function r(i){switch(i){case 2:return"vec2";case 3:return"vec3";case 4:return"vec4"}}n.vector=r;function a(i){switch(i){case 1:return"float";case 2:return"vec2";case 3:return"vec3";case 4:return"vec4"}}n.numeric=a;function t(i){return i==="vec2"||i==="vec3"||i==="vec4"}n.isVector=t;function s(i){return i==="mat2"||i==="mat3"||i==="mat4"}n.isMatrix=s})(exports.Type||(exports.Type={}));class w{constructor(e=new Map){this.cache=e,this.global="",this.local=""}once(e,r){if(this.cache.has(e))return this.cache.get(e);{const a=r();return this.cache.set(e,a),a}}getGlobal(){return this.global}addGlobal(e){return this.global+=e,this}getLocal(){return this.local}addLocal(e){return this.local+=e,this}child(){return new w(this.cache)}}const Te="==+-*/<><=>=!&&||",c=class c{constructor(e){this.getValue=e}static call(e,r,a){const t=Te.indexOf(e)!==-1,s=r.map(i=>typeof i=="number"?E(i):i);return r.length===2&&t?new c(i=>{const l=s.map(h=>h.getValue(i));return{type:a(l.map(h=>h.type)),content:`((${l[0].content}) ${e} (${l[1].content}))`}}):new c(i=>{const l=s.map(h=>h.getValue(i));return{type:a(l.map(h=>h.type)),content:`${e}(${l.map(h=>h.content).join(", ")})`}})}unary(e){return c.call(e,[this],r=>r[0])}sin(){return this.unary("sin")}cos(){return this.unary("cos")}radians(){return this.unary("radians")}degrees(){return this.unary("degrees")}tan(){return this.unary("tan")}asin(){return this.unary("asin")}acos(){return this.unary("acos")}exp(){return this.unary("exp")}log(){return this.unary("log")}exp2(){return this.unary("exp2")}log2(){return this.unary("log2")}sqrt(){return this.unary("sqrt")}inversesqrt(){return this.unary("inversesqrt")}abs(){return this.unary("abs")}sign(){return this.unary("sign")}floor(){return this.unary("floor")}ceil(){return this.unary("ceil")}fract(){return this.unary("fract")}normalize(){return this.unary("normalize")}round(){return this.add(.5).floor()}not(){return this.unary("!")}atan(e){return e===void 0?c.call("atan",[this],([r])=>r):c.call("atan",[this,e],r=>r[0])}pow(e){const r=typeof e=="number"?E(e):e;return c.call("pow",[this,r],([a])=>a)}mod(e){const r=typeof e=="number"?E(e):e;return c.call("mod",[this,r],([a])=>a)}min(e){const r=typeof e=="number"?E(e):e;return c.call("min",[this,r],([a])=>a)}max(e){return c.call("max",[this,e],([r])=>r)}mix(e,r){return c.call("mix",[this,e,r],([a])=>a)}clamp(e,r){return c.call("clamp",[this,e,r],([a])=>a)}smoothstep(e,r){return c.call("smoothstep",[e,r,this],([a])=>a)}length(){return c.call("length",[this],()=>"float")}distance(e){return c.call("distance",[this,e],()=>"float")}dot(e){return c.call("dot",[this,e],()=>"float")}reflect(e){return c.call("reflect",[this,e],([r])=>r)}refract(e,r){return c.call("refract",[this,e,r],([a])=>a)}texture2D(e){return c.call("texture2D",[this,e],()=>"vec4")}add(e){return c.call("+",[this,e],([r,a])=>r==="float"?a:r)}sub(e){return c.call("-",[this,e],([r,a])=>r==="float"?a:r)}div(e){return c.call("/",[this,e],([r,a])=>r==="float"?a:r)}mul(e){return c.call("*",[this,e],([r,a])=>r==="float"||r===a?a:a==="float"||exports.Type.isVector(r)?r:exports.Type.isVector(a)?a:r)}bool(e,r){return c.call(e,[this,r],()=>"bool")}lt(e){return this.bool("<",e)}gt(e){return this.bool(">",e)}lte(e){return this.bool("<=",e)}gte(e){return this.bool(">=",e)}eq(e){return this.bool("==",e)}neq(e){return this.bool("!=",e)}and(e){return c.call("&&",[this,e],()=>"bool")}or(e){return c.call("||",[this,e],()=>"bool")}mem(e){const r=`mem${U()}`;return new c(a=>{const t=this.getValue(a);return a.once(r,()=>{const s=t.type!=="bool";a.addLocal(`${s?`${e} `:""}${t.type} ${r} = ${t.content};
`)}),{type:t.type,content:r}})}memHQ(){return this.mem("highp")}memMQ(){return this.mem("mediump")}memLQ(){return this.mem("lowp")}cond(e,r,a){const t=`cond${U()}`;let s=null;return new c(i=>(i.once(t,()=>{const l=this.getValue(i),h=i.child(),o=r.getValue(h),d=i.child(),f=a.getValue(d);s=o.type,i.addGlobal(h.getGlobal()).addGlobal(d.getGlobal()),i.addLocal(`${o.type!=="bool"?e+" ":""}${o.type} ${t};
`).addLocal(`if (${l.content}) {
`).addLocal(h.getLocal()).addLocal(`${t} = ${o.content};
`).addLocal(`} else {
`).addLocal(d.getLocal()).addLocal(`${t} = ${f.content};
`).addLocal(`}
`)}),{type:s,content:t}))}condHQ(e,r){return this.cond("highp",e,r)}condMQ(e,r){return this.cond("mediump",e,r)}condLQ(e,r){return this.cond("lowp",e,r)}take(e,r,a,t){return new c(s=>{const i=[e,r,a,t].filter(h=>h!==void 0),l=this.getValue(s);return{type:i.length===1?"float":exports.Type.vector(i.length),content:`(${l.content}).${i.map(h=>"xyzw".charAt(h)).join("")}`}})}vec2(){return new c(e=>({type:"vec2",content:`vec2(${this.getValue(e).content})`}))}vec3(){return new c(e=>({type:"vec3",content:`vec3(${this.getValue(e).content})`}))}vec4(){return new c(e=>({type:"vec4",content:`vec4(${this.getValue(e).content})`}))}x(){return this.take(0)}y(){return this.take(1)}z(){return this.take(2)}w(){return this.take(3)}r(){return this.take(0)}g(){return this.take(1)}b(){return this.take(2)}a(){return this.take(3)}cat(e){return typeof e=="number"?this.cat(c.val(e)):new c(r=>{const a=this.getValue(r),t=e.getValue(r),s=exports.Type.numeric(exports.Type.size(a.type)+exports.Type.size(t.type));return{type:s,content:`${s}(${a.content}, ${t.content})`}})}static val(...e){if(e.length===1){if(typeof e[0]=="boolean")return new c(()=>({type:"bool",content:e[0]?"1":"0"}));if(e[0]instanceof c)return e[0];{const r=e[0].toString();return new c(()=>({type:"float",content:/[e\.]/.test(r)?r:`${r}.0`}))}}else if(e.some(r=>typeof r=="number")){const r=e.map(a=>c.val(a));return c.val.apply(null,r)}else return e.reduce((r,a)=>r.cat(a))}};c.PI=c.val(Math.PI);let m=c;exports.TypeMap=void 0;(n=>{function e(l){return Array.isArray(l)?l[0]:l}n.getType=e;function r(l){return Array.isArray(l)?l[1]:"highp"}n.getPrecision=r;function a(l){return Object.keys(l).reduce((h,o)=>(h[o]=e(l[o]),h),{})}n.withoutPrecision=a;function t(l,h){const o={};return Object.keys(h).forEach(d=>{const f=h[d];o[d]=new m(g=>(g.once(`types_map_value_${d}`,()=>{g.addGlobal(`${l} ${n.getPrecision(f)} ${n.getType(f)} ${d};
`)}),{type:n.getType(f),content:d}))}),o}n.values=t;function s(l){let h=0;for(const o in l)h+=exports.Type.size(e(l[o]));return h}n.stride=s;function i(l){const h=s(l);return Object.keys(l).sort().reduce((o,d)=>{const f=o.length?o[o.length-1]:null;return o.push({name:d,stride:h,size:exports.Type.size(e(l[d])),offset:f?f.offset+f.size:0}),o},[])}n.layout=i})(exports.TypeMap||(exports.TypeMap={}));function se({uniforms:n,attributes:e,varyings:r,instances:a,fragment:t,vertex:s}){const i=exports.TypeMap.values("uniform",n),l=exports.TypeMap.values("attribute",{...e,...a||{}}),h=r?exports.TypeMap.values("varying",r):{},o=new w;Object.keys(h).forEach(y=>{h[y].getValue(o)});const d=s({...i,...l}),f=Object.keys(d).map(y=>`${y} = ${d[y].getValue(o).content};
`).join(""),g=o.getGlobal()+`void main() {
`+o.getLocal()+f+`}
`,R=new w;Object.keys(h).forEach(y=>{h[y].getValue(o)});const we=t({...i,...h,gl_FragCoord:new m(()=>({type:"vec4",content:"gl_FragCoord"})),gl_PointCoord:new m(()=>({type:"vec2",content:"gl_FragCoord"})),gl_FrontFacing:new m(()=>({type:"bool",content:"gl_FrontFacing"}))}).gl_FragColor.getValue(R),Le=R.getGlobal()+`void main() {
`+R.getLocal()+`gl_FragColor = ${we.content};
}
`;return{vertex:g,fragment:Le,uniforms:exports.TypeMap.withoutPrecision(n),attributes:exports.TypeMap.withoutPrecision(e),instances:exports.TypeMap.withoutPrecision(a||{})}}const E=m.val;class ae{constructor(e,r,a){this.gl=e,this.primitivesType=r,this.source=a,this.textureInstances=new Map,this.textureIndexes=new Map,this.program=e.program(a.vertex,a.fragment),this.attributes=e.arrayBuffer(),this.instances=e.arrayBuffer(),this.elements=e.elementsBuffer(),this.attributesStride=exports.TypeMap.stride(a.attributes),this.attributesLayout=exports.TypeMap.layout(a.attributes),this.instancesStride=exports.TypeMap.stride(a.instances),this.instancesLayout=exports.TypeMap.layout(a.instances),this.attributesLayout.forEach(t=>{this.program.setAttribute(t.name,this.attributes,t.stride,t.offset)}),this.instancesLayout.forEach(t=>{this.program.setAttribute(t.name,this.instances,t.stride,t.offset)});for(const t in a.uniforms)exports.TypeMap.getType(a.uniforms[t])===exports.Type.Sampler&&this.textureIndexes.set(t,this.textureIndexes.size)}prepareData(e,r,a){const t=new Float32Array(e*a.length);return a.forEach((s,i)=>{r.forEach(l=>{const h=s[l.name],o=e*i+l.offset;if(Array.isArray(h))for(let d=0;d<h.length;d++)t[o+d]=h[d];else if(l.size===1&&typeof h=="number")t[o]=h;else if(l.size===2){const{x:d,y:f}=h;t[o]=d,t[o+1]=f}else if(l.size===3){const{x:d,y:f,z:g}=h;t[o]=d,t[o+1]=f,t[o+2]=g}else throw new Error(`Unsupported attribute '${l.name}' value: ${JSON.stringify(h)}`)})}),t}setAttributes(e){const r=this.prepareData(this.attributesStride,this.attributesLayout,e);return this.attributes.setContent(r),this}setInstances(e){const r=this.prepareData(this.instancesStride,this.instancesLayout,e);return this.instances.setContent(r),this}setElements(e){return this.elements.setContent(e),this}setUniforms(e){const r=this.source.uniforms;for(const a in e){const t=e[a];let s;if(typeof t=="number")s=[t];else if(Array.isArray(t))s=t;else if(t instanceof D){const i=this.textureIndexes.get(a);this.textureInstances.set(i,t),s=[i]}else if(r[a]===exports.Type.Vector2){const{x:i,y:l}=t;s=[i,l]}else if(r[a]===exports.Type.Vector3){const{x:i,y:l,z:h}=t;s=[i,l,h]}else throw new Error(`Invalid value for uniform '${a}', expected ${r[a]}`);this.program.setUniform(a,s)}return this}draw(e=this.instancesStride?this.instances.length/this.instancesStride:null,r=this.attributesStride?this.attributes.length/this.attributesStride:null,a=this.elements.length){const t=this.gl;t.settings().program(this.program).enabledAttributes(Object.keys(this.program.attributes).map(s=>this.program.attributes[s]?.location).filter(s=>s!=null)).instancedAttributes(this.instancesLayout.map(s=>s.name).map(s=>this.program.attributes[s]?.location).filter(s=>s!=null)).textures(Array.from(this.textureInstances.entries()).reduce((s,[i,l])=>(s[i]=l,s),new Array(16).fill(null))).apply(()=>{if(e!==null&&a!==0)t.settings().elementsBuffer(this.elements).apply(()=>{t.drawsInstancedElements(this.primitivesType,a,e)});else if(e!==null&&r!==null)t.drawInstancedArrays(this.primitivesType,r,e);else if(a!==0)t.settings().elementsBuffer(this.elements).apply(()=>{t.drawsElements(this.primitivesType,a)});else if(r)t.drawArrays(this.primitivesType,r);else throw new Error("Invalid draw dataset")})}dispose(){this.program.dispose(),this.attributes.dispose(),this.instances.dispose(),this.elements.dispose()}}function ie(n,e,r){return new ae(n,e,"vertex"in r&&typeof r.vertex=="string"?r:se(r))}class ve{constructor(e){this.values=e}dispose(){this.values.forEach(e=>e.dispose())}}function xe(...n){return new ve(n)}function le(...n){n.forEach(e=>e.dispose())}function he(...n){const e=[];try{for(let r=0;r<n.length;r++)e.push(n[r](...e));return e}catch(r){throw e.reverse().forEach(a=>a.dispose()),r}}exports.Disposable=void 0;(n=>{n.join=xe,n.dispose=le,n.create=he})(exports.Disposable||(exports.Disposable={}));function oe(n,e){try{return e(n)}finally{n.dispose()}}function ce(...n){const e=n.length-1,r=[];try{for(let a=0;a<e;a++)r.push(n[a](...r));return n[e](...r)}finally{r.reverse().forEach(a=>a.dispose())}}const G=256,_=16384,Re=0,Se=1,Oe=2,Ie=3,Me=4,Ne=5,Ve=6,Ce=0,Be=1,Pe=768,De=769,$e=770,Ue=771,Ge=772,_e=773,qe=774,ke=775,Fe=776,He=32774,ze=32778,We=32779,M=34962,N=34963,je=35040,Xe=35044,Qe=35048,Ye=1028,Ze=1029,Ke=1032,q=2884,k=3042,F=2929,H=3089,Je=0,et=1280,tt=1281,rt=1282,nt=1285,st=33901,L=5121,z=5123,S=5126,ue=6406,de=6407,fe=6408,at=6409,it=6410,lt=35632,ht=35633,ot=35714,ct=35718,ut=35721,dt=512,ft=513,pt=514,mt=515,gt=516,yt=517,At=518,bt=519,Et=9728,wt=9729,W=10240,j=10241,Lt=10242,Tt=10243,p=3553,vt=33984,X=33071,Q=35664,Y=35665,Z=35666,xt=35670,K=35674,J=35675,ee=35676,Rt=35678,St=35713,O=36160,T=36161,te=33189,Ot=36064,It=36096,Mt=37440,Nt=35904,Vt=35907;var V=(n=>(n[n.Front=Ye]="Front",n[n.Back=Ze]="Back",n[n.FrontAndBack=Ke]="FrontAndBack",n))(V||{}),v=(n=>(n[n.Add=He]="Add",n[n.Sub=ze]="Sub",n[n.RSub=We]="RSub",n[n.Min=32775]="Min",n[n.Max=32776]="Max",n))(v||{}),C=(n=>(n[n.Never=dt]="Never",n[n.Less=ft]="Less",n[n.Equal=pt]="Equal",n[n.LEqual=mt]="LEqual",n[n.Greater=gt]="Greater",n[n.NotEqual=yt]="NotEqual",n[n.GEqual=At]="GEqual",n[n.Always=bt]="Always",n))(C||{}),A=(n=>(n[n.Zero=Ce]="Zero",n[n.One=Be]="One",n[n.SrcColor=Pe]="SrcColor",n[n.OneMinusSrcColor=De]="OneMinusSrcColor",n[n.DstColor=qe]="DstColor",n[n.OneMinusDstColor=ke]="OneMinusDstColor",n[n.SrcAlpha=$e]="SrcAlpha",n[n.OneMinusSrcAlpha=Ue]="OneMinusSrcAlpha",n[n.DstAlpha=Ge]="DstAlpha",n[n.OneMinusDstAlpha=_e]="OneMinusDstAlpha",n[n.SrcAlphaSaturate=Fe]="SrcAlphaSaturate",n))(A||{}),B=(n=>(n[n.Nearest=Et]="Nearest",n[n.Linear=wt]="Linear",n))(B||{}),P=(n=>(n[n.Alpha=ue]="Alpha",n[n.Luminance=at]="Luminance",n[n.LuminanceAlpha=it]="LuminanceAlpha",n[n.Rgb=de]="Rgb",n[n.Rgba=fe]="Rgba",n[n.Srgb=Nt]="Srgb",n[n.Srgba=Vt]="Srgba",n))(P||{});exports.PixelFormat=(n=>(n[n.Rgba=fe]="Rgba",n[n.Rgb=de]="Rgb",n[n.Alpha=ue]="Alpha",n))(exports.PixelFormat||{});(n=>{function e(r){switch(r){case n.Rgb:return 3;case n.Rgba:return 4;case n.Alpha:return 1}}n.getChannelsCount=e})(exports.PixelFormat||(exports.PixelFormat={}));var x=(n=>(n[n.Vertex=ht]="Vertex",n[n.Fragment=lt]="Fragment",n))(x||{}),pe=(n=>(n[n.NoError=Je]="NoError",n[n.InvalidEnum=et]="InvalidEnum",n[n.InvalidValue=tt]="InvalidValue",n[n.InvalidOperation=rt]="InvalidOperation",n[n.OutOfMemory=nt]="OutOfMemory",n))(pe||{}),b=(n=>(n[n.Stream=je]="Stream",n[n.Static=Xe]="Static",n[n.Dynamic=Qe]="Dynamic",n))(b||{}),me=(n=>(n[n.Array=M]="Array",n[n.Elements=N]="Elements",n))(me||{}),ge=(n=>(n[n.Points=Re]="Points",n[n.Lines=Se]="Lines",n[n.LineStrip=Ie]="LineStrip",n[n.LineLoop=Oe]="LineLoop",n[n.Triangles=Me]="Triangles",n[n.TriangleStrip=Ne]="TriangleStrip",n[n.TriangleFan=Ve]="TriangleFan",n))(ge||{});class Ct{constructor(...e){this.settingsCache=I.initial();const[r,a]=e;typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement?this.handle=r.getContext("webgl",a):this.handle=r,this.instancedArraysExtension=this.handle.getExtension("ANGLE_instanced_arrays"),this.minMaxExtension=this.handle.getExtension("EXT_blend_minmax"),this.srgbExtension=this.handle.getExtension("EXT_sRGB")}get width(){return this.handle.drawingBufferWidth}get height(){return this.handle.drawingBufferHeight}isContextLost(){return this.handle.isContextLost()}getPointSizeRange(){return this.handle.getParameter(st)}clearColorBuffer(){return this.handle.clear(_),this}clearDepthBuffer(){return this.handle.clear(G),this}clearBuffers(){return this.handle.clear(_|G),this}read(e=exports.PixelFormat.Rgba){const{width:r,height:a}=this,t=new Uint8Array(r*a*exports.PixelFormat.getChannelsCount(e));return this.settings().viewport(0,0,r,a).apply(()=>{this.handle.readPixels(0,0,r,a,e,L,t)}),t}drawArrays(e,r){return this.handle.drawArrays(e,0,r),this}drawsElements(e,r){return this.handle.drawElements(e,r,z,0),this}drawInstancedArrays(e,r,a){return this.instancedArraysExtension.drawArraysInstancedANGLE(e,0,r,a),this}drawsInstancedElements(e,r,a){return this.instancedArraysExtension.drawElementsInstancedANGLE(e,r,z,0,a),this}settings(){return new u(this,this.settingsCache)}texture(e){return new D(this,e)}renderBuffer(e,r){return new ye(this,e,r)}frameBuffer(e,r){return new $(this,e,r)}arrayBuffer(e=null,r=b.Dynamic){return new Ae(this,e,r)}elementsBuffer(e=null,r=b.Dynamic){return new be(this,e,r)}program(e,r){return ce(()=>new re(this,x.Vertex,e),()=>new re(this,x.Fragment,r),(a,t)=>new Ee(this,a,t))}command(e,r){return ie(this,e,r)}hasSrgbExtension(){return!!this.srgbExtension}getErrorCode(){return this.handle.getError()}dispose(){const e=this.handle.getExtension("WEBGL_lose_context");e&&e.loseContext()}}var I;(n=>{n.initial=()=>({blend:!1,viewport:[0,0,0,0],scissorTest:!1,scissorBox:[0,0,0,0],depthTest:!1,depthFunction:C.Less,clearDepth:1,lineWidth:1,blendEquation:[v.Add,v.Add],blendFunction:[A.One,A.Zero,A.One,A.Zero],clearColor:[0,0,0,0],activeTexture:0,textures:new Map,arrayBuffer:null,elementsBuffer:null,program:null,enabledAttributes:new Set,instancedAttributes:new Set,renderBuffer:null,frameBuffer:null,cullFace:!1,cullFaceMode:V.Back})})(I||(I={}));class u{constructor(e,r,a=t=>t()){this.gl=e,this.cache=r,this.apply=a,this.blend=u.cached({read:t=>t.blend,write:(t,s)=>{t.blend=s},equals:(t,s)=>t===s,apply:(t,s)=>{s?t.handle.enable(k):t.handle.disable(k)}}),this.cullFace=u.cached({read:t=>t.cullFace,write:(t,s)=>{t.cullFace=s},equals:(t,s)=>t===s,apply:(t,s)=>{s?t.handle.enable(q):t.handle.disable(q)}}),this.cullFaceMode=u.cached({read:t=>t.cullFaceMode,write:(t,s)=>{t.cullFaceMode=s},equals:(t,s)=>t===s,apply:(t,s)=>{t.handle.cullFace(s)}}),this.viewport=(()=>{const t=u.cached({read:s=>s.viewport,write:(s,i)=>{s.viewport=i},equals:(s,i)=>s.every((l,h)=>l===i[h]),apply:(s,[i,l,h,o])=>{s.handle.viewport(i,l,h,o)}});return function(s,i,l,h){return t.call(this,[s,i,l,h])}})(),this.scissorTest=u.cached({read:t=>t.scissorTest,write:(t,s)=>{t.scissorTest=s},equals:(t,s)=>t===s,apply:(t,s)=>{s?t.handle.enable(H):t.handle.disable(H)}}),this.scissorBox=(()=>{const t=u.cached({read:s=>s.scissorBox,write:(s,i)=>{s.scissorBox=i},equals:(s,i)=>s.every((l,h)=>l===i[h]),apply:(s,[i,l,h,o])=>{s.handle.scissor(i,l,h,o)}});return function(s,i,l,h){return t.call(this,[s,i,l,h])}})(),this.depthTest=u.cached({read:t=>t.depthTest,write:(t,s)=>{t.depthTest=s},equals:(t,s)=>t===s,apply:(t,s)=>{s?t.handle.enable(F):t.handle.disable(F)}}),this.clearDepth=u.cached({read:t=>t.clearDepth,write:(t,s)=>{t.clearDepth=s},equals:(t,s)=>t===s,apply:(t,s)=>{t.handle.clearDepth(s)}}),this.lineWidth=u.cached({read:t=>t.lineWidth,write:(t,s)=>{t.lineWidth=s},equals:(t,s)=>t===s,apply:(t,s)=>{t.handle.lineWidth(s)}}),this.blendEquation=(()=>{const t=u.cached({read:s=>s.blendEquation,write:(s,i)=>{s.blendEquation=i},equals:(s,i)=>s.every((l,h)=>l===i[h]),apply:(s,[i,l])=>{s.handle.blendEquationSeparate(i,l)}});return function(s,i=s){return t.call(this,[s,i])}})(),this.blendFunction=(()=>{const t=u.cached({read:s=>s.blendFunction,write:(s,i)=>{s.blendFunction=i},equals:(s,i)=>s.every((l,h)=>l===i[h]),apply:(s,[i,l,h,o])=>{s.handle.blendFuncSeparate(i,l,h,o)}});return function(s,i,l=s,h=i){return t.call(this,[s,i,l,h])}})(),this.depthFunction=u.cached({read:t=>t.depthFunction,write:(t,s)=>{t.depthFunction=s},equals:(t,s)=>t===s,apply:(t,s)=>{t.handle.depthFunc(s)}}),this.clearColor=(()=>{const t=u.cached({read:s=>s.clearColor,write:(s,i)=>{s.clearColor=i},equals:(s,i)=>s.every((l,h)=>l===i[h]),apply:(s,[i,l,h,o])=>{s.handle.clearColor(i,l,h,o)}});return function(s,i,l,h){return t.call(this,[s,i,l,h])}})(),this.activeTexture=u.cached({read:t=>t.activeTexture,write:(t,s)=>{t.activeTexture=s},equals:(t,s)=>t===s,apply:(t,s)=>{t.handle.activeTexture(vt+s)}}),this.texture=(()=>{const t=new Array(16).fill(null).map((s,i)=>u.cached({read:l=>l.textures.get(i)||null,write:(l,h)=>{h?l.textures.set(i,h):l.textures.delete(i)},equals:(l,h)=>l===h,apply:(l,h)=>{l.settings().activeTexture(i).apply(()=>{l.handle.bindTexture(p,h?.handle||null)})}}));return function(s,i){return t[s].call(this,i)}})(),this.arrayBuffer=u.cached({read:t=>t.arrayBuffer,write:(t,s)=>{t.arrayBuffer=s},equals:(t,s)=>t===s,apply:(t,s)=>{t.handle.bindBuffer(M,s?.handle??null)}}),this.elementsBuffer=u.cached({read:t=>t.elementsBuffer,write:(t,s)=>{t.elementsBuffer=s},equals:(t,s)=>t===s,apply:(t,s)=>{t.handle.bindBuffer(N,s?.handle??null)}}),this.program=u.cached({read:t=>t.program,write:(t,s)=>{t.program=s},equals:(t,s)=>t===s,apply:(t,s)=>{t.handle.useProgram(s?s.handle:null)}}),this.renderBuffer=u.cached({read:t=>t.renderBuffer,write:(t,s)=>{t.renderBuffer=s},equals:(t,s)=>t===s,apply:(t,s)=>{t.handle.bindRenderbuffer(T,s?s.handle:null)}}),this.frameBuffer=u.cached({read:t=>t.frameBuffer,write:(t,s)=>{t.frameBuffer=s},equals:(t,s)=>t===s,apply:(t,s)=>{t.handle.bindFramebuffer(O,s?s.handle:null)}})}static cached({read:e,write:r,equals:a,apply:t}){return function(s){return this.then(new u(this.gl,this.cache,i=>{const l=e(this.cache);if(a(l,s))return i();try{return r(this.cache,s),t(this.gl,s),i()}finally{r(this.cache,l),t(this.gl,l)}}))}}then(e){return new u(this.gl,this.cache,r=>this.apply(()=>e.apply(r)))}textures(e){let r=this;for(let a=0;a<16;a++)r=r.texture(a,a>=e.length?null:e[a]);return r}enabledAttributes(e){return this.then(new u(this.gl,this.cache,r=>{const a=this.gl.handle,t=this.cache.enabledAttributes,s=new Set(e);this.cache.enabledAttributes=s;const i=(l,h)=>{l.forEach(o=>{h.has(o)||a.disableVertexAttribArray(o)}),h.forEach(o=>{l.has(o)||a.enableVertexAttribArray(o)})};try{return i(t,s),r()}finally{i(s,t),this.cache.enabledAttributes=t}}))}instancedAttributes(e){return this.then(new u(this.gl,this.cache,r=>{const a=this.gl.instancedArraysExtension,t=this.cache.instancedAttributes,s=new Set(e);this.cache.instancedAttributes=s;const i=(l,h)=>{l.forEach(o=>{h.has(o)||a.vertexAttribDivisorANGLE(o,0)}),h.forEach(o=>{l.has(o)||a.vertexAttribDivisorANGLE(o,1)})};try{return i(t,s),r()}finally{i(s,t),this.cache.instancedAttributes=t}}))}renderTarget(e){return new u(this.gl,this.cache,r=>oe(new $(this.gl,e),a=>this.gl.settings().frameBuffer(a).viewport(0,0,e.width,e.height).apply(r)))}}class D{constructor(e,r){this.gl=e,this.handle=e.handle.createTexture(),this.format=r.format||P.Rgba,this.filter=r.filter||B.Nearest,"image"in r?(this.width=r.image instanceof HTMLImageElement?r.image.naturalWidth:r.image instanceof VideoFrame?r.image.codedWidth:r.image.width,this.height=r.image instanceof HTMLImageElement?r.image.naturalHeight:r.image instanceof VideoFrame?r.image.codedHeight:r.image.height):(this.width=r.width,this.height=r.height),e.settings().activeTexture(0).texture(0,this).apply(()=>{e.handle.pixelStorei(Mt,1),e.handle.texParameteri(p,W,this.filter),e.handle.texParameteri(p,j,this.filter),e.handle.texParameteri(p,Lt,X),e.handle.texParameteri(p,Tt,X),"image"in r?e.handle.texImage2D(p,0,this.format,this.format,L,r.image):e.handle.texImage2D(p,0,this.format,this.width,this.height,0,this.format,L,"data"in r?r.data:null)})}read(e=exports.PixelFormat.Rgba){const r=new Uint8Array(this.width*this.height*exports.PixelFormat.getChannelsCount(e));return this.gl.settings().renderTarget(this).viewport(0,0,this.width,this.height).apply(()=>{this.gl.handle.readPixels(0,0,this.width,this.height,e,L,r)}),r}setFilter(e){this.gl.handle.texParameteri(p,W,e),this.gl.handle.texParameteri(p,j,e)}dispose(){this.gl.handle.deleteTexture(this.handle)}}class ${constructor(e,r,a){this.gl=e,this.colorBuffer=r,this.depthBuffer=a,this.handle=e.handle.createFramebuffer(),e.settings().frameBuffer(this).apply(()=>{e.handle.framebufferTexture2D(O,Ot,p,r.handle,0),a&&e.handle.framebufferRenderbuffer(O,It,T,a.handle)})}dispose(){this.gl.handle.deleteFramebuffer(this.handle)}}class ye{constructor(e,r,a){this.gl=e,this.widthValue=r,this.heightValue=a,this.handle=e.handle.createRenderbuffer(),e.settings().renderBuffer(this).apply(()=>{e.handle.renderbufferStorage(T,te,r,a)})}get width(){return this.widthValue}get height(){return this.heightValue}resize(e,r){const{gl:a}=this;return(e!==this.width||r!==this.height)&&(this.widthValue=e,this.heightValue=r,a.settings().renderBuffer(this).apply(()=>{a.handle.renderbufferStorage(T,te,e,r)})),this}dispose(){this.gl.handle.deleteRenderbuffer(this.handle)}}class Ae{constructor(e,r=null,a=b.Dynamic){this.gl=e,this.usage=a,this.lengthValue=0,this.handle=e.handle.createBuffer(),r&&this.setContent(r)}get length(){return this.lengthValue}setContent(e){const r=e instanceof Float32Array?e:new Float32Array(e);this.lengthValue=r.length;const a=this.gl;return a.settings().arrayBuffer(this).apply(()=>{a.handle.bufferData(M,r,this.usage)}),this}dispose(){this.gl.handle.deleteBuffer(this.handle)}}class be{constructor(e,r=null,a=b.Dynamic){this.gl=e,this.usage=a,this.lengthValue=0,this.handle=e.handle.createBuffer(),r&&this.setContent(r)}get length(){return this.lengthValue}setContent(e){const r=e instanceof Uint8Array||e instanceof Uint16Array?e:new Uint16Array(e);this.lengthValue=r.length;const a=this.gl;return a.settings().elementsBuffer(this).apply(()=>{a.handle.bufferData(N,r,this.usage)}),this}dispose(){this.gl.handle.deleteBuffer(this.handle)}}class re{constructor(e,r,a){this.gl=e,this.type=r,this.source=a;const t=this.handle=e.handle.createShader(r);if(e.handle.shaderSource(t,a),e.handle.compileShader(t),e.handle.getShaderParameter(t,St)===!1)throw new Error(`WebGL error '${e.handle.getShaderInfoLog(t)}' in '${a}'`)}dispose(){this.gl.handle.deleteShader(this.handle)}}class Ee{constructor(e,r,a){this.gl=e,this.vertex=r,this.fragment=a,this.uniforms={},this.attributes={};const t=this.handle=e.handle.createProgram();if(e.handle.attachShader(t,r.handle),e.handle.attachShader(t,a.handle),e.handle.linkProgram(t),e.handle.validateProgram(t),e.handle.getProgramParameter(t,ot)===!1)throw new Error(e.handle.getProgramInfoLog(t)||`Program linking error:
${r.source};
${a.source}`);const s=e.handle.getProgramParameter(t,ct);for(let l=0;l<s;l++){const h=e.handle.getActiveUniform(t,l);h!==null&&(this.uniforms[h.name]={type:h.type,location:e.handle.getUniformLocation(t,h.name),size:h.size})}const i=e.handle.getProgramParameter(t,ut);for(let l=0;l<i;l++){const h=e.handle.getActiveAttrib(t,l);h!=null&&(this.attributes[h.name]={type:h.type,location:l,size:h.size})}}setUniform(e,r){const{gl:a,uniforms:t}=this,s=t[e];if(s){const{location:i,type:l}=s;a.settings().program(this).apply(()=>{switch(l){case xt:a.handle.uniform1i(i,r[0]?1:0);break;case Rt:a.handle.uniform1iv(i,r);break;case S:a.handle.uniform1fv(i,r);break;case Q:a.handle.uniform2fv(i,r);break;case Y:a.handle.uniform3fv(i,r);break;case Z:a.handle.uniform4fv(i,r);break;case K:a.handle.uniformMatrix2fv(i,!1,r);break;case J:a.handle.uniformMatrix3fv(i,!1,r);break;case ee:a.handle.uniformMatrix4fv(i,!1,r);break}})}}setAttribute(e,r,a,t){const s=this.attributes[e];if(s!=null){const{gl:i}=this;i.settings().arrayBuffer(r).apply(()=>{i.handle.vertexAttribPointer(s.location,(()=>{switch(s.type){case S:return 1;case Q:return 2;case Y:return 3;case Z:return 4;case K:return 4;case J:return 9;case ee:return 16;default:throw new Error(`Invalid attribute type '${s.type}'`)}})(),S,!1,a*4,t*4)})}else console.warn(`Attribute '${e}' not found`)}dispose(){this.gl.handle.deleteProgram(this.handle)}}exports.ArrayBuffer=Ae;exports.BlendEquation=v;exports.BlendFunction=A;exports.BufferTarget=me;exports.BufferUsage=b;exports.Command=ae;exports.DepthFunction=C;exports.ElementsBuffer=be;exports.ErrorCode=pe;exports.FaceCulling=V;exports.FrameBuffer=$;exports.Gl=Ct;exports.Glsl=m;exports.GlslBuilder=w;exports.Precision=ne;exports.PrimitivesType=ge;exports.Program=Ee;exports.RenderBuffer=ye;exports.Settings=u;exports.ShaderType=x;exports.Texture=D;exports.TextureFilter=B;exports.TextureFormat=P;exports.command=ie;exports.create=he;exports.dispose=le;exports.source=se;exports.use=oe;exports.uses=ce;exports.val=E;
//# sourceMappingURL=index.cjs.map