@jscad/regl-renderer 2.6.12 → 3.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +8 -225
  2. package/LICENSE +1 -1
  3. package/README.md +21 -11
  4. package/demo-cli.js +20 -16
  5. package/demo-web.js +6 -4
  6. package/demo.es.html +236 -0
  7. package/demo.html +21 -15
  8. package/dist/jscad-regl-renderer.es.js +13 -0
  9. package/dist/jscad-regl-renderer.min.js +13 -335
  10. package/package.json +41 -16
  11. package/rollup.config.js +27 -0
  12. package/src/bound-utils/boundingBox.js +1 -2
  13. package/src/bound-utils/boundingSphere.js +4 -5
  14. package/src/bound-utils/computeBounds.js +4 -6
  15. package/src/bound-utils/computeBounds.test.js +2 -2
  16. package/src/cameras/camera.js +15 -19
  17. package/src/cameras/index.js +8 -4
  18. package/src/cameras/orthographicCamera.js +4 -6
  19. package/src/cameras/perspectiveCamera.js +7 -9
  20. package/src/controls/index.js +6 -0
  21. package/src/controls/orbitControls.js +18 -27
  22. package/src/{geometry-utils-V2 → geometry-utils-V3}/entitiesFromSolids.js +7 -9
  23. package/src/{geometry-utils-V2 → geometry-utils-V3}/entitiesFromSolids.test.js +4 -4
  24. package/src/geometry-utils-V3/geom2ToGeometries.js +57 -0
  25. package/src/{geometry-utils-V2 → geometry-utils-V3}/geom2ToGeometries.test.js +16 -12
  26. package/src/{geometry-utils-V2 → geometry-utils-V3}/geom3ToGeometries.js +3 -5
  27. package/src/{geometry-utils-V2 → geometry-utils-V3}/geom3ToGeometries.test.js +2 -2
  28. package/src/{geometry-utils-V2 → geometry-utils-V3}/path2ToGeometries.js +4 -5
  29. package/src/{geometry-utils-V2 → geometry-utils-V3}/path2ToGeometries.test.js +2 -2
  30. package/src/index.js +5 -20
  31. package/src/rendering/commands/drawAxis/index.js +2 -4
  32. package/src/rendering/commands/drawExps/drawConnector/arcGeo.js +1 -3
  33. package/src/rendering/commands/drawExps/drawConnector/index.js +5 -7
  34. package/src/rendering/commands/drawExps/drawMesh.js +2 -4
  35. package/src/rendering/commands/drawExps/drawMeshNoNormals.js +2 -4
  36. package/src/rendering/commands/drawExps/drawNormals.js +2 -4
  37. package/src/rendering/commands/drawExps/drawNormals2.js +2 -4
  38. package/src/rendering/commands/drawGrid/{index.js → makeDrawGrid.js} +2 -4
  39. package/src/rendering/commands/drawGrid/{multi.js → makeDrawMultiGrid.js} +5 -5
  40. package/src/rendering/commands/drawLines/colorOnlyShaders.js +2 -2
  41. package/src/rendering/commands/drawLines/index.js +9 -7
  42. package/src/rendering/commands/drawLines/meshShaders.js +3 -3
  43. package/src/rendering/commands/drawLines/vColorShaders.js +3 -3
  44. package/src/rendering/commands/drawMesh/colorOnlyShaders.js +2 -2
  45. package/src/rendering/commands/drawMesh/index.js +8 -7
  46. package/src/rendering/commands/drawMesh/meshShaders.js +3 -3
  47. package/src/rendering/commands/drawMesh/vColorShaders.js +3 -3
  48. package/src/rendering/commands/index.js +11 -0
  49. package/src/rendering/render.js +10 -10
  50. package/src/rendering/renderContext.js +2 -4
  51. package/src/rendering/renderDefaults.js +9 -11
  52. package/src/utils.js +3 -6
  53. package/src/geometry-utils-V1/cagToGeometries.js +0 -52
  54. package/src/geometry-utils-V1/csgToGeometries.js +0 -220
  55. package/src/geometry-utils-V1/entitiesFromSolids.js +0 -75
  56. package/src/geometry-utils-V2/geom2ToGeometries.js +0 -66
@@ -1,335 +1,13 @@
1
- (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jscadReglRenderer = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2
- const flatten=t=>t.reduce((t,a)=>Array.isArray(a)?t.concat(flatten(a)):t.concat(a),[]);module.exports=flatten;
3
-
4
- },{}],2:[function(require,module,exports){
5
- const fnNumberSort=(o,r)=>o-r;module.exports=fnNumberSort;
6
-
7
- },{}],3:[function(require,module,exports){
8
- const head=r=>{if(Array.isArray(r)&&0!==r.length)return r[0]};module.exports=head;
9
-
10
- },{}],4:[function(require,module,exports){
11
- module.exports={flatten:require("./flatten"),fnNumberSort:require("./fnNumberSort"),head:require("./head"),insertSorted:require("./insertSorted"),nth:require("./nth"),padToLength:require("./padToLength"),toArray:require("./toArray")};
12
-
13
- },{"./flatten":1,"./fnNumberSort":2,"./head":3,"./insertSorted":5,"./nth":6,"./padToLength":7,"./toArray":8}],5:[function(require,module,exports){
14
- const insertSorted=(t,e,o)=>{let r=0,n=t.length;for(;n>r;){const s=Math.floor((r+n)/2);o(e,t[s])>0?r=s+1:n=s}return t.splice(r,0,e),t};module.exports=insertSorted;
15
-
16
- },{}],6:[function(require,module,exports){
17
- const nth=(r,t)=>{if(Array.isArray(r)&&!(r.length<t))return r[t]};module.exports=nth;
18
-
19
- },{}],7:[function(require,module,exports){
20
- const padToLength=(e,o,t)=>{for(e=e.slice();e.length<t;)e.push(o);return e};module.exports=padToLength;
21
-
22
- },{}],8:[function(require,module,exports){
23
- const toArray=r=>Array.isArray(r)?r:null==r?[]:[r];module.exports=toArray;
24
-
25
- },{}],9:[function(require,module,exports){
26
- var transform=require("./lib/projectMat4");function unproject(r,t,e,o){var n=e[0],u=e[1],a=e[2],c=e[3],p=t[0],f=t[1],i=t[2];return p-=n,f=c-f-1,f-=u,r[0]=2*p/a-1,r[1]=2*f/c-1,r[2]=2*i-1,transform(r,r,o)}module.exports=unproject;
27
-
28
- },{"./lib/projectMat4":10}],10:[function(require,module,exports){
29
- function project(r,e,o){var t=e[0],c=e[1],n=e[2],p=o[0],u=o[1],j=o[2],a=o[3],d=o[4],f=o[5],i=o[6],l=o[7],m=o[8],s=o[9],v=o[10],x=o[11],b=o[12],g=o[13],h=o[14],k=1/(t*a+c*l+n*x+o[15]);return r[0]=(t*p+c*d+n*m+b)*k,r[1]=(t*u+c*f+n*s+g)*k,r[2]=(t*j+c*i+n*v+h)*k,r}module.exports=project;
30
-
31
- },{}],11:[function(require,module,exports){
32
- function adjoint(n,o){var t=o[0],r=o[1],a=o[2],d=o[3],e=o[4],i=o[5],u=o[6],j=o[7],c=o[8],f=o[9],l=o[10],m=o[11],p=o[12],s=o[13],v=o[14],x=o[15];return n[0]=i*(l*x-m*v)-f*(u*x-j*v)+s*(u*m-j*l),n[1]=-(r*(l*x-m*v)-f*(a*x-d*v)+s*(a*m-d*l)),n[2]=r*(u*x-j*v)-i*(a*x-d*v)+s*(a*j-d*u),n[3]=-(r*(u*m-j*l)-i*(a*m-d*l)+f*(a*j-d*u)),n[4]=-(e*(l*x-m*v)-c*(u*x-j*v)+p*(u*m-j*l)),n[5]=t*(l*x-m*v)-c*(a*x-d*v)+p*(a*m-d*l),n[6]=-(t*(u*x-j*v)-e*(a*x-d*v)+p*(a*j-d*u)),n[7]=t*(u*m-j*l)-e*(a*m-d*l)+c*(a*j-d*u),n[8]=e*(f*x-m*s)-c*(i*x-j*s)+p*(i*m-j*f),n[9]=-(t*(f*x-m*s)-c*(r*x-d*s)+p*(r*m-d*f)),n[10]=t*(i*x-j*s)-e*(r*x-d*s)+p*(r*j-d*i),n[11]=-(t*(i*m-j*f)-e*(r*m-d*f)+c*(r*j-d*i)),n[12]=-(e*(f*v-l*s)-c*(i*v-u*s)+p*(i*l-u*f)),n[13]=t*(f*v-l*s)-c*(r*v-a*s)+p*(r*l-a*f),n[14]=-(t*(i*v-u*s)-e*(r*v-a*s)+p*(r*u-a*i)),n[15]=t*(i*l-u*f)-e*(r*l-a*f)+c*(r*u-a*i),n}module.exports=adjoint;
33
-
34
- },{}],12:[function(require,module,exports){
35
- function clone(e){var n=new Float32Array(16);return n[0]=e[0],n[1]=e[1],n[2]=e[2],n[3]=e[3],n[4]=e[4],n[5]=e[5],n[6]=e[6],n[7]=e[7],n[8]=e[8],n[9]=e[9],n[10]=e[10],n[11]=e[11],n[12]=e[12],n[13]=e[13],n[14]=e[14],n[15]=e[15],n}module.exports=clone;
36
-
37
- },{}],13:[function(require,module,exports){
38
- function copy(o,c){return o[0]=c[0],o[1]=c[1],o[2]=c[2],o[3]=c[3],o[4]=c[4],o[5]=c[5],o[6]=c[6],o[7]=c[7],o[8]=c[8],o[9]=c[9],o[10]=c[10],o[11]=c[11],o[12]=c[12],o[13]=c[13],o[14]=c[14],o[15]=c[15],o}module.exports=copy;
39
-
40
- },{}],14:[function(require,module,exports){
41
- function create(){var e=new Float32Array(16);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}module.exports=create;
42
-
43
- },{}],15:[function(require,module,exports){
44
- function determinant(e){var n=e[0],t=e[1],r=e[2],a=e[3],d=e[4],i=e[5],m=e[6],o=e[7],u=e[8],c=e[9],f=e[10],l=e[11],p=e[12],s=e[13],v=e[14],x=e[15];return(n*i-t*d)*(f*x-l*v)-(n*m-r*d)*(c*x-l*s)+(n*o-a*d)*(c*v-f*s)+(t*m-r*i)*(u*x-l*p)-(t*o-a*i)*(u*v-f*p)+(r*o-a*m)*(u*s-c*p)}module.exports=determinant;
45
-
46
- },{}],16:[function(require,module,exports){
47
- function fromQuat(r,o){var t=o[0],u=o[1],a=o[2],e=o[3],f=t+t,m=u+u,n=a+a,Q=t*f,c=u*f,d=u*m,i=a*f,l=a*m,p=a*n,s=e*f,v=e*m,x=e*n;return r[0]=1-d-p,r[1]=c+x,r[2]=i-v,r[3]=0,r[4]=c-x,r[5]=1-Q-p,r[6]=l+s,r[7]=0,r[8]=i+v,r[9]=l-s,r[10]=1-Q-d,r[11]=0,r[12]=0,r[13]=0,r[14]=0,r[15]=1,r}module.exports=fromQuat;
48
-
49
- },{}],17:[function(require,module,exports){
50
- function fromRotation(t,o,a){var n,r,s,e=a[0],h=a[1],i=a[2],u=Math.sqrt(e*e+h*h+i*i);return Math.abs(u)<1e-6?null:(e*=u=1/u,h*=u,i*=u,n=Math.sin(o),s=1-(r=Math.cos(o)),t[0]=e*e*s+r,t[1]=h*e*s+i*n,t[2]=i*e*s-h*n,t[3]=0,t[4]=e*h*s-i*n,t[5]=h*h*s+r,t[6]=i*h*s+e*n,t[7]=0,t[8]=e*i*s+h*n,t[9]=h*i*s-e*n,t[10]=i*i*s+r,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t)}module.exports=fromRotation;
51
-
52
- },{}],18:[function(require,module,exports){
53
- function fromRotationTranslation(o,n,t){var r=n[0],a=n[1],i=n[2],e=n[3],f=r+r,l=a+a,m=i+i,s=r*f,u=r*l,R=r*m,T=a*l,c=a*m,d=i*m,p=e*f,v=e*l,x=e*m;return o[0]=1-(T+d),o[1]=u+x,o[2]=R-v,o[3]=0,o[4]=u-x,o[5]=1-(s+d),o[6]=c+p,o[7]=0,o[8]=R+v,o[9]=c-p,o[10]=1-(s+T),o[11]=0,o[12]=t[0],o[13]=t[1],o[14]=t[2],o[15]=1,o}module.exports=fromRotationTranslation;
54
-
55
- },{}],19:[function(require,module,exports){
56
- function fromScaling(n,o){return n[0]=o[0],n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=o[1],n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=o[2],n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,n}module.exports=fromScaling;
57
-
58
- },{}],20:[function(require,module,exports){
59
- function fromTranslation(n,o){return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=o[0],n[13]=o[1],n[14]=o[2],n[15]=1,n}module.exports=fromTranslation;
60
-
61
- },{}],21:[function(require,module,exports){
62
- function fromXRotation(o,t){var n=Math.sin(t),r=Math.cos(t);return o[0]=1,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=r,o[6]=n,o[7]=0,o[8]=0,o[9]=-n,o[10]=r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,o}module.exports=fromXRotation;
63
-
64
- },{}],22:[function(require,module,exports){
65
- function fromYRotation(o,t){var n=Math.sin(t),r=Math.cos(t);return o[0]=r,o[1]=0,o[2]=-n,o[3]=0,o[4]=0,o[5]=1,o[6]=0,o[7]=0,o[8]=n,o[9]=0,o[10]=r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,o}module.exports=fromYRotation;
66
-
67
- },{}],23:[function(require,module,exports){
68
- function fromZRotation(o,t){var n=Math.sin(t),r=Math.cos(t);return o[0]=r,o[1]=n,o[2]=0,o[3]=0,o[4]=-n,o[5]=r,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=1,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,o}module.exports=fromZRotation;
69
-
70
- },{}],24:[function(require,module,exports){
71
- function frustum(u,r,t,e,f,m,n){var o=1/(t-r),s=1/(f-e),a=1/(m-n);return u[0]=2*m*o,u[1]=0,u[2]=0,u[3]=0,u[4]=0,u[5]=2*m*s,u[6]=0,u[7]=0,u[8]=(t+r)*o,u[9]=(f+e)*s,u[10]=(n+m)*a,u[11]=-1,u[12]=0,u[13]=0,u[14]=n*m*2*a,u[15]=0,u}module.exports=frustum;
72
-
73
- },{}],25:[function(require,module,exports){
74
- function identity(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}module.exports=identity;
75
-
76
- },{}],26:[function(require,module,exports){
77
- module.exports={create:require("./create"),clone:require("./clone"),copy:require("./copy"),identity:require("./identity"),transpose:require("./transpose"),invert:require("./invert"),adjoint:require("./adjoint"),determinant:require("./determinant"),multiply:require("./multiply"),translate:require("./translate"),scale:require("./scale"),rotate:require("./rotate"),rotateX:require("./rotateX"),rotateY:require("./rotateY"),rotateZ:require("./rotateZ"),fromRotation:require("./fromRotation"),fromRotationTranslation:require("./fromRotationTranslation"),fromScaling:require("./fromScaling"),fromTranslation:require("./fromTranslation"),fromXRotation:require("./fromXRotation"),fromYRotation:require("./fromYRotation"),fromZRotation:require("./fromZRotation"),fromQuat:require("./fromQuat"),frustum:require("./frustum"),perspective:require("./perspective"),perspectiveFromFieldOfView:require("./perspectiveFromFieldOfView"),ortho:require("./ortho"),lookAt:require("./lookAt"),str:require("./str")};
78
-
79
- },{"./adjoint":11,"./clone":12,"./copy":13,"./create":14,"./determinant":15,"./fromQuat":16,"./fromRotation":17,"./fromRotationTranslation":18,"./fromScaling":19,"./fromTranslation":20,"./fromXRotation":21,"./fromYRotation":22,"./fromZRotation":23,"./frustum":24,"./identity":25,"./invert":27,"./lookAt":28,"./multiply":29,"./ortho":30,"./perspective":31,"./perspectiveFromFieldOfView":32,"./rotate":33,"./rotateX":34,"./rotateY":35,"./rotateZ":36,"./scale":37,"./str":38,"./translate":39,"./transpose":40}],27:[function(require,module,exports){
80
- function invert(n,r){var e=r[0],t=r[1],u=r[2],i=r[3],l=r[4],o=r[5],v=r[6],a=r[7],c=r[8],d=r[9],f=r[10],m=r[11],p=r[12],s=r[13],x=r[14],b=r[15],g=e*o-t*l,h=e*v-u*l,j=e*a-i*l,k=t*v-u*o,q=t*a-i*o,w=u*a-i*v,y=c*s-d*p,z=c*x-f*p,A=c*b-m*p,B=d*x-f*s,C=d*b-m*s,D=f*b-m*x,E=g*D-h*C+j*B+k*A-q*z+w*y;return E?(E=1/E,n[0]=(o*D-v*C+a*B)*E,n[1]=(u*C-t*D-i*B)*E,n[2]=(s*w-x*q+b*k)*E,n[3]=(f*q-d*w-m*k)*E,n[4]=(v*A-l*D-a*z)*E,n[5]=(e*D-u*A+i*z)*E,n[6]=(x*j-p*w-b*h)*E,n[7]=(c*w-f*j+m*h)*E,n[8]=(l*C-o*A+a*y)*E,n[9]=(t*A-e*C-i*y)*E,n[10]=(p*q-s*j+b*g)*E,n[11]=(d*j-c*q-m*g)*E,n[12]=(o*z-l*B-v*y)*E,n[13]=(e*B-t*z+u*y)*E,n[14]=(s*h-p*k-x*g)*E,n[15]=(c*k-d*h+f*g)*E,n):null}module.exports=invert;
81
-
82
- },{}],28:[function(require,module,exports){
83
- var identity=require("./identity");function lookAt(t,a,e,r){var i,o,s,h,n,M,d,q,u,b,l=a[0],y=a[1],k=a[2],v=r[0],A=r[1],c=r[2],f=e[0],m=e[1],p=e[2];return Math.abs(l-f)<1e-6&&Math.abs(y-m)<1e-6&&Math.abs(k-p)<1e-6?identity(t):(d=l-f,q=y-m,u=k-p,i=A*(u*=b=1/Math.sqrt(d*d+q*q+u*u))-c*(q*=b),o=c*(d*=b)-v*u,s=v*q-A*d,(b=Math.sqrt(i*i+o*o+s*s))?(i*=b=1/b,o*=b,s*=b):(i=0,o=0,s=0),h=q*s-u*o,n=u*i-d*s,M=d*o-q*i,(b=Math.sqrt(h*h+n*n+M*M))?(h*=b=1/b,n*=b,M*=b):(h=0,n=0,M=0),t[0]=i,t[1]=h,t[2]=d,t[3]=0,t[4]=o,t[5]=n,t[6]=q,t[7]=0,t[8]=s,t[9]=M,t[10]=u,t[11]=0,t[12]=-(i*l+o*y+s*k),t[13]=-(h*l+n*y+M*k),t[14]=-(d*l+q*y+u*k),t[15]=1,t)}module.exports=lookAt;
84
-
85
- },{"./identity":25}],29:[function(require,module,exports){
86
- function multiply(l,t,u){var r=t[0],e=t[1],i=t[2],m=t[3],n=t[4],o=t[5],p=t[6],y=t[7],a=t[8],c=t[9],d=t[10],f=t[11],s=t[12],v=t[13],x=t[14],b=t[15],g=u[0],h=u[1],j=u[2],k=u[3];return l[0]=g*r+h*n+j*a+k*s,l[1]=g*e+h*o+j*c+k*v,l[2]=g*i+h*p+j*d+k*x,l[3]=g*m+h*y+j*f+k*b,g=u[4],h=u[5],j=u[6],k=u[7],l[4]=g*r+h*n+j*a+k*s,l[5]=g*e+h*o+j*c+k*v,l[6]=g*i+h*p+j*d+k*x,l[7]=g*m+h*y+j*f+k*b,g=u[8],h=u[9],j=u[10],k=u[11],l[8]=g*r+h*n+j*a+k*s,l[9]=g*e+h*o+j*c+k*v,l[10]=g*i+h*p+j*d+k*x,l[11]=g*m+h*y+j*f+k*b,g=u[12],h=u[13],j=u[14],k=u[15],l[12]=g*r+h*n+j*a+k*s,l[13]=g*e+h*o+j*c+k*v,l[14]=g*i+h*p+j*d+k*x,l[15]=g*m+h*y+j*f+k*b,l}module.exports=multiply;
87
-
88
- },{}],30:[function(require,module,exports){
89
- function ortho(o,r,t,e,n,u,h){var a=1/(r-t),c=1/(e-n),d=1/(u-h);return o[0]=-2*a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-2*c,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=2*d,o[11]=0,o[12]=(r+t)*a,o[13]=(n+e)*c,o[14]=(h+u)*d,o[15]=1,o}module.exports=ortho;
90
-
91
- },{}],31:[function(require,module,exports){
92
- function perspective(e,t,r,p,n){var a=1/Math.tan(t/2),c=1/(p-n);return e[0]=a/r,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=a,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=(n+p)*c,e[11]=-1,e[12]=0,e[13]=0,e[14]=2*n*p*c,e[15]=0,e}module.exports=perspective;
93
-
94
- },{}],32:[function(require,module,exports){
95
- function perspectiveFromFieldOfView(e,t,a,r){var h=Math.tan(t.upDegrees*Math.PI/180),i=Math.tan(t.downDegrees*Math.PI/180),n=Math.tan(t.leftDegrees*Math.PI/180),M=Math.tan(t.rightDegrees*Math.PI/180),s=2/(n+M),o=2/(h+i);return e[0]=s,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=o,e[6]=0,e[7]=0,e[8]=-(n-M)*s*.5,e[9]=(h-i)*o*.5,e[10]=r/(a-r),e[11]=-1,e[12]=0,e[13]=0,e[14]=r*a/(a-r),e[15]=0,e}module.exports=perspectiveFromFieldOfView;
96
-
97
- },{}],33:[function(require,module,exports){
98
- function rotate(t,a,r,e){var o,n,s,h,u,M,l,c,i,b,d,f,m,p,q,v,x,g,j,k,w,y,z,A,B=e[0],C=e[1],D=e[2],E=Math.sqrt(B*B+C*C+D*D);return Math.abs(E)<1e-6?null:(B*=E=1/E,C*=E,D*=E,o=Math.sin(r),s=1-(n=Math.cos(r)),h=a[0],u=a[1],M=a[2],l=a[3],c=a[4],i=a[5],b=a[6],d=a[7],f=a[8],m=a[9],p=a[10],q=a[11],v=B*B*s+n,x=C*B*s+D*o,g=D*B*s-C*o,j=B*C*s-D*o,k=C*C*s+n,w=D*C*s+B*o,y=B*D*s+C*o,z=C*D*s-B*o,A=D*D*s+n,t[0]=h*v+c*x+f*g,t[1]=u*v+i*x+m*g,t[2]=M*v+b*x+p*g,t[3]=l*v+d*x+q*g,t[4]=h*j+c*k+f*w,t[5]=u*j+i*k+m*w,t[6]=M*j+b*k+p*w,t[7]=l*j+d*k+q*w,t[8]=h*y+c*z+f*A,t[9]=u*y+i*z+m*A,t[10]=M*y+b*z+p*A,t[11]=l*y+d*z+q*A,a!==t&&(t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15]),t)}module.exports=rotate;
99
-
100
- },{}],34:[function(require,module,exports){
101
- function rotateX(t,o,r){var a=Math.sin(r),e=Math.cos(r),n=o[4],s=o[5],u=o[6],c=o[7],h=o[8],i=o[9],M=o[10],X=o[11];return o!==t&&(t[0]=o[0],t[1]=o[1],t[2]=o[2],t[3]=o[3],t[12]=o[12],t[13]=o[13],t[14]=o[14],t[15]=o[15]),t[4]=n*e+h*a,t[5]=s*e+i*a,t[6]=u*e+M*a,t[7]=c*e+X*a,t[8]=h*e-n*a,t[9]=i*e-s*a,t[10]=M*e-u*a,t[11]=X*e-c*a,t}module.exports=rotateX;
102
-
103
- },{}],35:[function(require,module,exports){
104
- function rotateY(t,o,r){var a=Math.sin(r),e=Math.cos(r),n=o[0],s=o[1],u=o[2],c=o[3],h=o[8],i=o[9],M=o[10],Y=o[11];return o!==t&&(t[4]=o[4],t[5]=o[5],t[6]=o[6],t[7]=o[7],t[12]=o[12],t[13]=o[13],t[14]=o[14],t[15]=o[15]),t[0]=n*e-h*a,t[1]=s*e-i*a,t[2]=u*e-M*a,t[3]=c*e-Y*a,t[8]=n*a+h*e,t[9]=s*a+i*e,t[10]=u*a+M*e,t[11]=c*a+Y*e,t}module.exports=rotateY;
105
-
106
- },{}],36:[function(require,module,exports){
107
- function rotateZ(t,o,r){var a=Math.sin(r),e=Math.cos(r),n=o[0],s=o[1],u=o[2],c=o[3],h=o[4],i=o[5],M=o[6],Z=o[7];return o!==t&&(t[8]=o[8],t[9]=o[9],t[10]=o[10],t[11]=o[11],t[12]=o[12],t[13]=o[13],t[14]=o[14],t[15]=o[15]),t[0]=n*e+h*a,t[1]=s*e+i*a,t[2]=u*e+M*a,t[3]=c*e+Z*a,t[4]=h*e-n*a,t[5]=i*e-s*a,t[6]=M*e-u*a,t[7]=Z*e-c*a,t}module.exports=rotateZ;
108
-
109
- },{}],37:[function(require,module,exports){
110
- function scale(e,r,a){var c=a[0],l=a[1],n=a[2];return e[0]=r[0]*c,e[1]=r[1]*c,e[2]=r[2]*c,e[3]=r[3]*c,e[4]=r[4]*l,e[5]=r[5]*l,e[6]=r[6]*l,e[7]=r[7]*l,e[8]=r[8]*n,e[9]=r[9]*n,e[10]=r[10]*n,e[11]=r[11]*n,e[12]=r[12],e[13]=r[13],e[14]=r[14],e[15]=r[15],e}module.exports=scale;
111
-
112
- },{}],38:[function(require,module,exports){
113
- function str(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}module.exports=str;
114
-
115
- },{}],39:[function(require,module,exports){
116
- function translate(t,r,a){var e,n,l,o,s,u,c,d,f,i,m,p,v=a[0],x=a[1],b=a[2];return r===t?(t[12]=r[0]*v+r[4]*x+r[8]*b+r[12],t[13]=r[1]*v+r[5]*x+r[9]*b+r[13],t[14]=r[2]*v+r[6]*x+r[10]*b+r[14],t[15]=r[3]*v+r[7]*x+r[11]*b+r[15]):(e=r[0],n=r[1],l=r[2],o=r[3],s=r[4],u=r[5],c=r[6],d=r[7],f=r[8],i=r[9],m=r[10],p=r[11],t[0]=e,t[1]=n,t[2]=l,t[3]=o,t[4]=s,t[5]=u,t[6]=c,t[7]=d,t[8]=f,t[9]=i,t[10]=m,t[11]=p,t[12]=e*v+s*x+f*b+r[12],t[13]=n*v+u*x+i*b+r[13],t[14]=l*v+c*x+m*b+r[14],t[15]=o*v+d*x+p*b+r[15]),t}module.exports=translate;
117
-
118
- },{}],40:[function(require,module,exports){
119
- function transpose(e,r){if(e===r){var s=r[1],n=r[2],o=r[3],t=r[6],a=r[7],p=r[11];e[1]=r[4],e[2]=r[8],e[3]=r[12],e[4]=s,e[6]=r[9],e[7]=r[13],e[8]=n,e[9]=t,e[11]=r[14],e[12]=o,e[13]=a,e[14]=p}else e[0]=r[0],e[1]=r[4],e[2]=r[8],e[3]=r[12],e[4]=r[1],e[5]=r[5],e[6]=r[9],e[7]=r[13],e[8]=r[2],e[9]=r[6],e[10]=r[10],e[11]=r[14],e[12]=r[3],e[13]=r[7],e[14]=r[11],e[15]=r[15];return e}module.exports=transpose;
120
-
121
- },{}],41:[function(require,module,exports){
122
- function add(d,e,n){return d[0]=e[0]+n[0],d[1]=e[1]+n[1],d[2]=e[2]+n[2],d}module.exports=add;
123
-
124
- },{}],42:[function(require,module,exports){
125
- module.exports=angle;var fromValues=require("./fromValues"),normalize=require("./normalize"),dot=require("./dot");function angle(r,e){var a=fromValues(r[0],r[1],r[2]),o=fromValues(e[0],e[1],e[2]);normalize(a,a),normalize(o,o);var l=dot(a,o);return l>1?0:Math.acos(l)}
126
-
127
- },{"./dot":52,"./fromValues":58,"./normalize":69}],43:[function(require,module,exports){
128
- function ceil(e,c){return e[0]=Math.ceil(c[0]),e[1]=Math.ceil(c[1]),e[2]=Math.ceil(c[2]),e}module.exports=ceil;
129
-
130
- },{}],44:[function(require,module,exports){
131
- function clone(e){var n=new Float32Array(3);return n[0]=e[0],n[1]=e[1],n[2]=e[2],n}module.exports=clone;
132
-
133
- },{}],45:[function(require,module,exports){
134
- function copy(o,c){return o[0]=c[0],o[1]=c[1],o[2]=c[2],o}module.exports=copy;
135
-
136
- },{}],46:[function(require,module,exports){
137
- function create(){var e=new Float32Array(3);return e[0]=0,e[1]=0,e[2]=0,e}module.exports=create;
138
-
139
- },{}],47:[function(require,module,exports){
140
- function cross(r,o,s){var c=o[0],e=o[1],n=o[2],t=s[0],u=s[1],a=s[2];return r[0]=e*a-n*u,r[1]=n*t-c*a,r[2]=c*u-e*t,r}module.exports=cross;
141
-
142
- },{}],48:[function(require,module,exports){
143
- module.exports=require("./distance");
144
-
145
- },{"./distance":49}],49:[function(require,module,exports){
146
- function distance(t,e){var n=e[0]-t[0],r=e[1]-t[1],a=e[2]-t[2];return Math.sqrt(n*n+r*r+a*a)}module.exports=distance;
147
-
148
- },{}],50:[function(require,module,exports){
149
- module.exports=require("./divide");
150
-
151
- },{"./divide":51}],51:[function(require,module,exports){
152
- function divide(d,e,i){return d[0]=e[0]/i[0],d[1]=e[1]/i[1],d[2]=e[2]/i[2],d}module.exports=divide;
153
-
154
- },{}],52:[function(require,module,exports){
155
- function dot(o,t){return o[0]*t[0]+o[1]*t[1]+o[2]*t[2]}module.exports=dot;
156
-
157
- },{}],53:[function(require,module,exports){
158
- module.exports=1e-6;
159
-
160
- },{}],54:[function(require,module,exports){
161
- module.exports=equals;var EPSILON=require("./epsilon");function equals(a,t){var s=a[0],h=a[1],M=a[2],b=t[0],e=t[1],r=t[2];return Math.abs(s-b)<=EPSILON*Math.max(1,Math.abs(s),Math.abs(b))&&Math.abs(h-e)<=EPSILON*Math.max(1,Math.abs(h),Math.abs(e))&&Math.abs(M-r)<=EPSILON*Math.max(1,Math.abs(M),Math.abs(r))}
162
-
163
- },{"./epsilon":53}],55:[function(require,module,exports){
164
- function exactEquals(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}module.exports=exactEquals;
165
-
166
- },{}],56:[function(require,module,exports){
167
- function floor(o,r){return o[0]=Math.floor(r[0]),o[1]=Math.floor(r[1]),o[2]=Math.floor(r[2]),o}module.exports=floor;
168
-
169
- },{}],57:[function(require,module,exports){
170
- module.exports=forEach;var vec=require("./create")();function forEach(e,c,r,v,t,a){var n,o;for(c||(c=3),r||(r=0),o=v?Math.min(v*c+r,e.length):e.length,n=r;n<o;n+=c)vec[0]=e[n],vec[1]=e[n+1],vec[2]=e[n+2],t(vec,vec,a),e[n]=vec[0],e[n+1]=vec[1],e[n+2]=vec[2];return e}
171
-
172
- },{"./create":46}],58:[function(require,module,exports){
173
- function fromValues(r,e,o){var a=new Float32Array(3);return a[0]=r,a[1]=e,a[2]=o,a}module.exports=fromValues;
174
-
175
- },{}],59:[function(require,module,exports){
176
- module.exports={EPSILON:require("./epsilon"),create:require("./create"),clone:require("./clone"),angle:require("./angle"),fromValues:require("./fromValues"),copy:require("./copy"),set:require("./set"),equals:require("./equals"),exactEquals:require("./exactEquals"),add:require("./add"),subtract:require("./subtract"),sub:require("./sub"),multiply:require("./multiply"),mul:require("./mul"),divide:require("./divide"),div:require("./div"),min:require("./min"),max:require("./max"),floor:require("./floor"),ceil:require("./ceil"),round:require("./round"),scale:require("./scale"),scaleAndAdd:require("./scaleAndAdd"),distance:require("./distance"),dist:require("./dist"),squaredDistance:require("./squaredDistance"),sqrDist:require("./sqrDist"),length:require("./length"),len:require("./len"),squaredLength:require("./squaredLength"),sqrLen:require("./sqrLen"),negate:require("./negate"),inverse:require("./inverse"),normalize:require("./normalize"),dot:require("./dot"),cross:require("./cross"),lerp:require("./lerp"),random:require("./random"),transformMat4:require("./transformMat4"),transformMat3:require("./transformMat3"),transformQuat:require("./transformQuat"),rotateX:require("./rotateX"),rotateY:require("./rotateY"),rotateZ:require("./rotateZ"),forEach:require("./forEach")};
177
-
178
- },{"./add":41,"./angle":42,"./ceil":43,"./clone":44,"./copy":45,"./create":46,"./cross":47,"./dist":48,"./distance":49,"./div":50,"./divide":51,"./dot":52,"./epsilon":53,"./equals":54,"./exactEquals":55,"./floor":56,"./forEach":57,"./fromValues":58,"./inverse":60,"./len":61,"./length":62,"./lerp":63,"./max":64,"./min":65,"./mul":66,"./multiply":67,"./negate":68,"./normalize":69,"./random":70,"./rotateX":71,"./rotateY":72,"./rotateZ":73,"./round":74,"./scale":75,"./scaleAndAdd":76,"./set":77,"./sqrDist":78,"./sqrLen":79,"./squaredDistance":80,"./squaredLength":81,"./sub":82,"./subtract":83,"./transformMat3":84,"./transformMat4":85,"./transformQuat":86}],60:[function(require,module,exports){
179
- function inverse(e,n){return e[0]=1/n[0],e[1]=1/n[1],e[2]=1/n[2],e}module.exports=inverse;
180
-
181
- },{}],61:[function(require,module,exports){
182
- module.exports=require("./length");
183
-
184
- },{"./length":62}],62:[function(require,module,exports){
185
- function length(t){var e=t[0],n=t[1],r=t[2];return Math.sqrt(e*e+n*n+r*r)}module.exports=length;
186
-
187
- },{}],63:[function(require,module,exports){
188
- function lerp(r,e,l,n){var o=e[0],p=e[1],t=e[2];return r[0]=o+n*(l[0]-o),r[1]=p+n*(l[1]-p),r[2]=t+n*(l[2]-t),r}module.exports=lerp;
189
-
190
- },{}],64:[function(require,module,exports){
191
- function max(a,m,t){return a[0]=Math.max(m[0],t[0]),a[1]=Math.max(m[1],t[1]),a[2]=Math.max(m[2],t[2]),a}module.exports=max;
192
-
193
- },{}],65:[function(require,module,exports){
194
- function min(n,i,m){return n[0]=Math.min(i[0],m[0]),n[1]=Math.min(i[1],m[1]),n[2]=Math.min(i[2],m[2]),n}module.exports=min;
195
-
196
- },{}],66:[function(require,module,exports){
197
- module.exports=require("./multiply");
198
-
199
- },{"./multiply":67}],67:[function(require,module,exports){
200
- function multiply(l,t,u){return l[0]=t[0]*u[0],l[1]=t[1]*u[1],l[2]=t[2]*u[2],l}module.exports=multiply;
201
-
202
- },{}],68:[function(require,module,exports){
203
- function negate(e,n){return e[0]=-n[0],e[1]=-n[1],e[2]=-n[2],e}module.exports=negate;
204
-
205
- },{}],69:[function(require,module,exports){
206
- function normalize(r,e){var n=e[0],o=e[1],t=e[2],a=n*n+o*o+t*t;return a>0&&(a=1/Math.sqrt(a),r[0]=e[0]*a,r[1]=e[1]*a,r[2]=e[2]*a),r}module.exports=normalize;
207
-
208
- },{}],70:[function(require,module,exports){
209
- function random(a,t){t=t||1;var r=2*Math.random()*Math.PI,n=2*Math.random()-1,o=Math.sqrt(1-n*n)*t;return a[0]=Math.cos(r)*o,a[1]=Math.sin(r)*o,a[2]=n*t,a}module.exports=random;
210
-
211
- },{}],71:[function(require,module,exports){
212
- function rotateX(t,o,r,a){var e=r[1],n=r[2],s=o[1]-e,u=o[2]-n,c=Math.sin(a),h=Math.cos(a);return t[0]=o[0],t[1]=e+s*h-u*c,t[2]=n+s*c+u*h,t}module.exports=rotateX;
213
-
214
- },{}],72:[function(require,module,exports){
215
- function rotateY(t,o,r,a){var e=r[0],n=r[2],s=o[0]-e,u=o[2]-n,c=Math.sin(a),h=Math.cos(a);return t[0]=e+u*c+s*h,t[1]=o[1],t[2]=n+u*h-s*c,t}module.exports=rotateY;
216
-
217
- },{}],73:[function(require,module,exports){
218
- function rotateZ(t,o,r,a){var e=r[0],n=r[1],s=o[0]-e,u=o[1]-n,c=Math.sin(a),h=Math.cos(a);return t[0]=e+s*h-u*c,t[1]=n+s*c+u*h,t[2]=o[2],t}module.exports=rotateZ;
219
-
220
- },{}],74:[function(require,module,exports){
221
- function round(n,o){return n[0]=Math.round(o[0]),n[1]=Math.round(o[1]),n[2]=Math.round(o[2]),n}module.exports=round;
222
-
223
- },{}],75:[function(require,module,exports){
224
- function scale(e,c,l){return e[0]=c[0]*l,e[1]=c[1]*l,e[2]=c[2]*l,e}module.exports=scale;
225
-
226
- },{}],76:[function(require,module,exports){
227
- function scaleAndAdd(d,e,n,A){return d[0]=e[0]+n[0]*A,d[1]=e[1]+n[1]*A,d[2]=e[2]+n[2]*A,d}module.exports=scaleAndAdd;
228
-
229
- },{}],77:[function(require,module,exports){
230
- function set(e,t,n,o){return e[0]=t,e[1]=n,e[2]=o,e}module.exports=set;
231
-
232
- },{}],78:[function(require,module,exports){
233
- module.exports=require("./squaredDistance");
234
-
235
- },{"./squaredDistance":80}],79:[function(require,module,exports){
236
- module.exports=require("./squaredLength");
237
-
238
- },{"./squaredLength":81}],80:[function(require,module,exports){
239
- function squaredDistance(e,r){var a=r[0]-e[0],n=r[1]-e[1],s=r[2]-e[2];return a*a+n*n+s*s}module.exports=squaredDistance;
240
-
241
- },{}],81:[function(require,module,exports){
242
- function squaredLength(e){var r=e[0],n=e[1],t=e[2];return r*r+n*n+t*t}module.exports=squaredLength;
243
-
244
- },{}],82:[function(require,module,exports){
245
- module.exports=require("./subtract");
246
-
247
- },{"./subtract":83}],83:[function(require,module,exports){
248
- function subtract(t,r,u){return t[0]=r[0]-u[0],t[1]=r[1]-u[1],t[2]=r[2]-u[2],t}module.exports=subtract;
249
-
250
- },{}],84:[function(require,module,exports){
251
- function transformMat3(r,t,a){var n=t[0],o=t[1],e=t[2];return r[0]=n*a[0]+o*a[3]+e*a[6],r[1]=n*a[1]+o*a[4]+e*a[7],r[2]=n*a[2]+o*a[5]+e*a[8],r}module.exports=transformMat3;
252
-
253
- },{}],85:[function(require,module,exports){
254
- function transformMat4(r,t,a){var n=t[0],o=t[1],e=t[2],f=a[3]*n+a[7]*o+a[11]*e+a[15];return f=f||1,r[0]=(a[0]*n+a[4]*o+a[8]*e+a[12])/f,r[1]=(a[1]*n+a[5]*o+a[9]*e+a[13])/f,r[2]=(a[2]*n+a[6]*o+a[10]*e+a[14])/f,r}module.exports=transformMat4;
255
-
256
- },{}],86:[function(require,module,exports){
257
- function transformQuat(r,t,a){var n=t[0],o=t[1],u=t[2],e=a[0],f=a[1],m=a[2],s=a[3],Q=s*n+f*u-m*o,c=s*o+m*n-e*u,d=s*u+e*o-f*n,i=-e*n-f*o-m*u;return r[0]=Q*s+i*-e+c*-m-d*-f,r[1]=c*s+i*-f+d*-e-Q*-m,r[2]=d*s+i*-m+Q*-f-c*-e,r}module.exports=transformQuat;
258
-
259
- },{}],87:[function(require,module,exports){
260
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.createREGL=t()}(this,function(){function e(e,t){this.id=H++,this.type=e,this.data=t}function t(e){return"["+function e(t){if(0===t.length)return[];var r=t.charAt(0),n=t.charAt(t.length-1);if(1<t.length&&r===n&&('"'===r||"'"===r))return['"'+t.substr(1,t.length-2).replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];if(r=/\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(t))return e(t.substr(0,r.index)).concat(e(r[1])).concat(e(t.substr(r.index+r[0].length)));if(1===(r=t.split(".")).length)return['"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];for(t=[],n=0;n<r.length;++n)t=t.concat(e(r[n]));return t}(e).join("][")+"]"}function r(e){return"string"==typeof e?e.split():e}function n(e){return"string"==typeof e?document.querySelector(e):e}function i(e){var t,i,a,f,o=e||{};e={};var u=[],s=[],c="undefined"==typeof window?1:window.devicePixelRatio,l=!1,p=function(e){},d=function(){};if("string"==typeof o?t=document.querySelector(o):"object"==typeof o&&("string"==typeof o.nodeName&&"function"==typeof o.appendChild&&"function"==typeof o.getBoundingClientRect?t=o:"function"==typeof o.drawArrays||"function"==typeof o.drawElements?a=(f=o).canvas:("gl"in o?f=o.gl:"canvas"in o?a=n(o.canvas):"container"in o&&(i=n(o.container)),"attributes"in o&&(e=o.attributes),"extensions"in o&&(u=r(o.extensions)),"optionalExtensions"in o&&(s=r(o.optionalExtensions)),"onDone"in o&&(p=o.onDone),"profile"in o&&(l=!!o.profile),"pixelRatio"in o&&(c=+o.pixelRatio))),t&&("canvas"===t.nodeName.toLowerCase()?a=t:i=t),!f){if(!a){if(!(t=function(e,t,r){function n(){var t=window.innerWidth,n=window.innerHeight;e!==document.body&&(t=(n=a.getBoundingClientRect()).right-n.left,n=n.bottom-n.top),a.width=r*t,a.height=r*n}var i,a=document.createElement("canvas");return R(a.style,{border:0,margin:0,padding:0,top:0,left:0,width:"100%",height:"100%"}),e.appendChild(a),e===document.body&&(a.style.position="absolute",R(e.style,{margin:0,padding:0})),e!==document.body&&"function"==typeof ResizeObserver?(i=new ResizeObserver(function(){setTimeout(n)})).observe(e):window.addEventListener("resize",n,!1),n(),{canvas:a,onDestroy:function(){i?i.disconnect():window.removeEventListener("resize",n),e.removeChild(a)}}}(i||document.body,0,c)))return null;a=t.canvas,d=t.onDestroy}void 0===e.premultipliedAlpha&&(e.premultipliedAlpha=!0),f=function(e,t){function r(r){try{return e.getContext(r,t)}catch(e){return null}}return r("webgl")||r("experimental-webgl")||r("webgl-experimental")}(a,e)}return f?{gl:f,canvas:a,container:i,extensions:u,optionalExtensions:s,pixelRatio:c,profile:l,onDone:p,onDestroy:d}:(d(),p("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"),null)}function a(e,t){for(var r=Array(e),n=0;n<e;++n)r[n]=t(n);return r}function f(e){var t,r;return t=(65535<e)<<4,t|=r=(255<(e>>>=t))<<3,(t|=r=(15<(e>>>=r))<<2)|(r=(3<(e>>>=r))<<1)|e>>>r>>1}function o(){function e(e){e:{for(var t=16;268435456>=t;t*=16)if(e<=t){e=t;break e}e=0}return 0<(t=r[f(e)>>2]).length?t.pop():new ArrayBuffer(e)}function t(e){r[f(e.byteLength)>>2].push(e)}var r=a(8,function(){return[]});return{alloc:e,free:t,allocType:function(t,r){var n=null;switch(t){case 5120:n=new Int8Array(e(r),0,r);break;case 5121:n=new Uint8Array(e(r),0,r);break;case 5122:n=new Int16Array(e(2*r),0,r);break;case 5123:n=new Uint16Array(e(2*r),0,r);break;case 5124:n=new Int32Array(e(4*r),0,r);break;case 5125:n=new Uint32Array(e(4*r),0,r);break;case 5126:n=new Float32Array(e(4*r),0,r);break;default:return null}return n.length!==r?n.subarray(0,r):n},freeType:function(e){t(e.buffer)}}}function u(e){return!!e&&"object"==typeof e&&Array.isArray(e.shape)&&Array.isArray(e.stride)&&"number"==typeof e.offset&&e.shape.length===e.stride.length&&(Array.isArray(e.data)||G(e.data))}function s(e,t,r,n,i,a){for(var f=0;f<t;++f)for(var o=e[f],u=0;u<r;++u)for(var s=o[u],c=0;c<n;++c)i[a++]=s[c]}function c(e){return 0|J[Object.prototype.toString.call(e)]}function l(e,t){for(var r=0;r<t.length;++r)e[r]=t[r]}function p(e,t,r,n,i,a,f){for(var o=0,u=0;u<r;++u)for(var s=0;s<n;++s)e[o++]=t[i*u+a*s+f]}function d(e,t,r,n){function i(t){this.id=s++,this.buffer=e.createBuffer(),this.type=t,this.usage=35044,this.byteLength=0,this.dimension=1,this.dtype=5121,this.persistentData=null,r.profile&&(this.stats={size:0})}function a(t,r,n){t.byteLength=r.byteLength,e.bufferData(t.type,r,n)}function f(e,t,r,n,i,f){if(e.usage=r,Array.isArray(t)){if(e.dtype=n||5126,0<t.length)if(Array.isArray(t[0])){i=ee(t);for(var o=n=1;o<i.length;++o)n*=i[o];e.dimension=n,a(e,t=$(t,i,e.dtype),r),f?e.persistentData=t:q.freeType(t)}else"number"==typeof t[0]?(e.dimension=i,l(i=q.allocType(e.dtype,t.length),t),a(e,i,r),f?e.persistentData=i:q.freeType(i)):G(t[0])&&(e.dimension=t[0].length,e.dtype=n||c(t[0])||5126,a(e,t=$(t,[t.length,t[0].length],e.dtype),r),f?e.persistentData=t:q.freeType(t))}else if(G(t))e.dtype=n||c(t),e.dimension=i,a(e,t,r),f&&(e.persistentData=new Uint8Array(new Uint8Array(t.buffer)));else if(u(t)){i=t.shape;var s=t.stride,d=(o=t.offset,0),h=0,m=0,b=0;1===i.length?(d=i[0],h=1,m=s[0],b=0):2===i.length&&(d=i[0],h=i[1],m=s[0],b=s[1]),e.dtype=n||c(t.data)||5126,e.dimension=h,p(i=q.allocType(e.dtype,d*h),t.data,d,h,m,b,o),a(e,i,r),f?e.persistentData=i:q.freeType(i)}else t instanceof ArrayBuffer&&(e.dtype=5121,e.dimension=i,a(e,t,r),f&&(e.persistentData=new Uint8Array(new Uint8Array(t))))}function o(r){t.bufferCount--,n(r),e.deleteBuffer(r.buffer),r.buffer=null,delete d[r.id]}var s=0,d={};i.prototype.bind=function(){e.bindBuffer(this.type,this.buffer)},i.prototype.destroy=function(){o(this)};var h=[];return r.profile&&(t.getTotalBufferSize=function(){var e=0;return Object.keys(d).forEach(function(t){e+=d[t].stats.size}),e}),{create:function(n,a,s,h){function m(t){var n=35044,i=null,a=0,o=0,s=1;return Array.isArray(t)||G(t)||u(t)||t instanceof ArrayBuffer?i=t:"number"==typeof t?a=0|t:t&&("data"in t&&(i=t.data),"usage"in t&&(n=Z[t.usage]),"type"in t&&(o=K[t.type]),"dimension"in t&&(s=0|t.dimension),"length"in t&&(a=0|t.length)),b.bind(),i?f(b,i,n,o,s,h):(a&&e.bufferData(b.type,a,n),b.dtype=o||5121,b.usage=n,b.dimension=s,b.byteLength=a),r.profile&&(b.stats.size=b.byteLength*te[b.dtype]),m}t.bufferCount++;var b=new i(a);return d[b.id]=b,s||m(n),m._reglType="buffer",m._buffer=b,m.subdata=function(t,r){var n,i=0|(r||0);if(b.bind(),G(t)||t instanceof ArrayBuffer)e.bufferSubData(b.type,i,t);else if(Array.isArray(t)){if(0<t.length)if("number"==typeof t[0]){var a=q.allocType(b.dtype,t.length);l(a,t),e.bufferSubData(b.type,i,a),q.freeType(a)}else(Array.isArray(t[0])||G(t[0]))&&(n=ee(t),a=$(t,n,b.dtype),e.bufferSubData(b.type,i,a),q.freeType(a))}else if(u(t)){n=t.shape;var f=t.stride,o=a=0,s=0,d=0;1===n.length?(a=n[0],o=1,s=f[0],d=0):2===n.length&&(a=n[0],o=n[1],s=f[0],d=f[1]),n=Array.isArray(t.data)?b.dtype:c(t.data),p(n=q.allocType(n,a*o),t.data,a,o,s,d,t.offset),e.bufferSubData(b.type,i,n),q.freeType(n)}return m},r.profile&&(m.stats=b.stats),m.destroy=function(){o(b)},m},createStream:function(e,t){var r=h.pop();return r||(r=new i(e)),r.bind(),f(r,t,35040,0,1,!1),r},destroyStream:function(e){h.push(e)},clear:function(){Y(d).forEach(o),h.forEach(o)},getBuffer:function(e){return e&&e._buffer instanceof i?e._buffer:null},restore:function(){Y(d).forEach(function(t){t.buffer=e.createBuffer(),e.bindBuffer(t.type,t.buffer),e.bufferData(t.type,t.persistentData||t.byteLength,t.usage)})},_initBuffer:f}}function h(e,t,r,n){function i(e){this.id=s++,o[this.id]=this,this.buffer=e,this.primType=4,this.type=this.vertCount=0}function a(n,i,a,f,o,s,c){var l;if(n.buffer.bind(),i?((l=c)||G(i)&&(!u(i)||G(i.data))||(l=t.oes_element_index_uint?5125:5123),r._initBuffer(n.buffer,i,a,l,3)):(e.bufferData(34963,s,a),n.buffer.dtype=l||5121,n.buffer.usage=a,n.buffer.dimension=3,n.buffer.byteLength=s),l=c,!c){switch(n.buffer.dtype){case 5121:case 5120:l=5121;break;case 5123:case 5122:l=5123;break;case 5125:case 5124:l=5125}n.buffer.dtype=l}n.type=l,0>(i=o)&&(i=n.buffer.byteLength,5123===l?i>>=1:5125===l&&(i>>=2)),n.vertCount=i,i=f,0>f&&(i=4,1===(f=n.buffer.dimension)&&(i=0),2===f&&(i=1),3===f&&(i=4)),n.primType=i}function f(e){n.elementsCount--,delete o[e.id],e.buffer.destroy(),e.buffer=null}var o={},s=0,c={uint8:5121,uint16:5123};t.oes_element_index_uint&&(c.uint32=5125),i.prototype.bind=function(){this.buffer.bind()};var l=[];return{create:function(e,t){function o(e){if(e)if("number"==typeof e)s(e),l.primType=4,l.vertCount=0|e,l.type=5121;else{var t=null,r=35044,n=-1,i=-1,f=0,p=0;Array.isArray(e)||G(e)||u(e)?t=e:("data"in e&&(t=e.data),"usage"in e&&(r=Z[e.usage]),"primitive"in e&&(n=re[e.primitive]),"count"in e&&(i=0|e.count),"type"in e&&(p=c[e.type]),"length"in e?f=0|e.length:(f=i,5123===p||5122===p?f*=2:5125!==p&&5124!==p||(f*=4))),a(l,t,r,n,i,f,p)}else s(),l.primType=4,l.vertCount=0,l.type=5121;return o}var s=r.create(null,34963,!0),l=new i(s._buffer);return n.elementsCount++,o(e),o._reglType="elements",o._elements=l,o.subdata=function(e,t){return s.subdata(e,t),o},o.destroy=function(){f(l)},o},createStream:function(e){var t=l.pop();return t||(t=new i(r.create(null,34963,!0,!1)._buffer)),a(t,e,35040,-1,-1,0,0),t},destroyStream:function(e){l.push(e)},getElements:function(e){return"function"==typeof e&&e._elements instanceof i?e._elements:null},clear:function(){Y(o).forEach(f)}}}function m(e){for(var t=q.allocType(5123,e.length),r=0;r<e.length;++r)if(isNaN(e[r]))t[r]=65535;else if(1/0===e[r])t[r]=31744;else if(-1/0===e[r])t[r]=64512;else{ne[0]=e[r];var n=(a=ie[0])>>>31<<15,i=(a<<1>>>24)-127,a=a>>13&1023;t[r]=-24>i?n:-14>i?n+(a+1024>>-14-i):15<i?n+31744:n+(i+15<<10)+a}return t}function b(e){return Array.isArray(e)||G(e)}function g(e){return"[object "+e+"]"}function y(e){return Array.isArray(e)&&(0===e.length||"number"==typeof e[0])}function v(e){return!(!Array.isArray(e)||0===e.length||!b(e[0]))}function x(e){return Object.prototype.toString.call(e)}function w(e){if(!e)return!1;var t=x(e);return 0<=he.indexOf(t)||(y(e)||v(e)||u(e))}function A(e,t){36193===e.type?(e.data=m(t),q.freeType(t)):e.data=t}function k(e,t,r,n,i,a){if(e=void 0!==be[e]?be[e]:oe[e]*me[t],a&&(e*=6),i){for(n=0;1<=r;)n+=e*r*r,r/=2;return n}return e*r*n}function _(e,t,r,n,i,a,f){function o(){this.format=this.internalformat=6408,this.type=5121,this.flipY=this.premultiplyAlpha=this.compressed=!1,this.unpackAlignment=1,this.colorSpace=37444,this.channels=this.height=this.width=0}function s(e,t){e.internalformat=t.internalformat,e.format=t.format,e.type=t.type,e.compressed=t.compressed,e.premultiplyAlpha=t.premultiplyAlpha,e.flipY=t.flipY,e.unpackAlignment=t.unpackAlignment,e.colorSpace=t.colorSpace,e.width=t.width,e.height=t.height,e.channels=t.channels}function c(e,t){if("object"==typeof t&&t){"premultiplyAlpha"in t&&(e.premultiplyAlpha=t.premultiplyAlpha),"flipY"in t&&(e.flipY=t.flipY),"alignment"in t&&(e.unpackAlignment=t.alignment),"colorSpace"in t&&(e.colorSpace=U[t.colorSpace]),"type"in t&&(e.type=N[t.type]);var r=e.width,n=e.height,i=e.channels,a=!1;"shape"in t?(r=t.shape[0],n=t.shape[1],3===t.shape.length&&(i=t.shape[2],a=!0)):("radius"in t&&(r=n=t.radius),"width"in t&&(r=t.width),"height"in t&&(n=t.height),"channels"in t&&(i=t.channels,a=!0)),e.width=0|r,e.height=0|n,e.channels=0|i,r=!1,"format"in t&&(r=t.format,n=e.internalformat=Q[r],e.format=he[n],r in N&&!("type"in t)&&(e.type=N[r]),r in K&&(e.compressed=!0),r=!0),!a&&r?e.channels=oe[e.format]:a&&!r&&e.channels!==fe[e.format]&&(e.format=e.internalformat=fe[e.channels])}}function l(t){e.pixelStorei(37440,t.flipY),e.pixelStorei(37441,t.premultiplyAlpha),e.pixelStorei(37443,t.colorSpace),e.pixelStorei(3317,t.unpackAlignment)}function p(){o.call(this),this.yOffset=this.xOffset=0,this.data=null,this.needsFree=!1,this.element=null,this.needsCopy=!1}function d(e,t){var r=null;if(w(t)?r=t:t&&(c(e,t),"x"in t&&(e.xOffset=0|t.x),"y"in t&&(e.yOffset=0|t.y),w(t.data)&&(r=t.data)),t.copy){var n=i.viewportWidth,a=i.viewportHeight;e.width=e.width||n-e.xOffset,e.height=e.height||a-e.yOffset,e.needsCopy=!0}else if(r){if(G(r))e.channels=e.channels||4,e.data=r,"type"in t||5121!==e.type||(e.type=0|J[Object.prototype.toString.call(r)]);else if(y(r)){switch(e.channels=e.channels||4,a=(n=r).length,e.type){case 5121:case 5123:case 5125:case 5126:(a=q.allocType(e.type,a)).set(n),e.data=a;break;case 36193:e.data=m(n)}e.alignment=1,e.needsFree=!0}else if(u(r)){n=r.data,Array.isArray(n)||5121!==e.type||(e.type=0|J[Object.prototype.toString.call(n)]);a=r.shape;var f,o,s,l,p=r.stride;3===a.length?(s=a[2],l=p[2]):l=s=1,f=a[0],o=a[1],a=p[0],p=p[1],e.alignment=1,e.width=f,e.height=o,e.channels=s,e.format=e.internalformat=fe[s],e.needsFree=!0,f=l,r=r.offset,s=e.width,l=e.height,o=e.channels;for(var d=q.allocType(36193===e.type?5126:e.type,s*l*o),h=0,g=0;g<l;++g)for(var k=0;k<s;++k)for(var _=0;_<o;++_)d[h++]=n[a*k+p*g+f*_+r];A(e,d)}else if(x(r)===ue||x(r)===se||x(r)===ce)x(r)===ue||x(r)===se?e.element=r:e.element=r.canvas,e.width=e.element.width,e.height=e.element.height,e.channels=4;else if(x(r)===le)e.element=r,e.width=r.width,e.height=r.height,e.channels=4;else if(x(r)===pe)e.element=r,e.width=r.naturalWidth,e.height=r.naturalHeight,e.channels=4;else if(x(r)===de)e.element=r,e.width=r.videoWidth,e.height=r.videoHeight,e.channels=4;else if(v(r)){for(n=e.width||r[0].length,a=e.height||r.length,p=e.channels,p=b(r[0][0])?p||r[0][0].length:p||1,f=X.shape(r),s=1,l=0;l<f.length;++l)s*=f[l];s=q.allocType(36193===e.type?5126:e.type,s),X.flatten(r,f,"",s),A(e,s),e.alignment=1,e.width=n,e.height=a,e.channels=p,e.format=e.internalformat=fe[p],e.needsFree=!0}}else e.width=e.width||1,e.height=e.height||1,e.channels=e.channels||4}function h(t,r,i,a,f){var o=t.element,u=t.data,s=t.internalformat,c=t.format,p=t.type,d=t.width,h=t.height;l(t),o?e.texSubImage2D(r,f,i,a,c,p,o):t.compressed?e.compressedTexSubImage2D(r,f,i,a,s,d,h,u):t.needsCopy?(n(),e.copyTexSubImage2D(r,f,i,a,t.xOffset,t.yOffset,d,h)):e.texSubImage2D(r,f,i,a,d,h,c,p,u)}function g(){return me.pop()||new p}function _(e){e.needsFree&&q.freeType(e.data),p.call(e),me.push(e)}function O(){o.call(this),this.genMipmaps=!1,this.mipmapHint=4352,this.mipmask=0,this.images=Array(16)}function E(e,t,r){var n=e.images[0]=g();e.mipmask=1,n.width=e.width=t,n.height=e.height=r,n.channels=e.channels=4}function D(e,t){var r=null;if(w(t))s(r=e.images[0]=g(),e),d(r,t),e.mipmask=1;else if(c(e,t),Array.isArray(t.mipmap))for(var n=t.mipmap,i=0;i<n.length;++i)s(r=e.images[i]=g(),e),r.width>>=i,r.height>>=i,d(r,n[i]),e.mipmask|=1<<i;else s(r=e.images[0]=g(),e),d(r,t),e.mipmask=1;s(e,e.images[0])}function T(t,r){for(var i=t.images,a=0;a<i.length&&i[a];++a){var f=i[a],o=r,u=a,s=f.element,c=f.data,p=f.internalformat,d=f.format,h=f.type,m=f.width,b=f.height;l(f),s?e.texImage2D(o,u,d,d,h,s):f.compressed?e.compressedTexImage2D(o,u,p,m,b,0,c):f.needsCopy?(n(),e.copyTexImage2D(o,u,d,f.xOffset,f.yOffset,m,b,0)):e.texImage2D(o,u,d,m,b,0,d,h,c||null)}}function S(){var e=be.pop()||new O;o.call(e);for(var t=e.mipmask=0;16>t;++t)e.images[t]=null;return e}function j(e){for(var t=e.images,r=0;r<t.length;++r)t[r]&&_(t[r]),t[r]=null;be.push(e)}function C(){this.magFilter=this.minFilter=9728,this.wrapT=this.wrapS=33071,this.anisotropic=1,this.genMipmaps=!1,this.mipmapHint=4352}function V(e,t){"min"in t&&(e.minFilter=W[t.min],0<=ae.indexOf(e.minFilter)&&!("faces"in t)&&(e.genMipmaps=!0)),"mag"in t&&(e.magFilter=H[t.mag]);var r=e.wrapS,n=e.wrapT;if("wrap"in t){var i=t.wrap;"string"==typeof i?r=n=M[i]:Array.isArray(i)&&(r=M[i[0]],n=M[i[1]])}else"wrapS"in t&&(r=M[t.wrapS]),"wrapT"in t&&(n=M[t.wrapT]);if(e.wrapS=r,e.wrapT=n,"anisotropic"in t&&(e.anisotropic=t.anisotropic),"mipmap"in t){switch(r=!1,typeof t.mipmap){case"string":e.mipmapHint=L[t.mipmap],r=e.genMipmaps=!0;break;case"boolean":r=e.genMipmaps=t.mipmap;break;case"object":e.genMipmaps=!1,r=!0}!r||"min"in t||(e.minFilter=9984)}}function F(r,n){e.texParameteri(n,10241,r.minFilter),e.texParameteri(n,10240,r.magFilter),e.texParameteri(n,10242,r.wrapS),e.texParameteri(n,10243,r.wrapT),t.ext_texture_filter_anisotropic&&e.texParameteri(n,34046,r.anisotropic),r.genMipmaps&&(e.hint(33170,r.mipmapHint),e.generateMipmap(n))}function B(t){o.call(this),this.mipmask=0,this.internalformat=6408,this.id=ge++,this.refCount=1,this.target=t,this.texture=e.createTexture(),this.unit=-1,this.bindCount=0,this.texInfo=new C,f.profile&&(this.stats={size:0})}function z(t){e.activeTexture(33984),e.bindTexture(t.target,t.texture)}function I(){var t=xe[0];t?e.bindTexture(t.target,t.texture):e.bindTexture(3553,null)}function P(t){var r=t.texture,n=t.unit,i=t.target;0<=n&&(e.activeTexture(33984+n),e.bindTexture(i,null),xe[n]=null),e.deleteTexture(r),t.texture=null,t.params=null,t.pixels=null,t.refCount=0,delete ye[t.id],a.textureCount--}var L={"don't care":4352,"dont care":4352,nice:4354,fast:4353},M={repeat:10497,clamp:33071,mirror:33648},H={nearest:9728,linear:9729},W=R({mipmap:9987,"nearest mipmap nearest":9984,"linear mipmap nearest":9985,"nearest mipmap linear":9986,"linear mipmap linear":9987},H),U={none:0,browser:37444},N={uint8:5121,rgba4:32819,rgb565:33635,"rgb5 a1":32820},Q={alpha:6406,luminance:6409,"luminance alpha":6410,rgb:6407,rgba:6408,rgba4:32854,"rgb5 a1":32855,rgb565:36194},K={};t.ext_srgb&&(Q.srgb=35904,Q.srgba=35906),t.oes_texture_float&&(N.float32=N.float=5126),t.oes_texture_half_float&&(N.float16=N["half float"]=36193),t.webgl_depth_texture&&(R(Q,{depth:6402,"depth stencil":34041}),R(N,{uint16:5123,uint32:5125,"depth stencil":34042})),t.webgl_compressed_texture_s3tc&&R(K,{"rgb s3tc dxt1":33776,"rgba s3tc dxt1":33777,"rgba s3tc dxt3":33778,"rgba s3tc dxt5":33779}),t.webgl_compressed_texture_atc&&R(K,{"rgb atc":35986,"rgba atc explicit alpha":35987,"rgba atc interpolated alpha":34798}),t.webgl_compressed_texture_pvrtc&&R(K,{"rgb pvrtc 4bppv1":35840,"rgb pvrtc 2bppv1":35841,"rgba pvrtc 4bppv1":35842,"rgba pvrtc 2bppv1":35843}),t.webgl_compressed_texture_etc1&&(K["rgb etc1"]=36196);var Z=Array.prototype.slice.call(e.getParameter(34467));Object.keys(K).forEach(function(e){var t=K[e];0<=Z.indexOf(t)&&(Q[e]=t)});var $=Object.keys(Q);r.textureFormats=$;var ee=[];Object.keys(Q).forEach(function(e){ee[Q[e]]=e});var te=[];Object.keys(N).forEach(function(e){te[N[e]]=e});var re=[];Object.keys(H).forEach(function(e){re[H[e]]=e});var ne=[];Object.keys(W).forEach(function(e){ne[W[e]]=e});var ie=[];Object.keys(M).forEach(function(e){ie[M[e]]=e});var he=$.reduce(function(e,r){var n=Q[r];return 6409===n||6406===n||6409===n||6410===n||6402===n||34041===n||t.ext_srgb&&(35904===n||35906===n)?e[n]=n:32855===n||0<=r.indexOf("rgba")?e[n]=6408:e[n]=6407,e},{}),me=[],be=[],ge=0,ye={},ve=r.maxTextureUnits,xe=Array(ve).map(function(){return null});return R(B.prototype,{bind:function(){this.bindCount+=1;var t=this.unit;if(0>t){for(var r=0;r<ve;++r){var n=xe[r];if(n){if(0<n.bindCount)continue;n.unit=-1}xe[r]=this,t=r;break}f.profile&&a.maxTextureUnits<t+1&&(a.maxTextureUnits=t+1),this.unit=t,e.activeTexture(33984+t),e.bindTexture(this.target,this.texture)}return t},unbind:function(){--this.bindCount},decRef:function(){0>=--this.refCount&&P(this)}}),f.profile&&(a.getTotalTextureSize=function(){var e=0;return Object.keys(ye).forEach(function(t){e+=ye[t].stats.size}),e}),{create2D:function(t,r){function n(e,t){var r=i.texInfo;C.call(r);var a=S();return"number"==typeof e?E(a,0|e,"number"==typeof t?0|t:0|e):e?(V(r,e),D(a,e)):E(a,1,1),r.genMipmaps&&(a.mipmask=(a.width<<1)-1),i.mipmask=a.mipmask,s(i,a),i.internalformat=a.internalformat,n.width=a.width,n.height=a.height,z(i),T(a,3553),F(r,3553),I(),j(a),f.profile&&(i.stats.size=k(i.internalformat,i.type,a.width,a.height,r.genMipmaps,!1)),n.format=ee[i.internalformat],n.type=te[i.type],n.mag=re[r.magFilter],n.min=ne[r.minFilter],n.wrapS=ie[r.wrapS],n.wrapT=ie[r.wrapT],n}var i=new B(3553);return ye[i.id]=i,a.textureCount++,n(t,r),n.subimage=function(e,t,r,a){t|=0,r|=0,a|=0;var f=g();return s(f,i),f.width=0,f.height=0,d(f,e),f.width=f.width||(i.width>>a)-t,f.height=f.height||(i.height>>a)-r,z(i),h(f,3553,t,r,a),I(),_(f),n},n.resize=function(t,r){var a=0|t,o=0|r||a;if(a===i.width&&o===i.height)return n;n.width=i.width=a,n.height=i.height=o,z(i);for(var u=0;i.mipmask>>u;++u){var s=a>>u,c=o>>u;if(!s||!c)break;e.texImage2D(3553,u,i.format,s,c,0,i.format,i.type,null)}return I(),f.profile&&(i.stats.size=k(i.internalformat,i.type,a,o,!1,!1)),n},n._reglType="texture2d",n._texture=i,f.profile&&(n.stats=i.stats),n.destroy=function(){i.decRef()},n},createCube:function(t,r,n,i,o,u){function l(e,t,r,n,i,a){var o,u=p.texInfo;for(C.call(u),o=0;6>o;++o)m[o]=S();if("number"!=typeof e&&e){if("object"==typeof e)if(t)D(m[0],e),D(m[1],t),D(m[2],r),D(m[3],n),D(m[4],i),D(m[5],a);else if(V(u,e),c(p,e),"faces"in e)for(e=e.faces,o=0;6>o;++o)s(m[o],p),D(m[o],e[o]);else for(o=0;6>o;++o)D(m[o],e)}else for(e=0|e||1,o=0;6>o;++o)E(m[o],e,e);for(s(p,m[0]),p.mipmask=u.genMipmaps?(m[0].width<<1)-1:m[0].mipmask,p.internalformat=m[0].internalformat,l.width=m[0].width,l.height=m[0].height,z(p),o=0;6>o;++o)T(m[o],34069+o);for(F(u,34067),I(),f.profile&&(p.stats.size=k(p.internalformat,p.type,l.width,l.height,u.genMipmaps,!0)),l.format=ee[p.internalformat],l.type=te[p.type],l.mag=re[u.magFilter],l.min=ne[u.minFilter],l.wrapS=ie[u.wrapS],l.wrapT=ie[u.wrapT],o=0;6>o;++o)j(m[o]);return l}var p=new B(34067);ye[p.id]=p,a.cubeCount++;var m=Array(6);return l(t,r,n,i,o,u),l.subimage=function(e,t,r,n,i){r|=0,n|=0,i|=0;var a=g();return s(a,p),a.width=0,a.height=0,d(a,t),a.width=a.width||(p.width>>i)-r,a.height=a.height||(p.height>>i)-n,z(p),h(a,34069+e,r,n,i),I(),_(a),l},l.resize=function(t){if((t|=0)!==p.width){l.width=p.width=t,l.height=p.height=t,z(p);for(var r=0;6>r;++r)for(var n=0;p.mipmask>>n;++n)e.texImage2D(34069+r,n,p.format,t>>n,t>>n,0,p.format,p.type,null);return I(),f.profile&&(p.stats.size=k(p.internalformat,p.type,l.width,l.height,!1,!0)),l}},l._reglType="textureCube",l._texture=p,f.profile&&(l.stats=p.stats),l.destroy=function(){p.decRef()},l},clear:function(){for(var t=0;t<ve;++t)e.activeTexture(33984+t),e.bindTexture(3553,null),xe[t]=null;Y(ye).forEach(P),a.cubeCount=0,a.textureCount=0},getTexture:function(e){return null},restore:function(){for(var t=0;t<ve;++t){var r=xe[t];r&&(r.bindCount=0,r.unit=-1,xe[t]=null)}Y(ye).forEach(function(t){t.texture=e.createTexture(),e.bindTexture(t.target,t.texture);for(var r=0;32>r;++r)if(0!=(t.mipmask&1<<r))if(3553===t.target)e.texImage2D(3553,r,t.internalformat,t.width>>r,t.height>>r,0,t.internalformat,t.type,null);else for(var n=0;6>n;++n)e.texImage2D(34069+n,r,t.internalformat,t.width>>r,t.height>>r,0,t.internalformat,t.type,null);F(t.texInfo,t.target)})},refresh:function(){for(var t=0;t<ve;++t){var r=xe[t];r&&(r.bindCount=0,r.unit=-1,xe[t]=null),e.activeTexture(33984+t),e.bindTexture(3553,null),e.bindTexture(34067,null)}}}}function O(e,t,r,n,i,a){function f(e,t,r){this.target=e,this.texture=t,this.renderbuffer=r;var n=e=0;t?(e=t.width,n=t.height):r&&(e=r.width,n=r.height),this.width=e,this.height=n}function o(e){e&&(e.texture&&e.texture._texture.decRef(),e.renderbuffer&&e.renderbuffer._renderbuffer.decRef())}function u(e,t,r){e&&(e.texture?e.texture._texture.refCount+=1:e.renderbuffer._renderbuffer.refCount+=1)}function s(t,r){r&&(r.texture?e.framebufferTexture2D(36160,t,r.target,r.texture._texture.texture,0):e.framebufferRenderbuffer(36160,t,36161,r.renderbuffer._renderbuffer.renderbuffer))}function c(e){var t=3553,r=null,n=null,i=e;return"object"==typeof e&&(i=e.data,"target"in e&&(t=0|e.target)),"texture2d"===(e=i._reglType)?r=i:"textureCube"===e?r=i:"renderbuffer"===e&&(n=i,t=36161),new f(t,r,n)}function l(e,t,r,a,o){return r?((e=n.create2D({width:e,height:t,format:a,type:o}))._texture.refCount=0,new f(3553,e,null)):((e=i.create({width:e,height:t,format:a}))._renderbuffer.refCount=0,new f(36161,null,e))}function p(e){return e&&(e.texture||e.renderbuffer)}function d(e,t,r){e&&(e.texture?e.texture.resize(t,r):e.renderbuffer&&e.renderbuffer.resize(t,r),e.width=t,e.height=r)}function h(){this.id=k++,_[this.id]=this,this.framebuffer=e.createFramebuffer(),this.height=this.width=0,this.colorAttachments=[],this.depthStencilAttachment=this.stencilAttachment=this.depthAttachment=null}function m(e){e.colorAttachments.forEach(o),o(e.depthAttachment),o(e.stencilAttachment),o(e.depthStencilAttachment)}function b(t){e.deleteFramebuffer(t.framebuffer),t.framebuffer=null,a.framebufferCount--,delete _[t.id]}function g(t){var n;e.bindFramebuffer(36160,t.framebuffer);var i=t.colorAttachments;for(n=0;n<i.length;++n)s(36064+n,i[n]);for(n=i.length;n<r.maxColorAttachments;++n)e.framebufferTexture2D(36160,36064+n,3553,null,0);e.framebufferTexture2D(36160,33306,3553,null,0),e.framebufferTexture2D(36160,36096,3553,null,0),e.framebufferTexture2D(36160,36128,3553,null,0),s(36096,t.depthAttachment),s(36128,t.stencilAttachment),s(33306,t.depthStencilAttachment),e.checkFramebufferStatus(36160),e.isContextLost(),e.bindFramebuffer(36160,v.next?v.next.framebuffer:null),v.cur=v.next,e.getError()}function y(e,t){function r(e,t){var i,a=0,f=0,o=!0,s=!0;i=null;var d=!0,h="rgba",b="uint8",y=1,v=null,A=null,k=null,_=!1;"number"==typeof e?(a=0|e,f=0|t||a):e?("shape"in e?(a=(f=e.shape)[0],f=f[1]):("radius"in e&&(a=f=e.radius),"width"in e&&(a=e.width),"height"in e&&(f=e.height)),("color"in e||"colors"in e)&&(i=e.color||e.colors,Array.isArray(i)),i||("colorCount"in e&&(y=0|e.colorCount),"colorTexture"in e&&(d=!!e.colorTexture,h="rgba4"),"colorType"in e&&(b=e.colorType,!d)&&("half float"===b||"float16"===b?h="rgba16f":"float"!==b&&"float32"!==b||(h="rgba32f")),"colorFormat"in e&&(h=e.colorFormat,0<=x.indexOf(h)?d=!0:0<=w.indexOf(h)&&(d=!1))),("depthTexture"in e||"depthStencilTexture"in e)&&(_=!(!e.depthTexture&&!e.depthStencilTexture)),"depth"in e&&("boolean"==typeof e.depth?o=e.depth:(v=e.depth,s=!1)),"stencil"in e&&("boolean"==typeof e.stencil?s=e.stencil:(A=e.stencil,o=!1)),"depthStencil"in e&&("boolean"==typeof e.depthStencil?o=s=e.depthStencil:(k=e.depthStencil,s=o=!1))):a=f=1;var O=null,E=null,D=null,T=null;if(Array.isArray(i))O=i.map(c);else if(i)O=[c(i)];else for(O=Array(y),i=0;i<y;++i)O[i]=l(a,f,d,h,b);for(a=a||O[0].width,f=f||O[0].height,v?E=c(v):o&&!s&&(E=l(a,f,_,"depth","uint32")),A?D=c(A):s&&!o&&(D=l(a,f,!1,"stencil","uint8")),k?T=c(k):!v&&!A&&s&&o&&(T=l(a,f,_,"depth stencil","depth stencil")),o=null,i=0;i<O.length;++i)u(O[i]),O[i]&&O[i].texture&&(s=ve[O[i].texture._texture.format]*xe[O[i].texture._texture.type],null===o&&(o=s));return u(E),u(D),u(T),m(n),n.width=a,n.height=f,n.colorAttachments=O,n.depthAttachment=E,n.stencilAttachment=D,n.depthStencilAttachment=T,r.color=O.map(p),r.depth=p(E),r.stencil=p(D),r.depthStencil=p(T),r.width=n.width,r.height=n.height,g(n),r}var n=new h;return a.framebufferCount++,r(e,t),R(r,{resize:function(e,t){var i=Math.max(0|e,1),a=Math.max(0|t||i,1);if(i===n.width&&a===n.height)return r;for(var f=n.colorAttachments,o=0;o<f.length;++o)d(f[o],i,a);return d(n.depthAttachment,i,a),d(n.stencilAttachment,i,a),d(n.depthStencilAttachment,i,a),n.width=r.width=i,n.height=r.height=a,g(n),r},_reglType:"framebuffer",_framebuffer:n,destroy:function(){b(n),m(n)},use:function(e){v.setFBO({framebuffer:r},e)}})}var v={cur:null,next:null,dirty:!1,setFBO:null},x=["rgba"],w=["rgba4","rgb565","rgb5 a1"];t.ext_srgb&&w.push("srgba"),t.ext_color_buffer_half_float&&w.push("rgba16f","rgb16f"),t.webgl_color_buffer_float&&w.push("rgba32f");var A=["uint8"];t.oes_texture_half_float&&A.push("half float","float16"),t.oes_texture_float&&A.push("float","float32");var k=0,_={};return R(v,{getFramebuffer:function(e){return"function"==typeof e&&"framebuffer"===e._reglType&&(e=e._framebuffer)instanceof h?e:null},create:y,createCube:function(e){function t(e){var i,a={color:null},f=0,o=null;i="rgba";var u="uint8",s=1;if("number"==typeof e?f=0|e:e?("shape"in e?f=e.shape[0]:("radius"in e&&(f=0|e.radius),"width"in e?f=0|e.width:"height"in e&&(f=0|e.height)),("color"in e||"colors"in e)&&(o=e.color||e.colors,Array.isArray(o)),o||("colorCount"in e&&(s=0|e.colorCount),"colorType"in e&&(u=e.colorType),"colorFormat"in e&&(i=e.colorFormat)),"depth"in e&&(a.depth=e.depth),"stencil"in e&&(a.stencil=e.stencil),"depthStencil"in e&&(a.depthStencil=e.depthStencil)):f=1,o)if(Array.isArray(o))for(e=[],i=0;i<o.length;++i)e[i]=o[i];else e=[o];else for(e=Array(s),o={radius:f,format:i,type:u},i=0;i<s;++i)e[i]=n.createCube(o);for(a.color=Array(e.length),i=0;i<e.length;++i)s=e[i],f=f||s.width,a.color[i]={target:34069,data:e[i]};for(i=0;6>i;++i){for(s=0;s<e.length;++s)a.color[s].target=34069+i;0<i&&(a.depth=r[0].depth,a.stencil=r[0].stencil,a.depthStencil=r[0].depthStencil),r[i]?r[i](a):r[i]=y(a)}return R(t,{width:f,height:f,color:e})}var r=Array(6);return t(e),R(t,{faces:r,resize:function(e){var n=0|e;if(n===t.width)return t;var i=t.color;for(e=0;e<i.length;++e)i[e].resize(n);for(e=0;6>e;++e)r[e].resize(n);return t.width=t.height=n,t},_reglType:"framebufferCube",destroy:function(){r.forEach(function(e){e.destroy()})}})},clear:function(){Y(_).forEach(b)},restore:function(){v.cur=null,v.next=null,v.dirty=!0,Y(_).forEach(function(t){t.framebuffer=e.createFramebuffer(),g(t)})}})}function E(){this.w=this.z=this.y=this.x=this.state=0,this.buffer=null,this.size=0,this.normalized=!1,this.type=5126,this.divisor=this.stride=this.offset=0}function D(e,t,r,n,i,a,f){function o(){this.id=++l,this.attributes=[],this.elements=null,this.ownsElements=!1,this.offset=this.count=0,this.instances=-1,this.primitive=4;var e=t.oes_vertex_array_object;this.vao=e?e.createVertexArrayOES():null,p[this.id]=this,this.buffers=[]}var s=r.maxAttributes,c=Array(s);for(r=0;r<s;++r)c[r]=new E;var l=0,p={},d={Record:E,scope:{},state:c,currentVAO:null,targetVAO:null,restore:t.oes_vertex_array_object?function(){t.oes_vertex_array_object&&Y(p).forEach(function(e){e.refresh()})}:function(){},createVAO:function(e){function t(e){var n;Array.isArray(e)?(n=e,r.elements&&r.ownsElements&&r.elements.destroy(),r.elements=null,r.ownsElements=!1,r.offset=0,r.count=0,r.instances=-1,r.primitive=4):(e.elements?(n=e.elements,r.ownsElements?("function"==typeof n&&"elements"===n._reglType?r.elements.destroy():r.elements(n),r.ownsElements=!1):a.getElements(e.elements)?(r.elements=e.elements,r.ownsElements=!1):(r.elements=a.create(e.elements),r.ownsElements=!0)):(r.elements=null,r.ownsElements=!1),n=e.attributes,r.offset=0,r.count=-1,r.instances=-1,r.primitive=4,r.elements&&(r.count=r.elements._elements.vertCount,r.primitive=r.elements._elements.primType),"offset"in e&&(r.offset=0|e.offset),"count"in e&&(r.count=0|e.count),"instances"in e&&(r.instances=0|e.instances),"primitive"in e&&(r.primitive=re[e.primitive])),e={};var f=r.attributes;f.length=n.length;for(var o=0;o<n.length;++o){var s,c=n[o],l=f[o]=new E,p=c.data||c;if(Array.isArray(p)||G(p)||u(p))r.buffers[o]&&(s=r.buffers[o],G(p)&&s._buffer.byteLength>=p.byteLength?s.subdata(p):(s.destroy(),r.buffers[o]=null)),r.buffers[o]||(s=r.buffers[o]=i.create(c,34962,!1,!0)),l.buffer=i.getBuffer(s),l.size=0|l.buffer.dimension,l.normalized=!1,l.type=l.buffer.dtype,l.offset=0,l.stride=0,l.divisor=0,l.state=1,e[o]=1;else i.getBuffer(c)?(l.buffer=i.getBuffer(c),l.size=0|l.buffer.dimension,l.normalized=!1,l.type=l.buffer.dtype,l.offset=0,l.stride=0,l.divisor=0,l.state=1):i.getBuffer(c.buffer)?(l.buffer=i.getBuffer(c.buffer),l.size=0|(+c.size||l.buffer.dimension),l.normalized=!!c.normalized||!1,l.type="type"in c?K[c.type]:l.buffer.dtype,l.offset=0|(c.offset||0),l.stride=0|(c.stride||0),l.divisor=0|(c.divisor||0),l.state=1):"x"in c&&(l.x=+c.x||0,l.y=+c.y||0,l.z=+c.z||0,l.w=+c.w||0,l.state=2)}for(s=0;s<r.buffers.length;++s)!e[s]&&r.buffers[s]&&(r.buffers[s].destroy(),r.buffers[s]=null);return r.refresh(),t}var r=new o;return n.vaoCount+=1,t.destroy=function(){for(var e=0;e<r.buffers.length;++e)r.buffers[e]&&r.buffers[e].destroy();r.buffers.length=0,r.ownsElements&&(r.elements.destroy(),r.elements=null,r.ownsElements=!1),r.destroy()},t._vao=r,t._reglType="vao",t(e)},getVAO:function(e){return"function"==typeof e&&e._vao?e._vao:null},destroyBuffer:function(t){for(var r=0;r<c.length;++r){var n=c[r];n.buffer===t&&(e.disableVertexAttribArray(r),n.buffer=null)}},setVAO:t.oes_vertex_array_object?function(e){if(e!==d.currentVAO){var r=t.oes_vertex_array_object;e?r.bindVertexArrayOES(e.vao):r.bindVertexArrayOES(null),d.currentVAO=e}}:function(r){if(r!==d.currentVAO){if(r)r.bindAttrs();else{for(var n=t.angle_instanced_arrays,i=0;i<c.length;++i){var a=c[i];a.buffer?(e.enableVertexAttribArray(i),a.buffer.bind(),e.vertexAttribPointer(i,a.size,a.type,a.normalized,a.stride,a.offfset),n&&a.divisor&&n.vertexAttribDivisorANGLE(i,a.divisor)):(e.disableVertexAttribArray(i),e.vertexAttrib4f(i,a.x,a.y,a.z,a.w))}f.elements?e.bindBuffer(34963,f.elements.buffer.buffer):e.bindBuffer(34963,null)}d.currentVAO=r}},clear:t.oes_vertex_array_object?function(){Y(p).forEach(function(e){e.destroy()})}:function(){}};return o.prototype.bindAttrs=function(){for(var r=t.angle_instanced_arrays,n=this.attributes,i=0;i<n.length;++i){var f=n[i];f.buffer?(e.enableVertexAttribArray(i),e.bindBuffer(34962,f.buffer.buffer),e.vertexAttribPointer(i,f.size,f.type,f.normalized,f.stride,f.offset),r&&f.divisor&&r.vertexAttribDivisorANGLE(i,f.divisor)):(e.disableVertexAttribArray(i),e.vertexAttrib4f(i,f.x,f.y,f.z,f.w))}for(r=n.length;r<s;++r)e.disableVertexAttribArray(r);(r=a.getElements(this.elements))?e.bindBuffer(34963,r.buffer.buffer):e.bindBuffer(34963,null)},o.prototype.refresh=function(){var e=t.oes_vertex_array_object;e&&(e.bindVertexArrayOES(this.vao),this.bindAttrs(),d.currentVAO=null,e.bindVertexArrayOES(null))},o.prototype.destroy=function(){if(this.vao){var e=t.oes_vertex_array_object;this===d.currentVAO&&(d.currentVAO=null,e.bindVertexArrayOES(null)),e.deleteVertexArrayOES(this.vao),this.vao=null}this.ownsElements&&(this.elements.destroy(),this.elements=null,this.ownsElements=!1),p[this.id]&&(delete p[this.id],--n.vaoCount)},d}function T(e,t,r,n){function i(e,t,r,n){this.name=e,this.id=t,this.location=r,this.info=n}function a(e,t){for(var r=0;r<e.length;++r)if(e[r].id===t.id)return void(e[r].location=t.location);e.push(t)}function f(r,n,i){if(!(f=(i=35632===r?s:c)[n])){var a=t.str(n),f=e.createShader(r);e.shaderSource(f,a),e.compileShader(f),i[n]=f}return f}function o(e,t){this.id=d++,this.fragId=e,this.vertId=t,this.program=null,this.uniforms=[],this.attributes=[],this.refCount=1,n.profile&&(this.stats={uniformsCount:0,attributesCount:0})}function u(r,o,u){var s;s=f(35632,r.fragId);var c=f(35633,r.vertId);if(o=r.program=e.createProgram(),e.attachShader(o,s),e.attachShader(o,c),u)for(s=0;s<u.length;++s)c=u[s],e.bindAttribLocation(o,c[0],c[1]);e.linkProgram(o),c=e.getProgramParameter(o,35718),n.profile&&(r.stats.uniformsCount=c);var l=r.uniforms;for(s=0;s<c;++s)if(u=e.getActiveUniform(o,s)){if(1<u.size)for(var p=0;p<u.size;++p){var d=u.name.replace("[0]","["+p+"]");a(l,new i(d,t.id(d),e.getUniformLocation(o,d),u))}p=u.name,1<u.size&&(p=p.replace("[0]","")),a(l,new i(p,t.id(p),e.getUniformLocation(o,p),u))}for(c=e.getProgramParameter(o,35721),n.profile&&(r.stats.attributesCount=c),r=r.attributes,s=0;s<c;++s)(u=e.getActiveAttrib(o,s))&&a(r,new i(u.name,t.id(u.name),e.getAttribLocation(o,u.name),u))}var s={},c={},l={},p=[],d=0;return n.profile&&(r.getMaxUniformsCount=function(){var e=0;return p.forEach(function(t){t.stats.uniformsCount>e&&(e=t.stats.uniformsCount)}),e},r.getMaxAttributesCount=function(){var e=0;return p.forEach(function(t){t.stats.attributesCount>e&&(e=t.stats.attributesCount)}),e}),{clear:function(){var t=e.deleteShader.bind(e);Y(s).forEach(t),s={},Y(c).forEach(t),c={},p.forEach(function(t){e.deleteProgram(t.program)}),p.length=0,l={},r.shaderCount=0},program:function(t,n,i,a){var f=l[n];f||(f=l[n]={});var d=f[t];if(d&&(d.refCount++,!a))return d;var h=new o(n,t);return r.shaderCount++,u(h,i,a),d||(f[t]=h),p.push(h),R(h,{destroy:function(){if(h.refCount--,0>=h.refCount){e.deleteProgram(h.program);var t=p.indexOf(h);p.splice(t,1),r.shaderCount--}0>=f[h.vertId].refCount&&(e.deleteShader(c[h.vertId]),delete c[h.vertId],delete l[h.fragId][h.vertId]),Object.keys(l[h.fragId]).length||(e.deleteShader(s[h.fragId]),delete s[h.fragId],delete l[h.fragId])}})},restore:function(){s={},c={};for(var e=0;e<p.length;++e)u(p[e],null,p[e].attributes.map(function(e){return[e.location,e.name]}))},shader:f,frag:-1,vert:-1}}function S(e,t,r,n,i,a,f){function o(i){var a;a=null===t.next?5121:t.next.colorAttachments[0].texture._texture.type;var f=0,o=0,u=n.framebufferWidth,s=n.framebufferHeight,c=null;return G(i)?c=i:i&&(f=0|i.x,o=0|i.y,u=0|(i.width||n.framebufferWidth-f),s=0|(i.height||n.framebufferHeight-o),c=i.data||null),r(),i=u*s*4,c||(5121===a?c=new Uint8Array(i):5126===a&&(c=c||new Float32Array(i))),e.pixelStorei(3333,4),e.readPixels(f,o,u,s,6408,a,c),c}return function(e){return e&&"framebuffer"in e?function(e){var r;return t.setFBO({framebuffer:e.framebuffer},function(){r=o(e)}),r}(e):o(e)}}function j(e){return Array.prototype.slice.call(e)}function C(e){return j(e).join("")}function V(e){return Array.isArray(e)||G(e)||u(e)}function F(e){return e.sort(function(e,t){return"viewport"===e?-1:"viewport"===t?1:e<t?-1:1})}function B(e,t,r,n){this.thisDep=e,this.contextDep=t,this.propDep=r,this.append=n}function z(e){return e&&!(e.thisDep||e.contextDep||e.propDep)}function I(e){return new B(!1,!1,!1,e)}function P(e,t){var r=e.type;if(0===r)return new B(!0,1<=(r=e.data.length),2<=r,t);if(4===r)return new B((r=e.data).thisDep,r.contextDep,r.propDep,t);if(5===r)return new B(!1,!1,!1,t);if(6===r){for(var n=r=!1,i=!1,a=0;a<e.data.length;++a){var f=e.data[a];1===f.type?i=!0:2===f.type?n=!0:3===f.type?r=!0:0===f.type?(r=!0,1<=(f=f.data)&&(n=!0),2<=f&&(i=!0)):4===f.type&&(r=r||f.data.thisDep,n=n||f.data.contextDep,i=i||f.data.propDep)}return new B(r,n,i,t)}return new B(3===r,2===r,1===r,t)}function L(e,t,r,n,i,f,o,u,s,c,l,p,d,h,m){function g(e){return e.replace(".","_")}function y(e,t,r){var n=g(e);fe.push(e),ae[n]=ie[n]=!!r,oe[n]=t}function v(e,t,r){var n=g(e);fe.push(e),Array.isArray(r)?(ie[n]=r.slice(),ae[n]=r.slice()):ie[n]=ae[n]=r,ue[n]=t}function x(){var e=function(){function e(){var e=[],t=[];return R(function(){e.push.apply(e,j(arguments))},{def:function(){var n="v"+r++;return t.push(n),0<arguments.length&&(e.push(n,"="),e.push.apply(e,j(arguments)),e.push(";")),n},toString:function(){return C([0<t.length?"var "+t.join(",")+";":"",C(e)])}})}function t(){function t(e,t){n(e,t,"=",r.def(e,t),";")}var r=e(),n=e(),i=r.toString,a=n.toString;return R(function(){r.apply(r,j(arguments))},{def:r.def,entry:r,exit:n,save:t,set:function(e,n,i){t(e,n),r(e,n,"=",i,";")},toString:function(){return i()+a()}})}var r=0,n=[],i=[],a=e(),f={};return{global:a,link:function(e){for(var t=0;t<i.length;++t)if(i[t]===e)return n[t];return t="g"+r++,n.push(t),i.push(e),t},block:e,proc:function(e,r){function n(){var e="a"+i.length;return i.push(e),e}var i=[];r=r||0;for(var a=0;a<r;++a)n();var o=(a=t()).toString;return f[e]=R(a,{arg:n,toString:function(){return C(["function(",i.join(),"){",o(),"}"])}})},scope:t,cond:function(){var e=C(arguments),r=t(),n=t(),i=r.toString,a=n.toString;return R(r,{then:function(){return r.apply(r,j(arguments)),this},else:function(){return n.apply(n,j(arguments)),this},toString:function(){var t=a();return t&&(t="else{"+t+"}"),C(["if(",e,"){",i(),"}",t])}})},compile:function(){var e=['"use strict";',a,"return {"];Object.keys(f).forEach(function(t){e.push('"',t,'":',f[t].toString(),",")}),e.push("}");var t=C(e).replace(/;/g,";\n").replace(/}/g,"}\n").replace(/{/g,"{\n");return Function.apply(null,n.concat(t)).apply(null,i)}}}(),r=e.link,n=e.global;e.id=le++,e.batchId="0";var i=r(se),a=e.shared={props:"a0"};Object.keys(se).forEach(function(e){a[e]=n.def(i,".",e)});var f=e.next={},o=e.current={};Object.keys(ue).forEach(function(e){Array.isArray(ie[e])&&(f[e]=n.def(a.next,".",e),o[e]=n.def(a.current,".",e))});var u=e.constants={};Object.keys(ce).forEach(function(e){u[e]=n.def(JSON.stringify(ce[e]))}),e.invoke=function(t,n){switch(n.type){case 0:var i=["this",a.context,a.props,e.batchId];return t.def(r(n.data),".call(",i.slice(0,Math.max(n.data.length+1,4)),")");case 1:return t.def(a.props,n.data);case 2:return t.def(a.context,n.data);case 3:return t.def("this",n.data);case 4:return n.data.append(e,t),n.data.ref;case 5:return n.data.toString();case 6:return n.data.map(function(r){return e.invoke(t,r)})}},e.attribCache={};var s={};return e.scopeAttrib=function(e){if((e=t.id(e))in s)return s[e];var n=c.scope[e];return n||(n=c.scope[e]=new Z),s[e]=r(n)},e}function w(e,t){var r=e.static,n=e.dynamic;if("framebuffer"in r){var i=r.framebuffer;return i?(i=u.getFramebuffer(i),I(function(e,t){var r=e.link(i),n=e.shared;return t.set(n.framebuffer,".next",r),n=n.context,t.set(n,".framebufferWidth",r+".width"),t.set(n,".framebufferHeight",r+".height"),r})):I(function(e,t){var r=e.shared;return t.set(r.framebuffer,".next","null"),r=r.context,t.set(r,".framebufferWidth",r+".drawingBufferWidth"),t.set(r,".framebufferHeight",r+".drawingBufferHeight"),"null"})}if("framebuffer"in n){var a=n.framebuffer;return P(a,function(e,t){var r=e.invoke(t,a),n=e.shared,i=n.framebuffer;r=t.def(i,".getFramebuffer(",r,")");return t.set(i,".next",r),n=n.context,t.set(n,".framebufferWidth",r+"?"+r+".width:"+n+".drawingBufferWidth"),t.set(n,".framebufferHeight",r+"?"+r+".height:"+n+".drawingBufferHeight"),r})}return null}function A(e,r,n){function i(e){if(e in a){var r=t.id(a[e]);return(e=I(function(){return r})).id=r,e}if(e in f){var n=f[e];return P(n,function(e,t){var r=e.invoke(t,n);return t.def(e.shared.strings,".id(",r,")")})}return null}var a=e.static,f=e.dynamic,o=i("frag"),u=i("vert"),s=null;return z(o)&&z(u)?(s=l.program(u.id,o.id,null,n),e=I(function(e,t){return e.link(s)})):e=new B(o&&o.thisDep||u&&u.thisDep,o&&o.contextDep||u&&u.contextDep,o&&o.propDep||u&&u.propDep,function(e,t){var r,n,i=e.shared.shader;return r=o?o.append(e,t):t.def(i,".","frag"),n=u?u.append(e,t):t.def(i,".","vert"),t.def(i+".program("+n+","+r+")")}),{frag:o,vert:u,progVar:e,program:s}}function k(e,t){function r(e,t){if(e in n){var r=0|n[e];return t?a.offset=r:a.instances=r,I(function(e,n){return t&&(e.OFFSET=r),r})}if(e in i){var f=i[e];return P(f,function(e,r){var n=e.invoke(r,f);return t&&(e.OFFSET=n),n})}if(t){if(s)return I(function(e,t){return e.OFFSET=0});if(o)return new B(u.thisDep,u.contextDep,u.propDep,function(e,t){return t.def(e.shared.vao+".currentVAO?"+e.shared.vao+".currentVAO.offset:0")})}else if(o)return new B(u.thisDep,u.contextDep,u.propDep,function(e,t){return t.def(e.shared.vao+".currentVAO?"+e.shared.vao+".currentVAO.instances:-1")});return null}var n=e.static,i=e.dynamic,a={},o=!1,u=function(){if("vao"in n){var e=n.vao;return null!==e&&null===c.getVAO(e)&&(e=c.createVAO(e)),o=!0,a.vao=e,I(function(t){var r=c.getVAO(e);return r?t.link(r):"null"})}if("vao"in i){o=!0;var t=i.vao;return P(t,function(e,r){var n=e.invoke(r,t);return r.def(e.shared.vao+".getVAO("+n+")")})}return null}(),s=!1,l=function(){if("elements"in n){var e=n.elements;if(a.elements=e,V(e)){var t=a.elements=f.create(e,!0);e=f.getElements(t);s=!0}else e&&(e=f.getElements(e),s=!0);return(t=I(function(t,r){if(e){var n=t.link(e);return t.ELEMENTS=n}return t.ELEMENTS=null})).value=e,t}if("elements"in i){s=!0;var r=i.elements;return P(r,function(e,t){var n=(i=e.shared).isBufferArgs,i=i.elements,a=e.invoke(t,r),f=t.def("null");n=t.def(n,"(",a,")"),a=e.cond(n).then(f,"=",i,".createStream(",a,");").else(f,"=",i,".getElements(",a,");");return t.entry(a),t.exit(e.cond(n).then(i,".destroyStream(",f,");")),e.ELEMENTS=f})}return o?new B(u.thisDep,u.contextDep,u.propDep,function(e,t){return t.def(e.shared.vao+".currentVAO?"+e.shared.elements+".getElements("+e.shared.vao+".currentVAO.elements):null")}):null}(),p=r("offset",!0),d=function(){if("primitive"in n){var e=n.primitive;return a.primitive=e,I(function(t,r){return re[e]})}if("primitive"in i){var t=i.primitive;return P(t,function(e,r){var n=e.constants.primTypes,i=e.invoke(r,t);return r.def(n,"[",i,"]")})}return s?z(l)?l.value?I(function(e,t){return t.def(e.ELEMENTS,".primType")}):I(function(){return 4}):new B(l.thisDep,l.contextDep,l.propDep,function(e,t){var r=e.ELEMENTS;return t.def(r,"?",r,".primType:",4)}):o?new B(u.thisDep,u.contextDep,u.propDep,function(e,t){return t.def(e.shared.vao+".currentVAO?"+e.shared.vao+".currentVAO.primitive:4")}):null}(),h=function(){if("count"in n){var e=0|n.count;return a.count=e,I(function(){return e})}if("count"in i){var t=i.count;return P(t,function(e,r){return e.invoke(r,t)})}return s?z(l)?l?p?new B(p.thisDep,p.contextDep,p.propDep,function(e,t){return t.def(e.ELEMENTS,".vertCount-",e.OFFSET)}):I(function(e,t){return t.def(e.ELEMENTS,".vertCount")}):I(function(){return-1}):new B(l.thisDep||p.thisDep,l.contextDep||p.contextDep,l.propDep||p.propDep,function(e,t){var r=e.ELEMENTS;return e.OFFSET?t.def(r,"?",r,".vertCount-",e.OFFSET,":-1"):t.def(r,"?",r,".vertCount:-1")}):o?new B(u.thisDep,u.contextDep,u.propDep,function(e,t){return t.def(e.shared.vao,".currentVAO?",e.shared.vao,".currentVAO.count:-1")}):null}(),m=r("instances",!1);return{elements:l,primitive:d,count:h,instances:m,offset:p,vao:u,vaoActive:o,elementsActive:s,static:a}}function _(e,r){var n=e.static,a=e.dynamic,f={};return Object.keys(n).forEach(function(e){var r=n[e],a=t.id(e),o=new Z;if(V(r))o.state=1,o.buffer=i.getBuffer(i.create(r,34962,!1,!0)),o.type=0;else if(s=i.getBuffer(r))o.state=1,o.buffer=s,o.type=0;else if("constant"in r){var u=r.constant;o.buffer="null",o.state=2,"number"==typeof u?o.x=u:we.forEach(function(e,t){t<u.length&&(o[e]=u[t])})}else{var s=V(r.buffer)?i.getBuffer(i.create(r.buffer,34962,!1,!0)):i.getBuffer(r.buffer),c=0|r.offset,l=0|r.stride,p=0|r.size,d=!!r.normalized,h=0;"type"in r&&(h=K[r.type]),r=0|r.divisor,o.buffer=s,o.state=1,o.size=p,o.normalized=d,o.type=h||s.dtype,o.offset=c,o.stride=l,o.divisor=r}f[e]=I(function(e,t){var r=e.attribCache;if(a in r)return r[a];var n={isStream:!1};return Object.keys(o).forEach(function(e){n[e]=o[e]}),o.buffer&&(n.buffer=e.link(o.buffer),n.type=n.type||n.buffer+".dtype"),r[a]=n})}),Object.keys(a).forEach(function(e){var t=a[e];f[e]=P(t,function(e,r){function n(e){r(u[e],"=",i,".",e,"|0;")}var i=e.invoke(r,t),a=e.shared,f=e.constants,o=a.isBufferArgs,u=(a=a.buffer,{isStream:r.def(!1)}),s=new Z;s.state=1,Object.keys(s).forEach(function(e){u[e]=r.def(""+s[e])});var c=u.buffer,l=u.type;return r("if(",o,"(",i,")){",u.isStream,"=true;",c,"=",a,".createStream(",34962,",",i,");",l,"=",c,".dtype;","}else{",c,"=",a,".getBuffer(",i,");","if(",c,"){",l,"=",c,".dtype;",'}else if("constant" in ',i,"){",u.state,"=",2,";","if(typeof "+i+'.constant === "number"){',u[we[0]],"=",i,".constant;",we.slice(1).map(function(e){return u[e]}).join("="),"=0;","}else{",we.map(function(e,t){return u[e]+"="+i+".constant.length>"+t+"?"+i+".constant["+t+"]:0;"}).join(""),"}}else{","if(",o,"(",i,".buffer)){",c,"=",a,".createStream(",34962,",",i,".buffer);","}else{",c,"=",a,".getBuffer(",i,".buffer);","}",l,'="type" in ',i,"?",f.glTypes,"[",i,".type]:",c,".dtype;",u.normalized,"=!!",i,".normalized;"),n("size"),n("offset"),n("stride"),n("divisor"),r("}}"),r.exit("if(",u.isStream,"){",a,".destroyStream(",c,");","}"),u})}),f}function O(e,t,n,i,f){function o(e){var t=s[e];t&&(p[e]=t)}var u=function(e,t){if("string"==typeof(r=e.static).frag&&"string"==typeof r.vert){if(0<Object.keys(t.dynamic).length)return null;var r=t.static,n=Object.keys(r);if(0<n.length&&"number"==typeof r[n[0]]){for(var i=[],a=0;a<n.length;++a)i.push([0|r[n[a]],n[a]]);return i}}return null}(e,t),s=function(e,t,r){function n(e){if(e in i){var r=i[e];e=!0;var n,f,o=0|r.x,u=0|r.y;return"width"in r?n=0|r.width:e=!1,"height"in r?f=0|r.height:e=!1,new B(!e&&t&&t.thisDep,!e&&t&&t.contextDep,!e&&t&&t.propDep,function(e,t){var i=e.shared.context,a=n;"width"in r||(a=t.def(i,".","framebufferWidth","-",o));var s=f;return"height"in r||(s=t.def(i,".","framebufferHeight","-",u)),[o,u,a,s]})}if(e in a){var s=a[e];return e=P(s,function(e,t){var r=e.invoke(t,s),n=e.shared.context,i=t.def(r,".x|0"),a=t.def(r,".y|0");return[i,a,t.def('"width" in ',r,"?",r,".width|0:","(",n,".","framebufferWidth","-",i,")"),r=t.def('"height" in ',r,"?",r,".height|0:","(",n,".","framebufferHeight","-",a,")")]}),t&&(e.thisDep=e.thisDep||t.thisDep,e.contextDep=e.contextDep||t.contextDep,e.propDep=e.propDep||t.propDep),e}return t?new B(t.thisDep,t.contextDep,t.propDep,function(e,t){var r=e.shared.context;return[0,0,t.def(r,".","framebufferWidth"),t.def(r,".","framebufferHeight")]}):null}var i=e.static,a=e.dynamic;if(e=n("viewport")){var f=e;e=new B(e.thisDep,e.contextDep,e.propDep,function(e,t){var r=f.append(e,t),n=e.shared.context;return t.set(n,".viewportWidth",r[2]),t.set(n,".viewportHeight",r[3]),r})}return{viewport:e,scissor_box:n("scissor.box")}}(e,h=w(e)),l=k(e),p=function(e,t){var r=e.static,n=e.dynamic,i={};return fe.forEach(function(e){function t(t,a){if(e in r){var o=t(r[e]);i[f]=I(function(){return o})}else if(e in n){var u=n[e];i[f]=P(u,function(e,t){return a(e,t,e.invoke(t,u))})}}var f=g(e);switch(e){case"cull.enable":case"blend.enable":case"dither":case"stencil.enable":case"depth.enable":case"scissor.enable":case"polygonOffset.enable":case"sample.alpha":case"sample.enable":case"depth.mask":return t(function(e){return e},function(e,t,r){return r});case"depth.func":return t(function(e){return _e[e]},function(e,t,r){return t.def(e.constants.compareFuncs,"[",r,"]")});case"depth.range":return t(function(e){return e},function(e,t,r){return[t.def("+",r,"[0]"),t=t.def("+",r,"[1]")]});case"blend.func":return t(function(e){return[ke["srcRGB"in e?e.srcRGB:e.src],ke["dstRGB"in e?e.dstRGB:e.dst],ke["srcAlpha"in e?e.srcAlpha:e.src],ke["dstAlpha"in e?e.dstAlpha:e.dst]]},function(e,t,r){function n(e,n){return t.def('"',e,n,'" in ',r,"?",r,".",e,n,":",r,".",e)}e=e.constants.blendFuncs;var i=n("src","RGB"),a=n("dst","RGB"),f=(i=t.def(e,"[",i,"]"),t.def(e,"[",n("src","Alpha"),"]"));return[i,a=t.def(e,"[",a,"]"),f,e=t.def(e,"[",n("dst","Alpha"),"]")]});case"blend.equation":return t(function(e){return"string"==typeof e?[$[e],$[e]]:"object"==typeof e?[$[e.rgb],$[e.alpha]]:void 0},function(e,t,r){var n=e.constants.blendEquations,i=t.def(),a=t.def();return(e=e.cond("typeof ",r,'==="string"')).then(i,"=",a,"=",n,"[",r,"];"),e.else(i,"=",n,"[",r,".rgb];",a,"=",n,"[",r,".alpha];"),t(e),[i,a]});case"blend.color":return t(function(e){return a(4,function(t){return+e[t]})},function(e,t,r){return a(4,function(e){return t.def("+",r,"[",e,"]")})});case"stencil.mask":return t(function(e){return 0|e},function(e,t,r){return t.def(r,"|0")});case"stencil.func":return t(function(e){return[_e[e.cmp||"keep"],e.ref||0,"mask"in e?e.mask:-1]},function(e,t,r){return[e=t.def('"cmp" in ',r,"?",e.constants.compareFuncs,"[",r,".cmp]",":",7680),t.def(r,".ref|0"),t=t.def('"mask" in ',r,"?",r,".mask|0:-1")]});case"stencil.opFront":case"stencil.opBack":return t(function(t){return["stencil.opBack"===e?1029:1028,Oe[t.fail||"keep"],Oe[t.zfail||"keep"],Oe[t.zpass||"keep"]]},function(t,r,n){function i(e){return r.def('"',e,'" in ',n,"?",a,"[",n,".",e,"]:",7680)}var a=t.constants.stencilOps;return["stencil.opBack"===e?1029:1028,i("fail"),i("zfail"),i("zpass")]});case"polygonOffset.offset":return t(function(e){return[0|e.factor,0|e.units]},function(e,t,r){return[t.def(r,".factor|0"),t=t.def(r,".units|0")]});case"cull.face":return t(function(e){var t=0;return"front"===e?t=1028:"back"===e&&(t=1029),t},function(e,t,r){return t.def(r,'==="front"?',1028,":",1029)});case"lineWidth":return t(function(e){return e},function(e,t,r){return r});case"frontFace":return t(function(e){return Ee[e]},function(e,t,r){return t.def(r+'==="cw"?2304:2305')});case"colorMask":return t(function(e){return e.map(function(e){return!!e})},function(e,t,r){return a(4,function(e){return"!!"+r+"["+e+"]"})});case"sample.coverage":return t(function(e){return["value"in e?e.value:1,!!e.invert]},function(e,t,r){return[t.def('"value" in ',r,"?+",r,".value:1"),t=t.def("!!",r,".invert")]})}}),i}(e),d=A(e,0,u);o("viewport"),o(g("scissor.box"));var h,m=0<Object.keys(p).length;if((h={framebuffer:h,draw:l,shader:d,state:p,dirty:m,scopeVAO:null,drawVAO:null,useVAO:!1,attributes:{}}).profile=function(e){var t,r=e.static;if(e=e.dynamic,"profile"in r){var n=!!r.profile;(t=I(function(e,t){return n})).enable=n}else if("profile"in e){var i=e.profile;t=P(i,function(e,t){return e.invoke(t,i)})}return t}(e),h.uniforms=function(e,t){var r=e.static,n=e.dynamic,i={};return Object.keys(r).forEach(function(e){var t,n=r[e];if("number"==typeof n||"boolean"==typeof n)t=I(function(){return n});else if("function"==typeof n){var f=n._reglType;"texture2d"===f||"textureCube"===f?t=I(function(e){return e.link(n)}):"framebuffer"!==f&&"framebufferCube"!==f||(t=I(function(e){return e.link(n.color[0])}))}else b(n)&&(t=I(function(e){return e.global.def("[",a(n.length,function(e){return n[e]}),"]")}));t.value=n,i[e]=t}),Object.keys(n).forEach(function(e){var t=n[e];i[e]=P(t,function(e,r){return e.invoke(r,t)})}),i}(n),h.drawVAO=h.scopeVAO=l.vao,!h.drawVAO&&d.program&&!u&&r.angle_instanced_arrays&&l.static.elements){var y=!0;if(e=d.program.attributes.map(function(e){return e=t.static[e],y=y&&!!e,e}),y&&0<e.length){var v=c.getVAO(c.createVAO({attributes:e,elements:l.static.elements}));h.drawVAO=new B(null,null,null,function(e,t){return e.link(v)}),h.useVAO=!0}}return u?h.useVAO=!0:h.attributes=_(t),h.context=function(e){var t=e.static,r=e.dynamic,n={};return Object.keys(t).forEach(function(e){var r=t[e];n[e]=I(function(e,t){return"number"==typeof r||"boolean"==typeof r?""+r:e.link(r)})}),Object.keys(r).forEach(function(e){var t=r[e];n[e]=P(t,function(e,r){return e.invoke(r,t)})}),n}(i),h}function E(e,t,r){var n=e.shared.context,i=e.scope();Object.keys(r).forEach(function(a){t.save(n,"."+a);var f=r[a].append(e,t);Array.isArray(f)?i(n,".",a,"=[",f.join(),"];"):i(n,".",a,"=",f,";")}),t(i)}function D(e,t,r,n){var i,a=(o=e.shared).gl,f=o.framebuffer;te&&(i=t.def(o.extensions,".webgl_draw_buffers"));var o=(u=e.constants).drawBuffer,u=u.backBuffer;e=r?r.append(e,t):t.def(f,".next"),n||t("if(",e,"!==",f,".cur){"),t("if(",e,"){",a,".bindFramebuffer(",36160,",",e,".framebuffer);"),te&&t(i,".drawBuffersWEBGL(",o,"[",e,".colorAttachments.length]);"),t("}else{",a,".bindFramebuffer(",36160,",null);"),te&&t(i,".drawBuffersWEBGL(",u,");"),t("}",f,".cur=",e,";"),n||t("}")}function T(e,t,r){var n=e.shared,i=n.gl,f=e.current,o=e.next,u=n.current,s=n.next,c=e.cond(u,".dirty");fe.forEach(function(t){var n,l;if(!((t=g(t))in r.state))if(t in o){n=o[t],l=f[t];var p=a(ie[t].length,function(e){return c.def(n,"[",e,"]")});c(e.cond(p.map(function(e,t){return e+"!=="+l+"["+t+"]"}).join("||")).then(i,".",ue[t],"(",p,");",p.map(function(e,t){return l+"["+t+"]="+e}).join(";"),";"))}else n=c.def(s,".",t),p=e.cond(n,"!==",u,".",t),c(p),t in oe?p(e.cond(n).then(i,".enable(",oe[t],");").else(i,".disable(",oe[t],");"),u,".",t,"=",n,";"):p(i,".",ue[t],"(",n,");",u,".",t,"=",n,";")}),0===Object.keys(r.state).length&&c(u,".dirty=false;"),t(c)}function S(e,t,r,n){var i=e.shared,a=e.current,f=i.current,o=i.gl;F(Object.keys(r)).forEach(function(i){var u=r[i];if(!n||n(u)){var s=u.append(e,t);if(oe[i]){var c=oe[i];z(u)?t(o,s?".enable(":".disable(",c,");"):t(e.cond(s).then(o,".enable(",c,");").else(o,".disable(",c,");")),t(f,".",i,"=",s,";")}else if(b(s)){var l=a[i];t(o,".",ue[i],"(",s,");",s.map(function(e,t){return l+"["+t+"]="+e}).join(";"),";")}else t(o,".",ue[i],"(",s,");",f,".",i,"=",s,";")}})}function L(e,t){ee&&(e.instancing=t.def(e.shared.extensions,".angle_instanced_arrays"))}function M(e,t,r,n,i){function a(){return"undefined"==typeof performance?"Date.now()":"performance.now()"}function f(e){e(s=t.def(),"=",a(),";"),"string"==typeof i?e(p,".count+=",i,";"):e(p,".count++;"),h&&(n?e(c=t.def(),"=",m,".getNumPendingQueries();"):e(m,".beginQuery(",p,");"))}function o(e){e(p,".cpuTime+=",a(),"-",s,";"),h&&(n?e(m,".pushScopeStats(",c,",",m,".getNumPendingQueries(),",p,");"):e(m,".endQuery();"))}function u(e){var r=t.def(d,".profile");t(d,".profile=",e,";"),t.exit(d,".profile=",r,";")}var s,c,l=e.shared,p=e.stats,d=l.current,m=l.timer;if(r=r.profile){if(z(r))return void(r.enable?(f(t),o(t.exit),u("true")):u("false"));u(r=r.append(e,t))}else r=t.def(d,".profile");f(l=e.block()),t("if(",r,"){",l,"}"),o(e=e.block()),t.exit("if(",r,"){",e,"}")}function H(e,t,r,n,i){function a(r,n,i){function a(){t("if(!",c,".buffer){",u,".enableVertexAttribArray(",s,");}");var r,a=i.type;r=i.size?t.def(i.size,"||",n):n,t("if(",c,".type!==",a,"||",c,".size!==",r,"||",d.map(function(e){return c+"."+e+"!=="+i[e]}).join("||"),"){",u,".bindBuffer(",34962,",",l,".buffer);",u,".vertexAttribPointer(",[s,r,a,i.normalized,i.stride,i.offset],");",c,".type=",a,";",c,".size=",r,";",d.map(function(e){return c+"."+e+"="+i[e]+";"}).join(""),"}"),ee&&(a=i.divisor,t("if(",c,".divisor!==",a,"){",e.instancing,".vertexAttribDivisorANGLE(",[s,a],");",c,".divisor=",a,";}"))}function o(){t("if(",c,".buffer){",u,".disableVertexAttribArray(",s,");",c,".buffer=null;","}if(",we.map(function(e,t){return c+"."+e+"!=="+p[t]}).join("||"),"){",u,".vertexAttrib4f(",s,",",p,");",we.map(function(e,t){return c+"."+e+"="+p[t]+";"}).join(""),"}")}var u=f.gl,s=t.def(r,".location"),c=t.def(f.attributes,"[",s,"]");r=i.state;var l=i.buffer,p=[i.x,i.y,i.z,i.w],d=["buffer","normalized","offset","stride"];1===r?a():2===r?o():(t("if(",r,"===",1,"){"),a(),t("}else{"),o(),t("}"))}var f=e.shared;n.forEach(function(n){var f,o=n.name,u=r.attributes[o];if(u){if(!i(u))return;f=u.append(e,t)}else{if(!i(De))return;var s=e.scopeAttrib(o);f={},Object.keys(new Z).forEach(function(e){f[e]=t.def(s,".",e)})}a(e.link(n),function(e){switch(e){case 35664:case 35667:case 35671:return 2;case 35665:case 35668:case 35672:return 3;case 35666:case 35669:case 35673:return 4;default:return 1}}(n.info.type),f)})}function U(e,r,n,i,f,o){for(var u,s=e.shared,c=s.gl,l={},p=0;p<i.length;++p){var d=(x=i[p]).name,h=x.info.type,m=x.info.size,g=n.uniforms[d];if(1<m){if(!g)continue;var y=d.replace("[0]","");if(l[y])continue;l[y]=1}var v,x=e.link(x)+".location";if(g){if(!f(g))continue;if(z(g)){if(d=g.value,35678===h||35680===h)r(c,".uniform1i(",x,",",(h=e.link(d._texture||d.color[0]._texture))+".bind());"),r.exit(h,".unbind();");else if(35674===h||35675===h||35676===h)m=e.global.def("new Float32Array(["+Array.prototype.slice.call(d)+"])"),d=2,35675===h?d=3:35676===h&&(d=4),r(c,".uniformMatrix",d,"fv(",x,",false,",m,");");else{switch(h){case 5126:u="1f";break;case 35664:u="2f";break;case 35665:u="3f";break;case 35666:u="4f";break;case 35670:case 5124:u="1i";break;case 35671:case 35667:u="2i";break;case 35672:case 35668:u="3i";break;case 35673:u="4i";break;case 35669:u="4i"}1<m?(u+="v",d=e.global.def("["+Array.prototype.slice.call(d)+"]")):d=b(d)?Array.prototype.slice.call(d):d,r(c,".uniform",u,"(",x,",",d,");")}continue}v=g.append(e,r)}else{if(!f(De))continue;v=r.def(s.uniforms,"[",t.id(d),"]")}switch(35678===h?r("if(",v,"&&",v,'._reglType==="framebuffer"){',v,"=",v,".color[0];","}"):35680===h&&r("if(",v,"&&",v,'._reglType==="framebufferCube"){',v,"=",v,".color[0];","}"),d=1,h){case 35678:case 35680:h=r.def(v,"._texture"),r(c,".uniform1i(",x,",",h,".bind());"),r.exit(h,".unbind();");continue;case 5124:case 35670:u="1i";break;case 35667:case 35671:u="2i",d=2;break;case 35668:case 35672:u="3i",d=3;break;case 35669:case 35673:u="4i",d=4;break;case 5126:u="1f";break;case 35664:u="2f",d=2;break;case 35665:u="3f",d=3;break;case 35666:u="4f",d=4;break;case 35674:u="Matrix2fv";break;case 35675:u="Matrix3fv";break;case 35676:u="Matrix4fv"}if(-1===u.indexOf("Matrix")&&1<m&&(u+="v",d=1),"M"===u.charAt(0)){r(c,".uniform",u,"(",x,",");x=Math.pow(h-35674+2,2);var w=e.global.def("new Float32Array(",x,")");Array.isArray(v)?r("false,(",a(x,function(e){return w+"["+e+"]="+v[e]}),",",w,")"):r("false,(Array.isArray(",v,")||",v," instanceof Float32Array)?",v,":(",a(x,function(e){return w+"["+e+"]="+v+"["+e+"]"}),",",w,")"),r(");")}else{if(1<d){h=[];var A=[];for(m=0;m<d;++m)Array.isArray(v)?A.push(v[m]):A.push(r.def(v+"["+m+"]")),o&&h.push(r.def());o&&r("if(!",e.batchId,"||",h.map(function(e,t){return e+"!=="+A[t]}).join("||"),"){",h.map(function(e,t){return e+"="+A[t]+";"}).join("")),r(c,".uniform",u,"(",x,",",A.join(","),");")}else o&&(h=r.def(),r("if(!",e.batchId,"||",h,"!==",v,"){",h,"=",v,";")),r(c,".uniform",u,"(",x,",",v,");");o&&r("}")}}}function N(e,t,r,n){function i(i){var a=p[i];return a?a.contextDep&&n.contextDynamic||a.propDep?a.append(e,r):a.append(e,t):t.def(l,".",i)}function a(){function e(){r(u,".drawElementsInstancedANGLE(",[h,b,g,m+"<<(("+g+"-5121)>>1)",o],");")}function t(){r(u,".drawArraysInstancedANGLE(",[h,m,b,o],");")}d&&"null"!==d?y?e():(r("if(",d,"){"),e(),r("}else{"),t(),r("}")):t()}function f(){function e(){r(c+".drawElements("+[h,b,g,m+"<<(("+g+"-5121)>>1)"]+");")}function t(){r(c+".drawArrays("+[h,m,b]+");")}d&&"null"!==d?y?e():(r("if(",d,"){"),e(),r("}else{"),t(),r("}")):t()}var o,u,s=e.shared,c=s.gl,l=s.draw,p=n.draw,d=function(){var i=p.elements,a=t;return i?((i.contextDep&&n.contextDynamic||i.propDep)&&(a=r),i=i.append(e,a),p.elementsActive&&a("if("+i+")"+c+".bindBuffer(34963,"+i+".buffer.buffer);")):(i=a.def(),a(i,"=",l,".","elements",";","if(",i,"){",c,".bindBuffer(",34963,",",i,".buffer.buffer);}","else if(",s.vao,".currentVAO){",i,"=",e.shared.elements+".getElements("+s.vao,".currentVAO.elements);",ne?"":"if("+i+")"+c+".bindBuffer(34963,"+i+".buffer.buffer);","}")),i}(),h=i("primitive"),m=i("offset"),b=function(){var i=p.count,a=t;return i?((i.contextDep&&n.contextDynamic||i.propDep)&&(a=r),i=i.append(e,a)):i=a.def(l,".","count"),i}();if("number"==typeof b){if(0===b)return}else r("if(",b,"){"),r.exit("}");ee&&(o=i("instances"),u=e.instancing);var g=d+".type",y=p.elements&&z(p.elements)&&!p.vaoActive;ee&&("number"!=typeof o||0<=o)?"string"==typeof o?(r("if(",o,">0){"),a(),r("}else if(",o,"<0){"),f(),r("}")):a():f()}function q(e,t,r,n,i){return i=(t=x()).proc("body",i),ee&&(t.instancing=i.def(t.shared.extensions,".angle_instanced_arrays")),e(t,i,r,n),t.compile().body}function Q(e,t,r,n){L(e,t),r.useVAO?r.drawVAO?t(e.shared.vao,".setVAO(",r.drawVAO.append(e,t),");"):t(e.shared.vao,".setVAO(",e.shared.vao,".targetVAO);"):(t(e.shared.vao,".setVAO(null);"),H(e,t,r,n.attributes,function(){return!0})),U(e,t,r,n.uniforms,function(){return!0},!1),N(e,t,t,r)}function G(e,t,r,n){function i(){return!0}e.batchId="a1",L(e,t),H(e,t,r,n.attributes,i),U(e,t,r,n.uniforms,i,!1),N(e,t,t,r)}function Y(e,t,r,n){function i(e){return e.contextDep&&f||e.propDep}function a(e){return!i(e)}L(e,t);var f=r.contextDep,o=t.def(),u=t.def();e.shared.props=u,e.batchId=o;var s=e.scope(),c=e.scope();t(s.entry,"for(",o,"=0;",o,"<","a1",";++",o,"){",u,"=","a0","[",o,"];",c,"}",s.exit),r.needsContext&&E(e,c,r.context),r.needsFramebuffer&&D(e,c,r.framebuffer),S(e,c,r.state,i),r.profile&&i(r.profile)&&M(e,c,r,!1,!0),n?(r.useVAO?r.drawVAO?i(r.drawVAO)?c(e.shared.vao,".setVAO(",r.drawVAO.append(e,c),");"):s(e.shared.vao,".setVAO(",r.drawVAO.append(e,s),");"):s(e.shared.vao,".setVAO(",e.shared.vao,".targetVAO);"):(s(e.shared.vao,".setVAO(null);"),H(e,s,r,n.attributes,a),H(e,c,r,n.attributes,i)),U(e,s,r,n.uniforms,a,!1),U(e,c,r,n.uniforms,i,!0),N(e,s,c,r)):(t=e.global.def("{}"),n=r.shader.progVar.append(e,c),u=c.def(n,".id"),s=c.def(t,"[",u,"]"),c(e.shared.gl,".useProgram(",n,".program);","if(!",s,"){",s,"=",t,"[",u,"]=",e.link(function(t){return q(G,e,r,t,2)}),"(",n,");}",s,".call(this,a0[",o,"],",o,");"))}function X(e,r){function n(t){var n=r.shader[t];n&&i.set(a.shader,"."+t,n.append(e,i))}var i=e.proc("scope",3);e.batchId="a2";var a=e.shared,f=a.current;E(e,i,r.context),r.framebuffer&&r.framebuffer.append(e,i),F(Object.keys(r.state)).forEach(function(t){var n=r.state[t].append(e,i);b(n)?n.forEach(function(r,n){i.set(e.next[t],"["+n+"]",r)}):i.set(a.next,"."+t,n)}),M(e,i,r,!0,!0),["elements","offset","count","instances","primitive"].forEach(function(t){var n=r.draw[t];n&&i.set(a.draw,"."+t,""+n.append(e,i))}),Object.keys(r.uniforms).forEach(function(n){var f=r.uniforms[n].append(e,i);Array.isArray(f)&&(f="["+f.join()+"]"),i.set(a.uniforms,"["+t.id(n)+"]",f)}),Object.keys(r.attributes).forEach(function(t){var n=r.attributes[t].append(e,i),a=e.scopeAttrib(t);Object.keys(new Z).forEach(function(e){i.set(a,"."+e,n[e])})}),r.scopeVAO&&i.set(a.vao,".targetVAO",r.scopeVAO.append(e,i)),n("vert"),n("frag"),0<Object.keys(r.state).length&&(i(f,".dirty=true;"),i.exit(f,".dirty=true;")),i("a1(",e.shared.context,",a0,",e.batchId,");")}function J(e,t,r){var n=t.static[r];if(n&&function(e){if("object"==typeof e&&!b(e)){for(var t=Object.keys(e),r=0;r<t.length;++r)if(W.isDynamic(e[t[r]]))return!0;return!1}}(n)){var i=e.global,a=Object.keys(n),f=!1,o=!1,u=!1,s=e.global.def("{}");a.forEach(function(t){var r=n[t];if(W.isDynamic(r))"function"==typeof r&&(r=n[t]=W.unbox(r)),t=P(r,null),f=f||t.thisDep,u=u||t.propDep,o=o||t.contextDep;else{switch(i(s,".",t,"="),typeof r){case"number":i(r);break;case"string":i('"',r,'"');break;case"object":Array.isArray(r)&&i("[",r.join(),"]");break;default:i(e.link(r))}i(";")}}),t.dynamic[r]=new W.DynamicVariable(4,{thisDep:f,contextDep:o,propDep:u,ref:s,append:function(e,t){a.forEach(function(r){var i=n[r];W.isDynamic(i)&&(i=e.invoke(t,i),t(s,".",r,"=",i,";"))})}}),delete t.static[r]}}var Z=c.Record,$={add:32774,subtract:32778,"reverse subtract":32779};r.ext_blend_minmax&&($.min=32775,$.max=32776);var ee=r.angle_instanced_arrays,te=r.webgl_draw_buffers,ne=r.oes_vertex_array_object,ie={dirty:!0,profile:m.profile},ae={},fe=[],oe={},ue={};y("dither",3024),y("blend.enable",3042),v("blend.color","blendColor",[0,0,0,0]),v("blend.equation","blendEquationSeparate",[32774,32774]),v("blend.func","blendFuncSeparate",[1,0,1,0]),y("depth.enable",2929,!0),v("depth.func","depthFunc",513),v("depth.range","depthRange",[0,1]),v("depth.mask","depthMask",!0),v("colorMask","colorMask",[!0,!0,!0,!0]),y("cull.enable",2884),v("cull.face","cullFace",1029),v("frontFace","frontFace",2305),v("lineWidth","lineWidth",1),y("polygonOffset.enable",32823),v("polygonOffset.offset","polygonOffset",[0,0]),y("sample.alpha",32926),y("sample.enable",32928),v("sample.coverage","sampleCoverage",[1,!1]),y("stencil.enable",2960),v("stencil.mask","stencilMask",-1),v("stencil.func","stencilFunc",[519,0,-1]),v("stencil.opFront","stencilOpSeparate",[1028,7680,7680,7680]),v("stencil.opBack","stencilOpSeparate",[1029,7680,7680,7680]),y("scissor.enable",3089),v("scissor.box","scissor",[0,0,e.drawingBufferWidth,e.drawingBufferHeight]),v("viewport","viewport",[0,0,e.drawingBufferWidth,e.drawingBufferHeight]);var se={gl:e,context:d,strings:t,next:ae,current:ie,draw:p,elements:f,buffer:i,shader:l,attributes:c.state,vao:c,uniforms:s,framebuffer:u,extensions:r,timer:h,isBufferArgs:V},ce={primTypes:re,compareFuncs:_e,blendFuncs:ke,blendEquations:$,stencilOps:Oe,glTypes:K,orientationType:Ee};te&&(ce.backBuffer=[1029],ce.drawBuffer=a(n.maxDrawbuffers,function(e){return 0===e?[0]:a(e,function(e){return 36064+e})}));var le=0;return{next:ae,current:ie,procs:function(){var e=x(),t=e.proc("poll"),i=e.proc("refresh"),f=e.block();t(f),i(f);var o,u=e.shared,s=u.gl,c=u.next,l=u.current;f(l,".dirty=false;"),D(e,t),D(e,i,null,!0),ee&&(o=e.link(ee)),r.oes_vertex_array_object&&i(e.link(r.oes_vertex_array_object),".bindVertexArrayOES(null);");for(var p=0;p<n.maxAttributes;++p){var d=i.def(u.attributes,"[",p,"]"),h=e.cond(d,".buffer");h.then(s,".enableVertexAttribArray(",p,");",s,".bindBuffer(",34962,",",d,".buffer.buffer);",s,".vertexAttribPointer(",p,",",d,".size,",d,".type,",d,".normalized,",d,".stride,",d,".offset);").else(s,".disableVertexAttribArray(",p,");",s,".vertexAttrib4f(",p,",",d,".x,",d,".y,",d,".z,",d,".w);",d,".buffer=null;"),i(h),ee&&i(o,".vertexAttribDivisorANGLE(",p,",",d,".divisor);")}return i(e.shared.vao,".currentVAO=null;",e.shared.vao,".setVAO(",e.shared.vao,".targetVAO);"),Object.keys(oe).forEach(function(r){var n=oe[r],a=f.def(c,".",r),o=e.block();o("if(",a,"){",s,".enable(",n,")}else{",s,".disable(",n,")}",l,".",r,"=",a,";"),i(o),t("if(",a,"!==",l,".",r,"){",o,"}")}),Object.keys(ue).forEach(function(r){var n,o,u=ue[r],p=ie[r],d=e.block();d(s,".",u,"("),b(p)?(u=p.length,n=e.global.def(c,".",r),o=e.global.def(l,".",r),d(a(u,function(e){return n+"["+e+"]"}),");",a(u,function(e){return o+"["+e+"]="+n+"["+e+"];"}).join("")),t("if(",a(u,function(e){return n+"["+e+"]!=="+o+"["+e+"]"}).join("||"),"){",d,"}")):(n=f.def(c,".",r),o=f.def(l,".",r),d(n,");",l,".",r,"=",n,";"),t("if(",n,"!==",o,"){",d,"}")),i(d)}),e.compile()}(),compile:function(e,t,r,n,i){var a=x();a.stats=a.link(i),Object.keys(t.static).forEach(function(e){J(a,t,e)}),Ae.forEach(function(t){J(a,e,t)});var f=O(e,t,r,n);return function(e,t){var r=e.proc("draw",1);L(e,r),E(e,r,t.context),D(e,r,t.framebuffer),T(e,r,t),S(e,r,t.state),M(e,r,t,!1,!0);var n=t.shader.progVar.append(e,r);if(r(e.shared.gl,".useProgram(",n,".program);"),t.shader.program)Q(e,r,t,t.shader.program);else{r(e.shared.vao,".setVAO(null);");var i=e.global.def("{}"),a=r.def(n,".id"),f=r.def(i,"[",a,"]");r(e.cond(f).then(f,".call(this,a0);").else(f,"=",i,"[",a,"]=",e.link(function(r){return q(Q,e,t,r,1)}),"(",n,");",f,".call(this,a0);"))}0<Object.keys(t.state).length&&r(e.shared.current,".dirty=true;"),e.shared.vao&&r(e.shared.vao,".setVAO(null);")}(a,f),X(a,f),function(e,t){function r(e){return e.contextDep&&i||e.propDep}var n=e.proc("batch",2);e.batchId="0",L(e,n);var i=!1,a=!0;Object.keys(t.context).forEach(function(e){i=i||t.context[e].propDep}),i||(E(e,n,t.context),a=!1);var f=!1;if((o=t.framebuffer)?(o.propDep?i=f=!0:o.contextDep&&i&&(f=!0),f||D(e,n,o)):D(e,n,null),t.state.viewport&&t.state.viewport.propDep&&(i=!0),T(e,n,t),S(e,n,t.state,function(e){return!r(e)}),t.profile&&r(t.profile)||M(e,n,t,!1,"a1"),t.contextDep=i,t.needsContext=a,t.needsFramebuffer=f,(a=t.shader.progVar).contextDep&&i||a.propDep)Y(e,n,t,null);else if(a=a.append(e,n),n(e.shared.gl,".useProgram(",a,".program);"),t.shader.program)Y(e,n,t,t.shader.program);else{n(e.shared.vao,".setVAO(null);");var o=e.global.def("{}"),u=(f=n.def(a,".id"),n.def(o,"[",f,"]"));n(e.cond(u).then(u,".call(this,a0,a1);").else(u,"=",o,"[",f,"]=",e.link(function(r){return q(Y,e,t,r,2)}),"(",a,");",u,".call(this,a0,a1);"))}0<Object.keys(t.state).length&&n(e.shared.current,".dirty=true;"),e.shared.vao&&n(e.shared.vao,".setVAO(null);")}(a,f),R(a.compile(),{destroy:function(){f.shader.program.destroy()}})}}}function M(e,t){for(var r=0;r<e.length;++r)if(e[r]===t)return r;return-1}var R=function(e,t){for(var r=Object.keys(t),n=0;n<r.length;++n)e[r[n]]=t[r[n]];return e},H=0,W={DynamicVariable:e,define:function(r,n){return new e(r,t(n+""))},isDynamic:function(t){return"function"==typeof t&&!t._reglType||t instanceof e},unbox:function t(r,n){return"function"==typeof r?new e(0,r):"number"==typeof r||"boolean"==typeof r?new e(5,r):Array.isArray(r)?new e(6,r.map(function(e,r){return t(e,n+"["+r+"]")})):r instanceof e?r:void 0},accessor:t},U={next:"function"==typeof requestAnimationFrame?function(e){return requestAnimationFrame(e)}:function(e){return setTimeout(e,16)},cancel:"function"==typeof cancelAnimationFrame?function(e){return cancelAnimationFrame(e)}:clearTimeout},N="undefined"!=typeof performance&&performance.now?function(){return performance.now()}:function(){return+new Date},q=o();q.zero=o();var Q=function(e,t){var r=1;t.ext_texture_filter_anisotropic&&(r=e.getParameter(34047));var n=1,i=1;t.webgl_draw_buffers&&(n=e.getParameter(34852),i=e.getParameter(36063));var a=!!t.oes_texture_float;if(a){a=e.createTexture(),e.bindTexture(3553,a),e.texImage2D(3553,0,6408,1,1,0,6408,5126,null);var f=e.createFramebuffer();if(e.bindFramebuffer(36160,f),e.framebufferTexture2D(36160,36064,3553,a,0),e.bindTexture(3553,null),36053!==e.checkFramebufferStatus(36160))a=!1;else{e.viewport(0,0,1,1),e.clearColor(1,0,0,1),e.clear(16384);var o=q.allocType(5126,4);e.readPixels(0,0,1,1,6408,5126,o),e.getError()?a=!1:(e.deleteFramebuffer(f),e.deleteTexture(a),a=1===o[0]),q.freeType(o)}}return o=!0,"undefined"!=typeof navigator&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)||/Edge/.test(navigator.userAgent))||(o=e.createTexture(),f=q.allocType(5121,36),e.activeTexture(33984),e.bindTexture(34067,o),e.texImage2D(34069,0,6408,3,3,0,6408,5121,f),q.freeType(f),e.bindTexture(34067,null),e.deleteTexture(o),o=!e.getError()),{colorBits:[e.getParameter(3410),e.getParameter(3411),e.getParameter(3412),e.getParameter(3413)],depthBits:e.getParameter(3414),stencilBits:e.getParameter(3415),subpixelBits:e.getParameter(3408),extensions:Object.keys(t).filter(function(e){return!!t[e]}),maxAnisotropic:r,maxDrawbuffers:n,maxColorAttachments:i,pointSizeDims:e.getParameter(33901),lineWidthDims:e.getParameter(33902),maxViewportDims:e.getParameter(3386),maxCombinedTextureUnits:e.getParameter(35661),maxCubeMapSize:e.getParameter(34076),maxRenderbufferSize:e.getParameter(34024),maxTextureUnits:e.getParameter(34930),maxTextureSize:e.getParameter(3379),maxAttributes:e.getParameter(34921),maxVertexUniforms:e.getParameter(36347),maxVertexTextureUnits:e.getParameter(35660),maxVaryingVectors:e.getParameter(36348),maxFragmentUniforms:e.getParameter(36349),glsl:e.getParameter(35724),renderer:e.getParameter(7937),vendor:e.getParameter(7936),version:e.getParameter(7938),readFloat:a,npotTextureCube:o}},G=function(e){return e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Uint32Array||e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array||e instanceof Uint8ClampedArray},Y=function(e){return Object.keys(e).map(function(t){return e[t]})},X={shape:function(e){for(var t=[];e.length;e=e[0])t.push(e.length);return t},flatten:function(e,t,r,n){var i=1;if(t.length)for(var a=0;a<t.length;++a)i*=t[a];else i=0;switch(r=n||q.allocType(r,i),t.length){case 0:break;case 1:for(n=t[0],t=0;t<n;++t)r[t]=e[t];break;case 2:for(n=t[0],t=t[1],a=i=0;a<n;++a)for(var f=e[a],o=0;o<t;++o)r[i++]=f[o];break;case 3:s(e,t[0],t[1],t[2],r,0);break;default:!function e(t,r,n,i,a){for(var f=1,o=n+1;o<r.length;++o)f*=r[o];var u=r[n];if(4==r.length-n){var c=r[n+1],l=r[n+2];for(r=r[n+3],o=0;o<u;++o)s(t[o],c,l,r,i,a),a+=f}else for(o=0;o<u;++o)e(t[o],r,n+1,i,a),a+=f}(e,t,0,r,0)}return r}},J={"[object Int8Array]":5120,"[object Int16Array]":5122,"[object Int32Array]":5124,"[object Uint8Array]":5121,"[object Uint8ClampedArray]":5121,"[object Uint16Array]":5123,"[object Uint32Array]":5125,"[object Float32Array]":5126,"[object Float64Array]":5121,"[object ArrayBuffer]":5121},K={int8:5120,int16:5122,int32:5124,uint8:5121,uint16:5123,uint32:5125,float:5126,float32:5126},Z={dynamic:35048,stream:35040,static:35044},$=X.flatten,ee=X.shape,te=[];te[5120]=1,te[5122]=2,te[5124]=4,te[5121]=1,te[5123]=2,te[5125]=4,te[5126]=4;var re={points:0,point:0,lines:1,line:1,triangles:4,triangle:4,"line loop":2,"line strip":3,"triangle strip":5,"triangle fan":6},ne=new Float32Array(1),ie=new Uint32Array(ne.buffer),ae=[9984,9986,9985,9987],fe=[0,6409,6410,6407,6408],oe={};oe[6409]=oe[6406]=oe[6402]=1,oe[34041]=oe[6410]=2,oe[6407]=oe[35904]=3,oe[6408]=oe[35906]=4;var ue=g("HTMLCanvasElement"),se=g("OffscreenCanvas"),ce=g("CanvasRenderingContext2D"),le=g("ImageBitmap"),pe=g("HTMLImageElement"),de=g("HTMLVideoElement"),he=Object.keys(J).concat([ue,se,ce,le,pe,de]),me=[];me[5121]=1,me[5126]=4,me[36193]=2,me[5123]=2,me[5125]=4;var be=[];be[32854]=2,be[32855]=2,be[36194]=2,be[34041]=4,be[33776]=.5,be[33777]=.5,be[33778]=1,be[33779]=1,be[35986]=.5,be[35987]=1,be[34798]=1,be[35840]=.5,be[35841]=.25,be[35842]=.5,be[35843]=.25,be[36196]=.5;var ge=[];ge[32854]=2,ge[32855]=2,ge[36194]=2,ge[33189]=2,ge[36168]=1,ge[34041]=4,ge[35907]=4,ge[34836]=16,ge[34842]=8,ge[34843]=6;var ye=function(e,t,r,n,i){function a(e){this.id=s++,this.refCount=1,this.renderbuffer=e,this.format=32854,this.height=this.width=0,i.profile&&(this.stats={size:0})}function f(t){var r=t.renderbuffer;e.bindRenderbuffer(36161,null),e.deleteRenderbuffer(r),t.renderbuffer=null,t.refCount=0,delete c[t.id],n.renderbufferCount--}var o={rgba4:32854,rgb565:36194,"rgb5 a1":32855,depth:33189,stencil:36168,"depth stencil":34041};t.ext_srgb&&(o.srgba=35907),t.ext_color_buffer_half_float&&(o.rgba16f=34842,o.rgb16f=34843),t.webgl_color_buffer_float&&(o.rgba32f=34836);var u=[];Object.keys(o).forEach(function(e){u[o[e]]=e});var s=0,c={};return a.prototype.decRef=function(){0>=--this.refCount&&f(this)},i.profile&&(n.getTotalRenderbufferSize=function(){var e=0;return Object.keys(c).forEach(function(t){e+=c[t].stats.size}),e}),{create:function(t,r){function f(t,r){var n=0,a=0,c=32854;if("object"==typeof t&&t?("shape"in t?(n=0|(a=t.shape)[0],a=0|a[1]):("radius"in t&&(n=a=0|t.radius),"width"in t&&(n=0|t.width),"height"in t&&(a=0|t.height)),"format"in t&&(c=o[t.format])):"number"==typeof t?(n=0|t,a="number"==typeof r?0|r:n):t||(n=a=1),n!==s.width||a!==s.height||c!==s.format)return f.width=s.width=n,f.height=s.height=a,s.format=c,e.bindRenderbuffer(36161,s.renderbuffer),e.renderbufferStorage(36161,c,n,a),i.profile&&(s.stats.size=ge[s.format]*s.width*s.height),f.format=u[s.format],f}var s=new a(e.createRenderbuffer());return c[s.id]=s,n.renderbufferCount++,f(t,r),f.resize=function(t,r){var n=0|t,a=0|r||n;return n===s.width&&a===s.height?f:(f.width=s.width=n,f.height=s.height=a,e.bindRenderbuffer(36161,s.renderbuffer),e.renderbufferStorage(36161,s.format,n,a),i.profile&&(s.stats.size=ge[s.format]*s.width*s.height),f)},f._reglType="renderbuffer",f._renderbuffer=s,i.profile&&(f.stats=s.stats),f.destroy=function(){s.decRef()},f},clear:function(){Y(c).forEach(f)},restore:function(){Y(c).forEach(function(t){t.renderbuffer=e.createRenderbuffer(),e.bindRenderbuffer(36161,t.renderbuffer),e.renderbufferStorage(36161,t.format,t.width,t.height)}),e.bindRenderbuffer(36161,null)}}},ve=[];ve[6408]=4,ve[6407]=3;var xe=[];xe[5121]=1,xe[5126]=4,xe[36193]=2;var we=["x","y","z","w"],Ae="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),ke={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,"dst color":774,"one minus dst color":775,"dst alpha":772,"one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771,"one minus constant alpha":32772,"src alpha saturate":776},_e={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},Oe={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},Ee={cw:2304,ccw:2305},De=new B(!1,!1,!1,function(){});return function(e){function t(){if(0===J.length)A&&A.update(),ee=null;else{ee=U.next(t),l();for(var e=J.length-1;0<=e;--e){var r=J[e];r&&r(C,null,0)}b.flush(),A&&A.update()}}function r(){!ee&&0<J.length&&(ee=U.next(t))}function n(){ee&&(U.cancel(t),ee=null)}function a(e){e.preventDefault(),n(),K.forEach(function(e){e()})}function f(e){b.getError(),y.restore(),I.restore(),F.restore(),P.restore(),H.restore(),q.restore(),z.restore(),A&&A.restore(),G.procs.refresh(),r(),Z.forEach(function(e){e()})}function o(e){function t(e,t){var r={},n={};return Object.keys(e).forEach(function(i){var a=e[i];if(W.isDynamic(a))n[i]=W.unbox(a,i);else{if(t&&Array.isArray(a))for(var f=0;f<a.length;++f)if(W.isDynamic(a[f]))return void(n[i]=W.unbox(a,i));r[i]=a}}),{dynamic:n,static:r}}var r=t(e.context||{},!0),n=t(e.uniforms||{},!0),i=t(e.attributes||{},!1);e=t(function(e){function t(e){if(e in r){var t=r[e];delete r[e],Object.keys(t).forEach(function(n){r[e+"."+n]=t[n]})}}var r=R({},e);return delete r.uniforms,delete r.attributes,delete r.context,delete r.vao,"stencil"in r&&r.stencil.op&&(r.stencil.opBack=r.stencil.opFront=r.stencil.op,delete r.stencil.op),t("blend"),t("depth"),t("cull"),t("stencil"),t("polygonOffset"),t("scissor"),t("sample"),"vao"in e&&(r.vao=e.vao),r}(e),!1);var a={gpuTime:0,cpuTime:0,count:0},f=G.compile(e,i,n,r,a),o=f.draw,u=f.batch,s=f.scope,c=[];return R(function(e,t){var r;if("function"==typeof e)return s.call(this,null,e,0);if("function"==typeof t)if("number"==typeof e)for(r=0;r<e;++r)s.call(this,null,t,r);else{if(!Array.isArray(e))return s.call(this,e,t,0);for(r=0;r<e.length;++r)s.call(this,e[r],t,r)}else if("number"==typeof e){if(0<e)return u.call(this,function(e){for(;c.length<e;)c.push(null);return c}(0|e),0|e)}else{if(!Array.isArray(e))return o.call(this,e);if(e.length)return u.call(this,e,e.length)}},{stats:a,destroy:function(){f.destroy()}})}function u(e,t){var r=0;G.procs.poll();var n=t.color;n&&(b.clearColor(+n[0]||0,+n[1]||0,+n[2]||0,+n[3]||0),r|=16384),"depth"in t&&(b.clearDepth(+t.depth),r|=256),"stencil"in t&&(b.clearStencil(0|t.stencil),r|=1024),b.clear(r)}function s(e){return J.push(e),r(),{cancel:function(){var t=M(J,e);J[t]=function e(){var t=M(J,e);J[t]=J[J.length-1],--J.length,0>=J.length&&n()}}}}function c(){var e=Y.viewport,t=Y.scissor_box;e[0]=e[1]=t[0]=t[1]=0,C.viewportWidth=C.framebufferWidth=C.drawingBufferWidth=e[2]=t[2]=b.drawingBufferWidth,C.viewportHeight=C.framebufferHeight=C.drawingBufferHeight=e[3]=t[3]=b.drawingBufferHeight}function l(){C.tick+=1,C.time=m(),c(),G.procs.poll()}function p(){P.refresh(),c(),G.procs.refresh(),A&&A.update()}function m(){return(N()-k)/1e3}if(!(e=i(e)))return null;var b=e.gl,g=b.getContextAttributes();b.isContextLost();var y=function(e,t){function r(t){var r;t=t.toLowerCase();try{r=n[t]=e.getExtension(t)}catch(e){}return!!r}for(var n={},i=0;i<t.extensions.length;++i){var a=t.extensions[i];if(!r(a))return t.onDestroy(),t.onDone('"'+a+'" extension is not supported by the current WebGL context, try upgrading your system or a different browser'),null}return t.optionalExtensions.forEach(r),{extensions:n,restore:function(){Object.keys(n).forEach(function(e){if(n[e]&&!r(e))throw Error("(regl): error restoring extension "+e)})}}}(b,e);if(!y)return null;var v=function(){var e={"":0},t=[""];return{id:function(r){var n=e[r];return n||(n=e[r]=t.length,t.push(r),n)},str:function(e){return t[e]}}}(),x={vaoCount:0,bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,cubeCount:0,renderbufferCount:0,maxTextureUnits:0},w=y.extensions,A=function(e,t){function r(){this.endQueryIndex=this.startQueryIndex=-1,this.sum=0,this.stats=null}function n(e,t,n){var i=f.pop()||new r;i.startQueryIndex=e,i.endQueryIndex=t,i.sum=0,i.stats=n,o.push(i)}if(!t.ext_disjoint_timer_query)return null;var i=[],a=[],f=[],o=[],u=[],s=[];return{beginQuery:function(e){var r=i.pop()||t.ext_disjoint_timer_query.createQueryEXT();t.ext_disjoint_timer_query.beginQueryEXT(35007,r),a.push(r),n(a.length-1,a.length,e)},endQuery:function(){t.ext_disjoint_timer_query.endQueryEXT(35007)},pushScopeStats:n,update:function(){var e,r;if(0!==(e=a.length)){s.length=Math.max(s.length,e+1),u.length=Math.max(u.length,e+1),u[0]=0;var n=s[0]=0;for(r=e=0;r<a.length;++r){var c=a[r];t.ext_disjoint_timer_query.getQueryObjectEXT(c,34919)?(n+=t.ext_disjoint_timer_query.getQueryObjectEXT(c,34918),i.push(c)):a[e++]=c,u[r+1]=n,s[r+1]=e}for(a.length=e,r=e=0;r<o.length;++r){var l=(n=o[r]).startQueryIndex;c=n.endQueryIndex,n.sum+=u[c]-u[l],l=s[l],(c=s[c])===l?(n.stats.gpuTime+=n.sum/1e6,f.push(n)):(n.startQueryIndex=l,n.endQueryIndex=c,o[e++]=n)}o.length=e}},getNumPendingQueries:function(){return a.length},clear:function(){i.push.apply(i,a);for(var e=0;e<i.length;e++)t.ext_disjoint_timer_query.deleteQueryEXT(i[e]);a.length=0,i.length=0},restore:function(){a.length=0,i.length=0}}}(0,w),k=N(),E=b.drawingBufferWidth,j=b.drawingBufferHeight,C={tick:0,time:0,viewportWidth:E,viewportHeight:j,framebufferWidth:E,framebufferHeight:j,drawingBufferWidth:E,drawingBufferHeight:j,pixelRatio:e.pixelRatio},V=(E={elements:null,primitive:4,count:-1,offset:0,instances:-1},Q(b,w)),F=d(b,x,e,function(e){return z.destroyBuffer(e)}),B=h(b,w,F,x),z=D(b,w,V,x,F,B,E),I=T(b,v,x,e),P=_(b,w,V,function(){G.procs.poll()},C,x,e),H=ye(b,w,0,x,e),q=O(b,w,V,P,H,x),G=L(b,v,w,V,F,B,0,q,{},z,I,E,C,A,e),Y=(v=S(b,q,G.procs.poll,C),G.next),X=b.canvas,J=[],K=[],Z=[],$=[e.onDestroy],ee=null;X&&(X.addEventListener("webglcontextlost",a,!1),X.addEventListener("webglcontextrestored",f,!1));var te=q.setFBO=o({framebuffer:W.define.call(null,1,"framebuffer")});return p(),g=R(o,{clear:function(e){if("framebuffer"in e)if(e.framebuffer&&"framebufferCube"===e.framebuffer_reglType)for(var t=0;6>t;++t)te(R({framebuffer:e.framebuffer.faces[t]},e),u);else te(e,u);else u(0,e)},prop:W.define.bind(null,1),context:W.define.bind(null,2),this:W.define.bind(null,3),draw:o({}),buffer:function(e){return F.create(e,34962,!1,!1)},elements:function(e){return B.create(e,!1)},texture:P.create2D,cube:P.createCube,renderbuffer:H.create,framebuffer:q.create,framebufferCube:q.createCube,vao:z.createVAO,attributes:g,frame:s,on:function(e,t){var r;switch(e){case"frame":return s(t);case"lost":r=K;break;case"restore":r=Z;break;case"destroy":r=$}return r.push(t),{cancel:function(){for(var e=0;e<r.length;++e)if(r[e]===t){r[e]=r[r.length-1],r.pop();break}}}},limits:V,hasExtension:function(e){return 0<=V.extensions.indexOf(e.toLowerCase())},read:v,destroy:function(){J.length=0,n(),X&&(X.removeEventListener("webglcontextlost",a),X.removeEventListener("webglcontextrestored",f)),I.clear(),q.clear(),H.clear(),z.clear(),P.clear(),B.clear(),F.clear(),A&&A.clear(),$.forEach(function(e){e()})},_gl:b,_refresh:p,poll:function(){l(),A&&A.update()},now:m,stats:x}),e.onDone(null,g),g}});
261
-
262
- },{}],88:[function(require,module,exports){
263
- const boundingBox=r=>{if(0===r.length)return[[0,0,0],[0,0,0]];const e=Array.isArray(r)&&Array.isArray(r[0]),n=e?r[0].length:3,o=new Array(n),t=new Array(n);for(let r=0;r<n;r+=1)o[r]=1/0,t[r]=-1/0;if(e)r.forEach(r=>{for(let l=0;l<n;l+=1){const n=e?r[l]:r;t[l]=n>t[l]?n:t[l],o[l]=n<o[l]?n:o[l]}});else for(let e=0;e<r.length;e+=n)for(let l=0;l<n;l+=1){const n=r[l+e];t[l]=n>t[l]?n:t[l],o[l]=n<o[l]?n:o[l]}return[o,t]};module.exports=boundingBox;
264
-
265
- },{}],89:[function(require,module,exports){
266
- const vec3=require("gl-vec3"),{flatten:flatten}=require("@jscad/array-utils"),boundingBox=require("./boundingBox"),computeBounds=(...e)=>{let c;(e=flatten(e)).forEach(e=>{let t=boundingBox(e.positions);t=t.map(c=>vec3.transformMat4(c,c,e.transforms)),c?(vec3.min(c[0],c[0],t[0]),vec3.max(c[1],c[1],t[1])):c=t});const t=vec3.min(vec3.create(),c[1],c[0]),a=vec3.max(vec3.create(),c[1],c[0]),n=vec3.subtract(vec3.create(),a,t);let r=vec3.scale(vec3.create(),n,.5);return r=vec3.add(r,t,r),{dia:vec3.distance(r,a),center:[...r],min:[...t],max:[...a],size:[...n]}};module.exports=computeBounds;
267
-
268
- },{"./boundingBox":88,"@jscad/array-utils":4,"gl-vec3":59}],90:[function(require,module,exports){
269
- const vec3=require("gl-vec3"),mat4=require("gl-mat4"),fromOrthographicToPerspective=e=>{const{near:t,far:r,fov:o,zoom:a}=e,{viewport:i}=e,c=require("./perspectiveCamera").setProjection(e,{width:i[2],height:i[3]}),{projectionType:p}=require("./perspectiveCamera").cameraState;return Object.assign({},e,c,{projectionType:p},{near:t,far:r,fov:o})},fromPerspectiveToOrthographic=e=>{const{fov:t,aspect:r}=e,o=.3*vec3.length(vec3.subtract([],e.position,e.target)),a=Math.tan(t)*o*r,i=Math.tan(t)*o,{near:c,far:p,viewport:s}=e,n={zoom:1,near:c,far:p},v=require("./orthographicCamera").cameraState,h=require("./orthographicCamera").setProjection(n,{width:a,height:i});return Object.assign({},v,e,h,{projectionType:v.projectionType,viewport:s})},toPerspectiveView=({camera:e})=>{const t=vec3.distance(e.position,e.target),r=[t,t,t];return{view:mat4.lookAt(mat4.create(),r,e.target,e.up),position:r}},toPresetView=(e,{camera:t})=>{const r=vec3.distance(t.position,t.target),o=vec3.add(vec3.create(),{top:[0,-1e-6,1],bottom:[0,0,-1],front:[0,1,0],back:[0,-1,0],left:[-1,0,0],right:[1,0,0],undefined:[0,0,0]}[e].map(e=>e*r),t.target);return{view:mat4.lookAt(mat4.create(),o,t.target,t.up),position:o}};module.exports={toPerspectiveView:toPerspectiveView,toPresetView:toPresetView,fromOrthographicToPerspective:fromOrthographicToPerspective,fromPerspectiveToOrthographic:fromPerspectiveToOrthographic};
270
-
271
- },{"./orthographicCamera":91,"./perspectiveCamera":92,"gl-mat4":26,"gl-vec3":59}],91:[function(require,module,exports){
272
- const mat4=require("gl-mat4"),cameraState={view:mat4.identity(new Float32Array(16)),projection:mat4.identity(new Float32Array(16)),matrix:mat4.identity(new Float32Array(16)),near:1,far:1300,up:[0,0,1],eye:new Float32Array(3),position:[150,250,200],target:[0,0,0],fov:Math.PI/4,aspect:1,viewport:[0,0,0,0],zoom:1,projectionType:"orthographic"},cameraProps={},setProjection=(t,e)=>{const{width:a,height:r}=e,o=a/r,i=[0,0,a,r],n=t.zoom,c=-a*n,m=a*n,p=-r*n,s=r*n;return{projection:mat4.ortho([],c,m,p,s,t.near,t.far),aspect:o,viewport:i}};module.exports={cameraState:cameraState,cameraProps:cameraProps,setProjection:setProjection};
273
-
274
- },{"gl-mat4":26}],92:[function(require,module,exports){
275
- const mat4=require("gl-mat4"),vec3=require("gl-vec3"),cameraState={view:mat4.identity(new Float32Array(16)),projection:mat4.identity(new Float32Array(16)),matrix:mat4.identity(new Float32Array(16)),near:1,far:18e3,up:[0,0,1],eye:new Float32Array(3),position:[450,550,700],target:[0,0,0],fov:Math.PI/4,aspect:1,viewport:[0,0,0,0],projectionType:"perspective"},cameraProps={},defaults=Object.assign({},cameraState,cameraProps),setProjection=(e,t,a)=>{const r=a.width/a.height,o=mat4.perspective(mat4.identity([]),t.fov,r,t.near,t.far),i=[0,0,a.width,a.height],c=e||{};return c.projection=o,c.aspect=r,c.viewport=i,c},update=(e,t)=>{t||(t=e);const{position:a,target:r,up:o}=t,i=vec3.subtract([],a,r),c=vec3.add(vec3.create(),r,i),n=mat4.lookAt(mat4.create(),c,r,o),p=e||{};return p.position=c,p.view=n,p};module.exports={cameraState:cameraState,cameraProps:cameraProps,defaults:defaults,setProjection:setProjection,update:update};
276
-
277
- },{"gl-mat4":26,"gl-vec3":59}],93:[function(require,module,exports){
278
- const vec3=require("gl-vec3"),mat4=require("gl-mat4"),{max:max,min:min,sqrt:sqrt,PI:PI,sin:sin,cos:cos,atan2:atan2}=Math,computeBounds=require("../bound-utils/computeBounds"),controlsProps={limits:{minDistance:.01,maxDistance:1e4},drag:.27,EPS:1e-6,zoomToFit:{auto:!0,targets:"all",tightness:1.5},userControl:{zoom:!0,zoomSpeed:1,rotate:!0,rotateSpeed:1,pan:!0,panSpeed:1},autoRotate:{enabled:!1,speed:1},autoAdjustPlanes:!0},controlsState={thetaDelta:0,phiDelta:0,scale:1},defaults=Object.assign({},controlsState,controlsProps),update=({controls:t,camera:e},a)=>{const{EPS:o,drag:s}=t,{position:r,target:n}=e,c=t.up?t.up:e.up;let i=t.thetaDelta;const l=t.phiDelta,m=t.scale,p=vec3.subtract([],r,n);let u,d;1===c[2]?(u=atan2(p[0],p[1]),d=atan2(sqrt(p[0]*p[0]+p[1]*p[1]),p[2])):(u=atan2(p[0],p[2]),d=atan2(sqrt(p[0]*p[0]+p[2]*p[2]),p[1])),t.autoRotate.enabled&&t.userControl.rotate&&(i+=2*Math.PI/60/60*t.autoRotate.speed),u+=i,d=max(o,min(PI-o,d+=l));const h=max(t.limits.minDistance,min(t.limits.maxDistance,vec3.length(p)*m));1===c[2]?(p[0]=h*sin(d)*sin(u),p[2]=h*cos(d),p[1]=h*sin(d)*cos(u)):(p[0]=h*sin(d)*sin(u),p[1]=h*cos(d),p[2]=h*sin(d)*cos(u));const g=vec3.add(vec3.create(),n,p),v=mat4.lookAt(mat4.create(),g,n,c),D=1-max(min(s,1),.01);return{controls:{thetaDelta:i*D,phiDelta:l*D,scale:1,changed:vec3.distance(r,g)>.001},camera:{position:g,view:v}}},rotate=({controls:t,camera:e,speed:a=1},o)=>{let{thetaDelta:s,phiDelta:r}=t;return t.userControl.rotate&&(s+=o[0]*a,r+=o[1]*a),{controls:{thetaDelta:s,phiDelta:r},camera:e}},zoom=({controls:t,camera:e,speed:a=1},o=0)=>{let{scale:s}=t;if(t.userControl.zoom&&e&&void 0!==o&&0!==o&&!isNaN(o)){const r=(o=o/o*(0===Math.sign(o)?1:Math.sign(o))*a)+t.scale,n=vec3.distance(e.position,e.target)*r;if(n>t.limits.minDistance&&n<t.limits.maxDistance&&(s+=o),"orthographic"===e.projectionType){const t=.3*vec3.length(vec3.subtract([],e.position,e.target)),a=Math.tan(e.fov)*t*e.aspect,o=Math.tan(e.fov)*t;e=require("../cameras/orthographicCamera").setProjection(e,{width:a,height:o})}}return{controls:{scale:s},camera:e}},pan=({controls:t,camera:e,speed:a=1},o)=>{const s=require("camera-unproject"),{projection:r,view:n,viewport:c}=e,i=mat4.multiply([],r,n),l=mat4.invert([],i),m=[c[2],c[3],0],p=[c[2]-o[0],c[3]+o[1],0],u=s([],m,c,l),d=s([],p,c,l),h=vec3.distance(e.position,e.eye),g=vec3.subtract([],u,d).map(e=>e*a*h*t.scale);return{controls:t,camera:{position:vec3.add(vec3.create(),e.position,g),target:vec3.add(vec3.create(),e.target,g)}}},zoomToFit=({controls:t,camera:e,entities:a})=>{const{zoomToFit:o}=t;if("all"!==o.targets)return{controls:t,camera:e};if(0===a.length)return{controls:t,camera:e};const s=a.map(t=>t.geometry),r=computeBounds(s),{fov:n,target:c,position:i}=e,{tightness:l}=Object.assign({},o,controlsProps.zoomToFit),m=r.dia*l/Math.tan(n/2)/vec3.distance(c,i);return{camera:{target:r.center},controls:{scale:m}}},reset=({controls:t,camera:e},a)=>{return{camera:{position:a.camera.position,target:a.camera.target,projection:mat4.perspective([],e.fov,e.aspect,e.near,e.far),view:a.camera.view},controls:{thetaDelta:a.controls.thetaDelta,phiDelta:a.controls.phiDelta,scale:a.controls.scale}}};module.exports={controlsProps:controlsProps,controlsState:controlsState,defaults:defaults,update:update,rotate:rotate,zoom:zoom,pan:pan,zoomToFit:zoomToFit,reset:reset};
279
-
280
- },{"../bound-utils/computeBounds":89,"../cameras/orthographicCamera":91,"camera-unproject":9,"gl-mat4":26,"gl-vec3":59}],94:[function(require,module,exports){
281
- const{flatten:flatten,toArray:toArray}=require("@jscad/array-utils"),{meshColor:meshColor}=require("../rendering/renderDefaults"),geom2ToGeometries=require("./geom2ToGeometries"),geom3ToGeometries=require("./geom3ToGeometries"),path2ToGeometries=require("./path2ToGeometries"),assembleEntities=e=>{return e.map(e=>{return{geometry:e,visuals:{drawCmd:"2d"===e.type?"drawLines":"drawMesh",show:!0,transparent:e.isTransparent,useVertexColors:!0}}})},entitiesFromSolids=(e,...o)=>{const r={color:meshColor,smoothNormals:!0},{color:t,smoothNormals:s}=Object.assign({},r,e);o=(o=flatten(toArray(o))).filter(e=>e&&e instanceof Object);const i=[];return o.forEach(e=>{let o=[];"sides"in e?o=geom2ToGeometries({color:t},e):"points"in e?o=path2ToGeometries({color:t},e):"polygons"in e&&(o=geom3ToGeometries({smoothLighting:s,normalThreshold:.3,color:t},e)),i.push(...assembleEntities(o))}),i};module.exports=entitiesFromSolids;
282
-
283
- },{"../rendering/renderDefaults":111,"./geom2ToGeometries":95,"./geom3ToGeometries":96,"./path2ToGeometries":97,"@jscad/array-utils":4}],95:[function(require,module,exports){
284
- const mat4=require("gl-mat4"),maxIndex=Math.floor(32767.5),geom2ToGeometries=(o,e)=>{let{color:t}=o;const n=e.sides;if(0===n.length)return[];"color"in e&&(t=e.color);const r=t[3]<1,s=[],l=Math.floor(n.length/maxIndex)+1,a=(o,e)=>{s.push(o,e||o)},m=[];for(let o=0;o<l;o++){const l=o*maxIndex,c=Math.min(l+maxIndex,n.length),h=[];for(let o=l;o<c;o++){const e=n[o];if(e.color){if(0===s.length&&h.length>0){const o=h.length;for(let e=0;e<o;e++)s.push(t)}a(e.color,e.endColor)}else s.length&&a(t);h.push([e[0][0],e[0][1],0]),h.push([e[1][0],e[1][1],0])}const i=h.map(o=>[0,0,-1]),f=h.map((o,e)=>e),p=e.transforms?mat4.clone(e.transforms):mat4.create();m.push({type:"2d",positions:h,normals:i,indices:f,transforms:p,color:t,colors:s,isTransparent:r})}return m};module.exports=geom2ToGeometries;
285
-
286
- },{"gl-mat4":26}],96:[function(require,module,exports){
287
- const vec3=require("gl-vec3"),mat4=require("gl-mat4"),maxIndex=65535,geom3ToGeometries=(o,e)=>{let{color:t,smoothLighting:n}=o;"color"in e&&(t=e.color);const r=e.polygons,l=e.transforms?mat4.clone(e.transforms):mat4.create(),s=[];let c=0;for(;c<r.length;){let o=0,e=c;for(let t=c;t<r.length&&!((o+=r[t].vertices.length)>65535);t++)e++;const n=[],i=[],a=[],p=[],m=t[3]<1;for(let o=c;o<e;o++){const e=r[o],l=e.vertices,s=calculateNormal(e),c=polygonColor(e,t),m=[];for(let o=0;o<l.length;o++){const e=l[o];n.push(e),i.push(s),p.push(c);const t=n.length-1;m.push(t)}for(let o=2;o<m.length;o++)a.push([m[0],m[o-1],m[o]])}const u={type:"3d",positions:n,normals:i,indices:a,colors:p,transforms:l,isTransparent:m};s.push(u),c=e}return s},smoothing=()=>{const o=[],e=[];let t=!0;const n=[],r=[],l=[],s=[],c=[];let i=0;for(let a=0;a<o.length;a++){const p=o[a],m=p.vertices,u=polygonColor(p,e),h=calculateNormal(p);u&&1!==u[3]&&(t=!0);const g=[];for(let o=0;o<m.length;o++){let e;const t=m[o];{const o={normal:h,position:t},l=fuzyNormalAndPositionLookup(c,o,.5);if(l)e=l.index;else{const l=c[o.position],a=[{normal:o.normal,index:i}];c[o.position]=l?c[o.position].concat(a):a,e=i,u&&s.push(u),r.push(h),n.push(t),i+=1}}g.push(e)}for(let o=2;o<g.length;o++)l.push([g[0],g[o-1],g[o]])}},polygonColor=(o,e)=>{let t=e;return o.color&&(t=o.color),t&&t.length<4&&t.push(1),t},calculateNormal=o=>{if(o.plane)return vec3.clone(o.plane);const e=o.vertices,t=vec3.create();vec3.subtract(t,e[1],e[0]);const n=vec3.create();vec3.subtract(n,e[2],e[0]);const r=vec3.create();return vec3.cross(r,t,n),vec3.normalize(r,r),r},areNormalsSimilar=(o,e,t)=>vec3.distance(o,e)<=t,fuzyNormalAndPositionLookup=(o,e,t)=>{const n=o[e.position];if(n)for(let o=0;o<n.length;o++){const r=n[o].normal;if(areNormalsSimilar(r,e.normal,t))return{tupple:{position:e.position,normal:r},index:n[o].index}}};module.exports=geom3ToGeometries;
288
-
289
- },{"gl-mat4":26,"gl-vec3":59}],97:[function(require,module,exports){
290
- const mat4=require("gl-mat4"),maxIndex=Math.floor(32767.5)-2,path2ToGeometries=(o,t)=>{let{color:e}=o;const s=t.points;if(0===s.length)return[];"color"in t&&(e=t.color);const n=e[3]<1,r=Math.floor(s.length/maxIndex)+1,a=[];for(let o=0;o<r;o++){const l=o*maxIndex,m=Math.min(l+maxIndex,s.length),c=[];let i;for(let o=l;o<m;o++){const t=s[o];i&&(c.push([i[0],i[1],0]),c.push([t[0],t[1],0])),i=t}if(o+1===r&&t.isClosed&&i){const o=s[0];c.push([i[0],i[1],0]),c.push([o[0],o[1],0])}const p=c.map(o=>[0,0,-1]),h=c.map((o,t)=>t),f=t.transforms?mat4.clone(t.transforms):mat4.create();a.push({type:"2d",positions:c,normals:p,indices:h,transforms:f,color:e,isTransparent:n})}return a};module.exports=path2ToGeometries;
291
-
292
- },{"gl-mat4":26}],98:[function(require,module,exports){
293
- module.exports={prepareRender:require("./rendering/render"),drawCommands:{drawGrid:require("./rendering/commands/drawGrid/multi.js"),drawAxis:require("./rendering/commands/drawAxis"),drawMesh:require("./rendering/commands/drawMesh"),drawLines:require("./rendering/commands/drawLines")},cameras:{camera:require("./cameras/camera"),orthographic:require("./cameras/orthographicCamera"),perspective:require("./cameras/perspectiveCamera")},controls:{orbit:require("./controls/orbitControls")},entitiesFromSolids:require("./geometry-utils-V2/entitiesFromSolids")};
294
-
295
- },{"./cameras/camera":90,"./cameras/orthographicCamera":91,"./cameras/perspectiveCamera":92,"./controls/orbitControls":93,"./geometry-utils-V2/entitiesFromSolids":94,"./rendering/commands/drawAxis":99,"./rendering/commands/drawGrid/multi.js":101,"./rendering/commands/drawLines":103,"./rendering/commands/drawMesh":106,"./rendering/render":109}],99:[function(require,module,exports){
296
- const mat4=require("gl-mat4"),drawAxis=(t,i)=>{let{size:o,xColor:e,yColor:l,zColor:m,lineWidth:a,alwaysVisible:n}=Object.assign({},{xColor:[1,0,0,1],yColor:[0,1,0,1],zColor:[0,0,1,1],size:10,lineWidth:3,alwaysVisible:!0},i);a>t.limits.lineWidthDims[1]&&(a=t.limits.lineWidthDims[1]);const r=[0,0,0,o,0,0],d={frag:"precision mediump float;\n uniform vec4 color;\n void main() {\n gl_FragColor = color;\n }",vert:"\n precision mediump float;\n attribute vec3 position;\n uniform mat4 model, view, projection;\n void main() {\n gl_Position = projection * view * model * vec4(position, 1);\n }",uniforms:{model:(t,i)=>i&&i.model?i.model:mat4.identity([]),color:(t,i)=>i.color,angle:(t,i)=>i.angle},attributes:{position:r},count:r.length/3,primitive:"line loop",lineWidth:a,depth:{enable:!n}},s=mat4.identity([]),c=mat4.rotateZ(mat4.create(),mat4.identity([]),Math.PI/2),p=mat4.rotateY(mat4.create(),mat4.identity([]),-Math.PI/2),u=t(d);return t=>{const i={model:mat4.identity([])};return t=Object.assign({},i,t),u([{color:e,model:mat4.multiply(mat4.create(),t.model,s)},{color:l,model:mat4.multiply(mat4.create(),t.model,c)},{color:m,model:mat4.multiply(mat4.create(),t.model,p)}])}};module.exports=drawAxis;
297
-
298
- },{"gl-mat4":26}],100:[function(require,module,exports){
299
- const mat4=require("gl-mat4"),makeDrawGrid=(o,i={})=>{const n=[],t={visuals:{color:[0,0,1,1],fadeOut:!1},ticks:1,size:[16,16],centered:!1,lineWidth:2},e=Object.assign({},t.visuals,i.visuals||{}),{fadeOut:r,color:s}=e,{size:l,ticks:a,centered:c,lineWidth:d}=Object.assign({},t,i),f=l[0],u=l[1];if(c){const o=.5*f,i=.5*u,t=-o+o%a,e=-t,r=-i+i%a,s=-r,l=0;for(let o=t,i=0;o<=e;o+=a,i+=1)i%l!=0&&(n.push(r,o,0),n.push(s,o,0),n.push(r,o,0));for(let o=r,i=0;o<=s;o+=a,i+=1)i%l!=0&&(n.push(o,t,0),n.push(o,e,0),n.push(o,t,0))}else{for(let o=.5*-f;o<=.5*f;o+=a)n.push(.5*-u,o,0),n.push(.5*u,o,0),n.push(.5*-u,o,0);for(let o=.5*-u;o<=.5*u;o+=a)n.push(o,.5*-f,0),n.push(o,.5*f,0),n.push(o,.5*-f,0)}return o({vert:"precision mediump float;\n\n uniform float camNear, camFar;\n uniform mat4 model, view, projection;\n\n attribute vec3 position;\n varying vec3 fragNormal, fragPosition;\n varying vec4 worldPosition;\n\n void main() {\n fragPosition = position;\n worldPosition = model * vec4(position, 1);\n vec4 glPosition = projection * view * worldPosition;\n gl_Position = glPosition;\n }",frag:"precision mediump float;\n uniform vec4 color;\n varying vec3 fragNormal, fragPosition;\n varying vec4 worldPosition;\n\n uniform vec4 fogColor;\n uniform bool fadeOut;\n void main() {\n float dist = .5;\n if(fadeOut){\n dist = distance( vec2(0.,0.), vec2(worldPosition.x, worldPosition.y));\n dist *= 0.0025;\n dist = sqrt(dist);\n }\n\n gl_FragColor = mix(color, fogColor, dist);\n }\n ",attributes:{position:o.buffer(n)},count:n.length/3,uniforms:{model:(o,i)=>i&&i.model?i.model:mat4.identity([]),color:(o,i)=>i&&i.color?i.color:s,fogColor:(o,i)=>i&&i.color?[i.color[0],i.color[1],i.color[2],0]:[s[0],s[1],s[2],0],fadeOut:(o,i)=>i&&void 0!==i.fadeOut?i.fadeOut:r},lineWidth:(i,n)=>Math.min(n&&n.lineWidth?n.lineWidth:d,o.limits.lineWidthDims[1]),primitive:"lines",cull:{enable:!0,face:"front"},polygonOffset:{enable:!0,offset:{factor:1,units:10*Math.random()}},blend:{enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}})};module.exports=makeDrawGrid;
300
-
301
- },{"gl-mat4":26}],101:[function(require,module,exports){
302
- const makeDrawMultiGrid=(e,i)=>{const{size:s,ticks:r}=Object.assign({},{size:[50,50],ticks:[10,1]},i),t=require("./index")(e,{size:s,ticks:r[0]}),u=require("./index")(e,{size:s,ticks:r[1]});return e=>{t(e),u({color:e.subColor,fadeOut:e.fadeOut})}};module.exports=makeDrawMultiGrid;
303
-
304
- },{"./index":100}],102:[function(require,module,exports){
305
- const vColorFrag="\nprecision mediump float;\nuniform vec4 ucolor;\n\nvoid main () {\n gl_FragColor = ucolor;\n}\n";module.exports={frag:vColorFrag};
306
-
307
- },{}],103:[function(require,module,exports){
308
- const mat4=require("gl-mat4"),{meshColor:meshColor}=require("../../renderDefaults"),drawLines=(e,r={})=>{const o={color:meshColor,geometry:void 0};let{geometry:t,color:s,transparent:a}=Object.assign({},o,r);"color"in t&&(s=t.color);const l=!!(t.indices&&t.indices.length>0),i=!!(t.normals&&t.normals.length>0),n=!!(t.colors&&t.colors.length>0),c={primitive:"lines",vert:n?require("./vColorShaders").vert:require("./meshShaders").vert,frag:n?require("./vColorShaders").frag:require("./colorOnlyShaders").frag,uniforms:{model:(e,r)=>r.model||t.transforms||mat4.create(),ucolor:(e,r)=>r&&r.color?r.color:s},attributes:{position:e.buffer({usage:"static",type:"float",data:t.positions})}};return a&&(c.blend={enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}),n&&(c.attributes.color=e.buffer({usage:"static",type:"float",data:t.colors})),l&&(c.elements=e.elements({usage:"static",type:"uint16",data:t.indices})),i&&(c.attributes.normal=e.buffer({usage:"static",type:"float",data:t.normals})),e(c)};module.exports=drawLines;
309
-
310
- },{"../../renderDefaults":111,"./colorOnlyShaders":102,"./meshShaders":104,"./vColorShaders":105,"gl-mat4":26}],104:[function(require,module,exports){
311
- const meshVert="\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\n\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\n\n\nvoid main() {\n\n\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n",meshFrag="\nprecision mediump float;\nvarying vec3 surfaceNormal;\nuniform float ambientLightAmount;\nuniform float diffuseLightAmount;\nuniform vec4 ucolor;\nuniform vec3 lightDirection;\nuniform vec3 opacity;\n\nvarying vec4 _worldSpacePosition;\n\nuniform vec2 printableArea;\n\nvec4 errorColor = vec4(0.15, 0.15, 0.15, 0.3);\n\nvoid main () {\n vec4 depth = gl_FragCoord;\n\n float v = 0.8; // shadow value\n vec4 endColor = ucolor;\n\n vec3 ambient = ambientLightAmount * endColor.rgb;\n float cosTheta = dot(surfaceNormal, lightDirection);\n vec3 diffuse = diffuseLightAmount * endColor.rgb * clamp(cosTheta , 0.0, 1.0 );\n\n float cosTheta2 = dot(surfaceNormal, vec3(-lightDirection.x, -lightDirection.y, lightDirection.z));\n vec3 diffuse2 = diffuseLightAmount * endColor.rgb * clamp(cosTheta2 , 0.0, 1.0 );\n\n gl_FragColor = vec4((ambient + diffuse + diffuse2 * v), endColor.a);\n}";module.exports={vert:meshVert,frag:meshFrag};
312
-
313
- },{}],105:[function(require,module,exports){
314
- const vColorVert="\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\nattribute vec4 color;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\nvarying vec4 vColor;\n\nvoid main() {\n vColor = color;\n\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n",vColorFrag="\nprecision mediump float;\nvarying vec4 vColor;\n\nvoid main () {\n gl_FragColor = vColor;\n}\n";module.exports={frag:vColorFrag,vert:vColorVert};
315
-
316
- },{}],106:[function(require,module,exports){
317
- const mat4=require("gl-mat4"),{meshColor:meshColor}=require("../../renderDefaults"),drawMesh=(e,r={extras:{}})=>{const t={useVertexColors:!0,dynamicCulling:!0,geometry:void 0,color:meshColor,visuals:{}},{geometry:s,dynamicCulling:a,useVertexColors:o,color:l,visuals:n}=Object.assign({},t,r),i=e.buffer([]),u=!!(s.indices&&s.indices.length>0),c=!!(s.normals&&s.normals.length>0),m="transparent"in n&&n.transparent,g=!!(o&&s.colors&&s.colors.length>0),d=s.transforms||mat4.create(),f=mat4.determinant(d)<0,h=a&&f?"front":"back",p=g?require("./vColorShaders").vert:require("./meshShaders").vert,b=g?require("./vColorShaders").frag:require("./meshShaders").frag,v=mat4.invert(mat4.create(),d);let C={primitive:"triangles",vert:p,frag:b,uniforms:{model:(e,r)=>d,ucolor:(e,r)=>r&&r.color?r.color:l,vColorToggler:(e,r)=>r&&r.useVertexColors&&!0===r.useVertexColors?1:0,unormal:(e,r)=>{const t=mat4.invert(mat4.create(),r.camera.view);return mat4.multiply(t,v,t),mat4.transpose(t,t),t}},attributes:{position:e.buffer({usage:"static",type:"float",data:s.positions}),ao:i},cull:{enable:!0,face:h}};return m&&(C.blend={enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}),s.cells?C.elements=s.cells:u?C.elements=e.elements({usage:"static",type:"uint16",data:s.indices}):s.triangles?C.elements=s.triangles:C.count=s.positions.length/3,c&&(C.attributes.normal=e.buffer({usage:"static",type:"float",data:s.normals})),g&&(C.attributes.color=e.buffer({usage:"static",type:"float",data:s.colors})),e(C=Object.assign({},C,r.extras))};module.exports=drawMesh;
318
-
319
- },{"../../renderDefaults":111,"./meshShaders":107,"./vColorShaders":108,"gl-mat4":26}],107:[function(require,module,exports){
320
- const meshFrag="\nprecision mediump float;\nvarying vec3 surfaceNormal;\nuniform float ambientLightAmount;\nuniform float diffuseLightAmount;\nuniform vec4 ucolor;\nuniform vec3 lightDirection;\nuniform vec3 opacity;\n\nvarying vec4 _worldSpacePosition;\n\nuniform vec2 printableArea;\n\nvec4 errorColor = vec4(0.15, 0.15, 0.15, 0.3);\n\nvoid main () {\n vec4 depth = gl_FragCoord;\n\n float v = 0.8; // shadow value\n vec4 endColor = ucolor;\n\n vec3 ambient = ambientLightAmount * endColor.rgb;\n float cosTheta = dot(surfaceNormal, lightDirection);\n vec3 diffuse = diffuseLightAmount * endColor.rgb * clamp(cosTheta , 0.0, 1.0 );\n\n float cosTheta2 = dot(surfaceNormal, vec3(-lightDirection.x, -lightDirection.y, lightDirection.z));\n vec3 diffuse2 = diffuseLightAmount * endColor.rgb * clamp(cosTheta2 , 0.0, 1.0 );\n\n gl_FragColor = vec4((ambient + diffuse + diffuse2 * v), endColor.a);\n}",meshVert="\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\n\nvoid main() {\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n";module.exports={vert:meshVert,frag:meshFrag};
321
-
322
- },{}],108:[function(require,module,exports){
323
- const vColorVert="\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection, unormal;\n\nattribute vec3 position, normal;\nattribute vec4 color;\n\nattribute float ao;\nvarying float ambientAo;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\nvarying vec4 vColor;\n\nvoid main() {\n surfacePosition = (unormal * vec4(position, 1.0)).xyz;\n surfaceNormal = normalize((unormal * vec4(normal, 1.0)).xyz); //vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n //gl_Position = projection * view * worldSpacePosition;\n\n vColor = color;\n\n //ambientAo = (1. - ao) * (0.5 * max(normal.x, 0.) + 0.5);\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n //gl_Position = zBufferAdjust(glPosition, camNear, camFar);\n}\n",vColorFrag="\nprecision mediump float;\nvarying vec3 surfaceNormal, surfacePosition;\n\nuniform float ambientLightAmount;\nuniform float diffuseLightAmount;\nuniform float specularLightAmount;\n\nuniform vec3 lightDirection;\nuniform vec4 lightColor;\nuniform vec3 opacity;\nuniform float uMaterialShininess;\n\nvarying vec4 vColor;\nuniform vec4 ucolor;\nuniform float vColorToggler;\n\nuniform vec2 printableArea;\nvec4 errorColor = vec4(0.15, 0.15, 0.15, 0.3);//vec4(0.15, 0.15, 0.15, 0.3);\nvarying vec4 _worldSpacePosition;\nvarying float ambientAo;\n\nvoid main () {\n vec4 depth = gl_FragCoord;\n vec4 endColor = vColor * vColorToggler + ucolor * (1.0 - vColorToggler);\n\n vec3 ambient = ambientLightAmount * endColor.rgb ; //ambientAo * \n\n float diffuseWeight = dot(surfaceNormal, lightDirection);\n vec3 diffuse = diffuseLightAmount * endColor.rgb * clamp(diffuseWeight , 0.0, 1.0 );\n\n //specular\n \n vec4 specularColor = vec4(lightColor);\n vec3 eyeDirection = normalize(surfacePosition.xyz);\n vec3 reflectionDirection = reflect(-lightDirection, -surfaceNormal);\n float specularLightWeight = pow(max(dot(reflectionDirection, eyeDirection), 0.0), uMaterialShininess);\n vec3 specular = specularColor.rgb * specularLightWeight * specularLightAmount;\n\n gl_FragColor = vec4((ambient + diffuse + specular), endColor.a);\n}\n";module.exports={frag:vColorFrag,vert:vColorVert};
324
-
325
- },{}],109:[function(require,module,exports){
326
- const renderContext=require("./renderContext"),renderDefaults=require("./renderDefaults"),prepareRender=e=>{const r=Object.assign({},{},e.glOptions,{onDone:(e,r)=>{if(e)throw e}}),n=require("regl")(r),a=new Map;return function(e){var r;n.poll(),(r=e).rendering=Object.assign({},renderDefaults,r.rendering),renderContext(n)(r,e=>{n.clear({color:r.rendering.background,depth:1}),r.entities&&r.entities.sort((e,r)=>{const n="transparent"in e.visuals&&e.visuals.transparent;return n===("transparent"in r.visuals&&r.visuals.transparent)?0:n?1:-1}).forEach(e=>{const{visuals:t}=e;if((!("show"in t)||t.show)&&t.drawCmd&&r.drawCommands[t.drawCmd]){let s;t.cacheId?s=a.get(t.cacheId):(t.cacheId=a.size,s=r.drawCommands[t.drawCmd](n,e),a.set(t.cacheId,s)),s({...e,...t,camera:r.camera})}})})}};module.exports=prepareRender;
327
-
328
- },{"./renderContext":110,"./renderDefaults":111,"regl":87}],110:[function(require,module,exports){
329
- const mat4=require("gl-mat4"),renderWrapper=(e,i={})=>{const{fbo:r}=i,n={cull:{enable:!0},context:{lightDirection:[.2,.2,1]},uniforms:{view:(e,i)=>i.camera.view,eye:(e,i)=>i.camera.position,projection:(e,i)=>i.camera.projection,camNear:(e,i)=>i.camera.near,camFar:(e,i)=>i.camera.far,invertedView:(e,i)=>mat4.invert([],i.camera.view),lightPosition:(e,i)=>i&&i.rendering&&i.rendering.lightPosition?i.rendering.lightPosition:[100,200,100],lightDirection:(e,i)=>i&&i.rendering&&i.rendering.lightDirection?i.rendering.lightDirection:e.lightDirection||[0,0,0],lightView:e=>mat4.lookAt([],e.lightDirection,[0,0,0],[0,0,1]),lightProjection:mat4.ortho([],-25,-25,-20,20,-25,25),lightColor:(e,i)=>i&&i.rendering&&i.rendering.lightColor?i.rendering.lightColor:[1,.8,0],ambientLightAmount:(e,i)=>i&&i.rendering&&i.rendering.ambientLightAmount?i.rendering.ambientLightAmount:.3,diffuseLightAmount:(e,i)=>i&&i.rendering&&i.rendering.diffuseLightAmount?i&&i.rendering&&i.rendering.diffuseLightAmount:.89,specularLightAmount:(e,i)=>i&&i.rendering&&i.rendering.specularLightAmount?i.rendering.specularLightAmount:.16,uMaterialShininess:(e,i)=>i&&i.rendering&&i.rendering.materialShininess?i.rendering.materialShininess:8,materialAmbient:[.5,.8,.3],materialDiffuse:[.5,.8,.3],materialSpecular:[.5,.8,.3]},framebuffer:r};return e(Object.assign({},n,i.extras))};module.exports=renderWrapper;
330
-
331
- },{"gl-mat4":26}],111:[function(require,module,exports){
332
- module.exports={background:[1,1,1,1],meshColor:[0,.6,1,1],lightColor:[1,1,1,1],lightDirection:[.2,.2,1],lightPosition:[100,200,100],ambientLightAmount:.3,diffuseLightAmount:.89,specularLightAmount:.16,materialShininess:8};
333
-
334
- },{}]},{},[98])(98)
335
- });
1
+ /**
2
+ * Renderer for JSCAD Geometries
3
+ * @module @jscad/regl-renderer
4
+ * @version 3.0.1-alpha.0
5
+ * @license MIT
6
+ */
7
+ !function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).jscadReglRenderer={})}(this,(function(exports){"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var create_1$1=function(){var out=new Float32Array(3);return out[0]=0,out[1]=0,out[2]=0,out};var clone_1$1=function(a){var out=new Float32Array(3);return out[0]=a[0],out[1]=a[1],out[2]=a[2],out};var fromValues_1=function(x,y,z){var out=new Float32Array(3);return out[0]=x,out[1]=y,out[2]=z,out};var normalize_1=function(out,a){var x=a[0],y=a[1],z=a[2],len=x*x+y*y+z*z;len>0&&(len=1/Math.sqrt(len),out[0]=a[0]*len,out[1]=a[1]*len,out[2]=a[2]*len);return out};var dot_1=function(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]};var angle_1=function(a,b){var tempA=fromValues(a[0],a[1],a[2]),tempB=fromValues(b[0],b[1],b[2]);normalize(tempA,tempA),normalize(tempB,tempB);var cosine=dot(tempA,tempB);return cosine>1?0:Math.acos(cosine)},fromValues=fromValues_1,normalize=normalize_1,dot=dot_1;var copy_1$1=function(out,a){return out[0]=a[0],out[1]=a[1],out[2]=a[2],out};var set_1=function(out,x,y,z){return out[0]=x,out[1]=y,out[2]=z,out};var equals_1=function(a,b){var a0=a[0],a1=a[1],a2=a[2],b0=b[0],b1=b[1],b2=b[2];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))},EPSILON=1e-6;var exactEquals_1=function(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]};var add_1=function(out,a,b){return out[0]=a[0]+b[0],out[1]=a[1]+b[1],out[2]=a[2]+b[2],out};var subtract_1=function(out,a,b){return out[0]=a[0]-b[0],out[1]=a[1]-b[1],out[2]=a[2]-b[2],out};var subExports={};!function(module){module.exports=subtract_1}({get exports(){return subExports},set exports(v){subExports=v}});var multiply_1$1=function(out,a,b){return out[0]=a[0]*b[0],out[1]=a[1]*b[1],out[2]=a[2]*b[2],out};var mulExports={};!function(module){module.exports=multiply_1$1}({get exports(){return mulExports},set exports(v){mulExports=v}});var divide_1=function(out,a,b){return out[0]=a[0]/b[0],out[1]=a[1]/b[1],out[2]=a[2]/b[2],out};var divExports={};!function(module){module.exports=divide_1}({get exports(){return divExports},set exports(v){divExports=v}});var min_1=function(out,a,b){return out[0]=Math.min(a[0],b[0]),out[1]=Math.min(a[1],b[1]),out[2]=Math.min(a[2],b[2]),out};var max_1=function(out,a,b){return out[0]=Math.max(a[0],b[0]),out[1]=Math.max(a[1],b[1]),out[2]=Math.max(a[2],b[2]),out};var floor_1=function(out,a){return out[0]=Math.floor(a[0]),out[1]=Math.floor(a[1]),out[2]=Math.floor(a[2]),out};var ceil_1=function(out,a){return out[0]=Math.ceil(a[0]),out[1]=Math.ceil(a[1]),out[2]=Math.ceil(a[2]),out};var round_1=function(out,a){return out[0]=Math.round(a[0]),out[1]=Math.round(a[1]),out[2]=Math.round(a[2]),out};var scale_1$1=function(out,a,b){return out[0]=a[0]*b,out[1]=a[1]*b,out[2]=a[2]*b,out};var scaleAndAdd_1=function(out,a,b,scale){return out[0]=a[0]+b[0]*scale,out[1]=a[1]+b[1]*scale,out[2]=a[2]+b[2]*scale,out};var distance_1=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return Math.sqrt(x*x+y*y+z*z)};var distExports={};!function(module){module.exports=distance_1}({get exports(){return distExports},set exports(v){distExports=v}});var squaredDistance_1=function(a,b){var x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2];return x*x+y*y+z*z};var sqrDistExports={};!function(module){module.exports=squaredDistance_1}({get exports(){return sqrDistExports},set exports(v){sqrDistExports=v}});var length_1=function(a){var x=a[0],y=a[1],z=a[2];return Math.sqrt(x*x+y*y+z*z)};var lenExports={};!function(module){module.exports=length_1}({get exports(){return lenExports},set exports(v){lenExports=v}});var squaredLength_1=function(a){var x=a[0],y=a[1],z=a[2];return x*x+y*y+z*z};var sqrLenExports={};!function(module){module.exports=squaredLength_1}({get exports(){return sqrLenExports},set exports(v){sqrLenExports=v}});var negate_1=function(out,a){return out[0]=-a[0],out[1]=-a[1],out[2]=-a[2],out};var inverse_1=function(out,a){return out[0]=1/a[0],out[1]=1/a[1],out[2]=1/a[2],out};var cross_1=function(out,a,b){var ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2];return out[0]=ay*bz-az*by,out[1]=az*bx-ax*bz,out[2]=ax*by-ay*bx,out};var lerp_1=function(out,a,b,t){var ax=a[0],ay=a[1],az=a[2];return out[0]=ax+t*(b[0]-ax),out[1]=ay+t*(b[1]-ay),out[2]=az+t*(b[2]-az),out};var random_1=function(out,scale){scale=scale||1;var r=2*Math.random()*Math.PI,z=2*Math.random()-1,zScale=Math.sqrt(1-z*z)*scale;return out[0]=Math.cos(r)*zScale,out[1]=Math.sin(r)*zScale,out[2]=z*scale,out};var transformMat4_1=function(out,a,m){var x=a[0],y=a[1],z=a[2],w=m[3]*x+m[7]*y+m[11]*z+m[15];return w=w||1,out[0]=(m[0]*x+m[4]*y+m[8]*z+m[12])/w,out[1]=(m[1]*x+m[5]*y+m[9]*z+m[13])/w,out[2]=(m[2]*x+m[6]*y+m[10]*z+m[14])/w,out};var transformMat3_1=function(out,a,m){var x=a[0],y=a[1],z=a[2];return out[0]=x*m[0]+y*m[3]+z*m[6],out[1]=x*m[1]+y*m[4]+z*m[7],out[2]=x*m[2]+y*m[5]+z*m[8],out};var transformQuat_1=function(out,a,q){var x=a[0],y=a[1],z=a[2],qx=q[0],qy=q[1],qz=q[2],qw=q[3],ix=qw*x+qy*z-qz*y,iy=qw*y+qz*x-qx*z,iz=qw*z+qx*y-qy*x,iw=-qx*x-qy*y-qz*z;return out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy,out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz,out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx,out};var rotateX_1$1=function(out,a,b,c){var by=b[1],bz=b[2],py=a[1]-by,pz=a[2]-bz,sc=Math.sin(c),cc=Math.cos(c);return out[0]=a[0],out[1]=by+py*cc-pz*sc,out[2]=bz+py*sc+pz*cc,out};var rotateY_1$1=function(out,a,b,c){var bx=b[0],bz=b[2],px=a[0]-bx,pz=a[2]-bz,sc=Math.sin(c),cc=Math.cos(c);return out[0]=bx+pz*sc+px*cc,out[1]=a[1],out[2]=bz+pz*cc-px*sc,out};var rotateZ_1$1=function(out,a,b,c){var bx=b[0],by=b[1],px=a[0]-bx,py=a[1]-by,sc=Math.sin(c),cc=Math.cos(c);return out[0]=bx+px*cc-py*sc,out[1]=by+px*sc+py*cc,out[2]=a[2],out};var forEach_1=function(a,stride,offset,count,fn,arg){var i,l;stride||(stride=3);offset||(offset=0);l=count?Math.min(count*stride+offset,a.length):a.length;for(i=offset;i<l;i+=stride)vec[0]=a[i],vec[1]=a[i+1],vec[2]=a[i+2],fn(vec,vec,arg),a[i]=vec[0],a[i+1]=vec[1],a[i+2]=vec[2];return a},vec=create_1$1();var glVec3={EPSILON:1e-6,create:create_1$1,clone:clone_1$1,angle:angle_1,fromValues:fromValues_1,copy:copy_1$1,set:set_1,equals:equals_1,exactEquals:exactEquals_1,add:add_1,subtract:subtract_1,sub:subExports,multiply:multiply_1$1,mul:mulExports,divide:divide_1,div:divExports,min:min_1,max:max_1,floor:floor_1,ceil:ceil_1,round:round_1,scale:scale_1$1,scaleAndAdd:scaleAndAdd_1,distance:distance_1,dist:distExports,squaredDistance:squaredDistance_1,sqrDist:sqrDistExports,length:length_1,len:lenExports,squaredLength:squaredLength_1,sqrLen:sqrLenExports,negate:negate_1,inverse:inverse_1,normalize:normalize_1,dot:dot_1,cross:cross_1,lerp:lerp_1,random:random_1,transformMat4:transformMat4_1,transformMat3:transformMat3_1,transformQuat:transformQuat_1,rotateX:rotateX_1$1,rotateY:rotateY_1$1,rotateZ:rotateZ_1$1,forEach:forEach_1};var identity_1=function(out){return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out};var rotate_1=function(out,a,rad,axis){var s,c,t,a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23,b00,b01,b02,b10,b11,b12,b20,b21,b22,x=axis[0],y=axis[1],z=axis[2],len=Math.sqrt(x*x+y*y+z*z);if(Math.abs(len)<1e-6)return null;len=1/len,x*=len,y*=len,z*=len,s=Math.sin(rad),c=Math.cos(rad),t=1-c,a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],b00=x*x*t+c,b01=y*x*t+z*s,b02=z*x*t-y*s,b10=x*y*t-z*s,b11=y*y*t+c,b12=z*y*t+x*s,b20=x*z*t+y*s,b21=y*z*t-x*s,b22=z*z*t+c,out[0]=a00*b00+a10*b01+a20*b02,out[1]=a01*b00+a11*b01+a21*b02,out[2]=a02*b00+a12*b01+a22*b02,out[3]=a03*b00+a13*b01+a23*b02,out[4]=a00*b10+a10*b11+a20*b12,out[5]=a01*b10+a11*b11+a21*b12,out[6]=a02*b10+a12*b11+a22*b12,out[7]=a03*b10+a13*b11+a23*b12,out[8]=a00*b20+a10*b21+a20*b22,out[9]=a01*b20+a11*b21+a21*b22,out[10]=a02*b20+a12*b21+a22*b22,out[11]=a03*b20+a13*b21+a23*b22,a!==out&&(out[12]=a[12],out[13]=a[13],out[14]=a[14],out[15]=a[15]);return out};var fromRotation_1=function(out,rad,axis){var s,c,t,x=axis[0],y=axis[1],z=axis[2],len=Math.sqrt(x*x+y*y+z*z);if(Math.abs(len)<1e-6)return null;return len=1/len,x*=len,y*=len,z*=len,s=Math.sin(rad),c=Math.cos(rad),t=1-c,out[0]=x*x*t+c,out[1]=y*x*t+z*s,out[2]=z*x*t-y*s,out[3]=0,out[4]=x*y*t-z*s,out[5]=y*y*t+c,out[6]=z*y*t+x*s,out[7]=0,out[8]=x*z*t+y*s,out[9]=y*z*t-x*s,out[10]=z*z*t+c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out};var identity=identity_1,lookAt_1=function(out,eye,center,up){var x0,x1,x2,y0,y1,y2,z0,z1,z2,len,eyex=eye[0],eyey=eye[1],eyez=eye[2],upx=up[0],upy=up[1],upz=up[2],centerx=center[0],centery=center[1],centerz=center[2];if(Math.abs(eyex-centerx)<1e-6&&Math.abs(eyey-centery)<1e-6&&Math.abs(eyez-centerz)<1e-6)return identity(out);z0=eyex-centerx,z1=eyey-centery,z2=eyez-centerz,len=1/Math.sqrt(z0*z0+z1*z1+z2*z2),z0*=len,z1*=len,z2*=len,x0=upy*z2-upz*z1,x1=upz*z0-upx*z2,x2=upx*z1-upy*z0,len=Math.sqrt(x0*x0+x1*x1+x2*x2),len?(x0*=len=1/len,x1*=len,x2*=len):(x0=0,x1=0,x2=0);y0=z1*x2-z2*x1,y1=z2*x0-z0*x2,y2=z0*x1-z1*x0,len=Math.sqrt(y0*y0+y1*y1+y2*y2),len?(y0*=len=1/len,y1*=len,y2*=len):(y0=0,y1=0,y2=0);return out[0]=x0,out[1]=y0,out[2]=z0,out[3]=0,out[4]=x1,out[5]=y1,out[6]=z1,out[7]=0,out[8]=x2,out[9]=y2,out[10]=z2,out[11]=0,out[12]=-(x0*eyex+x1*eyey+x2*eyez),out[13]=-(y0*eyex+y1*eyey+y2*eyez),out[14]=-(z0*eyex+z1*eyey+z2*eyez),out[15]=1,out};var glMat4={create:function(){var out=new Float32Array(16);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},clone:function(a){var out=new Float32Array(16);return out[0]=a[0],out[1]=a[1],out[2]=a[2],out[3]=a[3],out[4]=a[4],out[5]=a[5],out[6]=a[6],out[7]=a[7],out[8]=a[8],out[9]=a[9],out[10]=a[10],out[11]=a[11],out[12]=a[12],out[13]=a[13],out[14]=a[14],out[15]=a[15],out},copy:function(out,a){return out[0]=a[0],out[1]=a[1],out[2]=a[2],out[3]=a[3],out[4]=a[4],out[5]=a[5],out[6]=a[6],out[7]=a[7],out[8]=a[8],out[9]=a[9],out[10]=a[10],out[11]=a[11],out[12]=a[12],out[13]=a[13],out[14]=a[14],out[15]=a[15],out},identity:identity_1,transpose:function(out,a){if(out===a){var a01=a[1],a02=a[2],a03=a[3],a12=a[6],a13=a[7],a23=a[11];out[1]=a[4],out[2]=a[8],out[3]=a[12],out[4]=a01,out[6]=a[9],out[7]=a[13],out[8]=a02,out[9]=a12,out[11]=a[14],out[12]=a03,out[13]=a13,out[14]=a23}else out[0]=a[0],out[1]=a[4],out[2]=a[8],out[3]=a[12],out[4]=a[1],out[5]=a[5],out[6]=a[9],out[7]=a[13],out[8]=a[2],out[9]=a[6],out[10]=a[10],out[11]=a[14],out[12]=a[3],out[13]=a[7],out[14]=a[11],out[15]=a[15];return out},invert:function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b00=a00*a11-a01*a10,b01=a00*a12-a02*a10,b02=a00*a13-a03*a10,b03=a01*a12-a02*a11,b04=a01*a13-a03*a11,b05=a02*a13-a03*a12,b06=a20*a31-a21*a30,b07=a20*a32-a22*a30,b08=a20*a33-a23*a30,b09=a21*a32-a22*a31,b10=a21*a33-a23*a31,b11=a22*a33-a23*a32,det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det)return null;return det=1/det,out[0]=(a11*b11-a12*b10+a13*b09)*det,out[1]=(a02*b10-a01*b11-a03*b09)*det,out[2]=(a31*b05-a32*b04+a33*b03)*det,out[3]=(a22*b04-a21*b05-a23*b03)*det,out[4]=(a12*b08-a10*b11-a13*b07)*det,out[5]=(a00*b11-a02*b08+a03*b07)*det,out[6]=(a32*b02-a30*b05-a33*b01)*det,out[7]=(a20*b05-a22*b02+a23*b01)*det,out[8]=(a10*b10-a11*b08+a13*b06)*det,out[9]=(a01*b08-a00*b10-a03*b06)*det,out[10]=(a30*b04-a31*b02+a33*b00)*det,out[11]=(a21*b02-a20*b04-a23*b00)*det,out[12]=(a11*b07-a10*b09-a12*b06)*det,out[13]=(a00*b09-a01*b07+a02*b06)*det,out[14]=(a31*b01-a30*b03-a32*b00)*det,out[15]=(a20*b03-a21*b01+a22*b00)*det,out},adjoint:function(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];return out[0]=a11*(a22*a33-a23*a32)-a21*(a12*a33-a13*a32)+a31*(a12*a23-a13*a22),out[1]=-(a01*(a22*a33-a23*a32)-a21*(a02*a33-a03*a32)+a31*(a02*a23-a03*a22)),out[2]=a01*(a12*a33-a13*a32)-a11*(a02*a33-a03*a32)+a31*(a02*a13-a03*a12),out[3]=-(a01*(a12*a23-a13*a22)-a11*(a02*a23-a03*a22)+a21*(a02*a13-a03*a12)),out[4]=-(a10*(a22*a33-a23*a32)-a20*(a12*a33-a13*a32)+a30*(a12*a23-a13*a22)),out[5]=a00*(a22*a33-a23*a32)-a20*(a02*a33-a03*a32)+a30*(a02*a23-a03*a22),out[6]=-(a00*(a12*a33-a13*a32)-a10*(a02*a33-a03*a32)+a30*(a02*a13-a03*a12)),out[7]=a00*(a12*a23-a13*a22)-a10*(a02*a23-a03*a22)+a20*(a02*a13-a03*a12),out[8]=a10*(a21*a33-a23*a31)-a20*(a11*a33-a13*a31)+a30*(a11*a23-a13*a21),out[9]=-(a00*(a21*a33-a23*a31)-a20*(a01*a33-a03*a31)+a30*(a01*a23-a03*a21)),out[10]=a00*(a11*a33-a13*a31)-a10*(a01*a33-a03*a31)+a30*(a01*a13-a03*a11),out[11]=-(a00*(a11*a23-a13*a21)-a10*(a01*a23-a03*a21)+a20*(a01*a13-a03*a11)),out[12]=-(a10*(a21*a32-a22*a31)-a20*(a11*a32-a12*a31)+a30*(a11*a22-a12*a21)),out[13]=a00*(a21*a32-a22*a31)-a20*(a01*a32-a02*a31)+a30*(a01*a22-a02*a21),out[14]=-(a00*(a11*a32-a12*a31)-a10*(a01*a32-a02*a31)+a30*(a01*a12-a02*a11)),out[15]=a00*(a11*a22-a12*a21)-a10*(a01*a22-a02*a21)+a20*(a01*a12-a02*a11),out},determinant:function(a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15];return(a00*a11-a01*a10)*(a22*a33-a23*a32)-(a00*a12-a02*a10)*(a21*a33-a23*a31)+(a00*a13-a03*a10)*(a21*a32-a22*a31)+(a01*a12-a02*a11)*(a20*a33-a23*a30)-(a01*a13-a03*a11)*(a20*a32-a22*a30)+(a02*a13-a03*a12)*(a20*a31-a21*a30)},multiply:function(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],a30=a[12],a31=a[13],a32=a[14],a33=a[15],b0=b[0],b1=b[1],b2=b[2],b3=b[3];return out[0]=b0*a00+b1*a10+b2*a20+b3*a30,out[1]=b0*a01+b1*a11+b2*a21+b3*a31,out[2]=b0*a02+b1*a12+b2*a22+b3*a32,out[3]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[4],b1=b[5],b2=b[6],b3=b[7],out[4]=b0*a00+b1*a10+b2*a20+b3*a30,out[5]=b0*a01+b1*a11+b2*a21+b3*a31,out[6]=b0*a02+b1*a12+b2*a22+b3*a32,out[7]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[8],b1=b[9],b2=b[10],b3=b[11],out[8]=b0*a00+b1*a10+b2*a20+b3*a30,out[9]=b0*a01+b1*a11+b2*a21+b3*a31,out[10]=b0*a02+b1*a12+b2*a22+b3*a32,out[11]=b0*a03+b1*a13+b2*a23+b3*a33,b0=b[12],b1=b[13],b2=b[14],b3=b[15],out[12]=b0*a00+b1*a10+b2*a20+b3*a30,out[13]=b0*a01+b1*a11+b2*a21+b3*a31,out[14]=b0*a02+b1*a12+b2*a22+b3*a32,out[15]=b0*a03+b1*a13+b2*a23+b3*a33,out},translate:function(out,a,v){var a00,a01,a02,a03,a10,a11,a12,a13,a20,a21,a22,a23,x=v[0],y=v[1],z=v[2];a===out?(out[12]=a[0]*x+a[4]*y+a[8]*z+a[12],out[13]=a[1]*x+a[5]*y+a[9]*z+a[13],out[14]=a[2]*x+a[6]*y+a[10]*z+a[14],out[15]=a[3]*x+a[7]*y+a[11]*z+a[15]):(a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11],out[0]=a00,out[1]=a01,out[2]=a02,out[3]=a03,out[4]=a10,out[5]=a11,out[6]=a12,out[7]=a13,out[8]=a20,out[9]=a21,out[10]=a22,out[11]=a23,out[12]=a00*x+a10*y+a20*z+a[12],out[13]=a01*x+a11*y+a21*z+a[13],out[14]=a02*x+a12*y+a22*z+a[14],out[15]=a03*x+a13*y+a23*z+a[15]);return out},scale:function(out,a,v){var x=v[0],y=v[1],z=v[2];return out[0]=a[0]*x,out[1]=a[1]*x,out[2]=a[2]*x,out[3]=a[3]*x,out[4]=a[4]*y,out[5]=a[5]*y,out[6]=a[6]*y,out[7]=a[7]*y,out[8]=a[8]*z,out[9]=a[9]*z,out[10]=a[10]*z,out[11]=a[11]*z,out[12]=a[12],out[13]=a[13],out[14]=a[14],out[15]=a[15],out},rotate:rotate_1,rotateX:function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a10=a[4],a11=a[5],a12=a[6],a13=a[7],a20=a[8],a21=a[9],a22=a[10],a23=a[11];a!==out&&(out[0]=a[0],out[1]=a[1],out[2]=a[2],out[3]=a[3],out[12]=a[12],out[13]=a[13],out[14]=a[14],out[15]=a[15]);return out[4]=a10*c+a20*s,out[5]=a11*c+a21*s,out[6]=a12*c+a22*s,out[7]=a13*c+a23*s,out[8]=a20*c-a10*s,out[9]=a21*c-a11*s,out[10]=a22*c-a12*s,out[11]=a23*c-a13*s,out},rotateY:function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a00=a[0],a01=a[1],a02=a[2],a03=a[3],a20=a[8],a21=a[9],a22=a[10],a23=a[11];a!==out&&(out[4]=a[4],out[5]=a[5],out[6]=a[6],out[7]=a[7],out[12]=a[12],out[13]=a[13],out[14]=a[14],out[15]=a[15]);return out[0]=a00*c-a20*s,out[1]=a01*c-a21*s,out[2]=a02*c-a22*s,out[3]=a03*c-a23*s,out[8]=a00*s+a20*c,out[9]=a01*s+a21*c,out[10]=a02*s+a22*c,out[11]=a03*s+a23*c,out},rotateZ:function(out,a,rad){var s=Math.sin(rad),c=Math.cos(rad),a00=a[0],a01=a[1],a02=a[2],a03=a[3],a10=a[4],a11=a[5],a12=a[6],a13=a[7];a!==out&&(out[8]=a[8],out[9]=a[9],out[10]=a[10],out[11]=a[11],out[12]=a[12],out[13]=a[13],out[14]=a[14],out[15]=a[15]);return out[0]=a00*c+a10*s,out[1]=a01*c+a11*s,out[2]=a02*c+a12*s,out[3]=a03*c+a13*s,out[4]=a10*c-a00*s,out[5]=a11*c-a01*s,out[6]=a12*c-a02*s,out[7]=a13*c-a03*s,out},fromRotation:fromRotation_1,fromRotationTranslation:function(out,q,v){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,xy=x*y2,xz=x*z2,yy=y*y2,yz=y*z2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2;return out[0]=1-(yy+zz),out[1]=xy+wz,out[2]=xz-wy,out[3]=0,out[4]=xy-wz,out[5]=1-(xx+zz),out[6]=yz+wx,out[7]=0,out[8]=xz+wy,out[9]=yz-wx,out[10]=1-(xx+yy),out[11]=0,out[12]=v[0],out[13]=v[1],out[14]=v[2],out[15]=1,out},fromScaling:function(out,v){return out[0]=v[0],out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=v[1],out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=v[2],out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromTranslation:function(out,v){return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=v[0],out[13]=v[1],out[14]=v[2],out[15]=1,out},fromXRotation:function(out,rad){var s=Math.sin(rad),c=Math.cos(rad);return out[0]=1,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=c,out[6]=s,out[7]=0,out[8]=0,out[9]=-s,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromYRotation:function(out,rad){var s=Math.sin(rad),c=Math.cos(rad);return out[0]=c,out[1]=0,out[2]=-s,out[3]=0,out[4]=0,out[5]=1,out[6]=0,out[7]=0,out[8]=s,out[9]=0,out[10]=c,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromZRotation:function(out,rad){var s=Math.sin(rad),c=Math.cos(rad);return out[0]=c,out[1]=s,out[2]=0,out[3]=0,out[4]=-s,out[5]=c,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=1,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},fromQuat:function(out,q){var x=q[0],y=q[1],z=q[2],w=q[3],x2=x+x,y2=y+y,z2=z+z,xx=x*x2,yx=y*x2,yy=y*y2,zx=z*x2,zy=z*y2,zz=z*z2,wx=w*x2,wy=w*y2,wz=w*z2;return out[0]=1-yy-zz,out[1]=yx+wz,out[2]=zx-wy,out[3]=0,out[4]=yx-wz,out[5]=1-xx-zz,out[6]=zy+wx,out[7]=0,out[8]=zx+wy,out[9]=zy-wx,out[10]=1-xx-yy,out[11]=0,out[12]=0,out[13]=0,out[14]=0,out[15]=1,out},frustum:function(out,left,right,bottom,top,near,far){var rl=1/(right-left),tb=1/(top-bottom),nf=1/(near-far);return out[0]=2*near*rl,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=2*near*tb,out[6]=0,out[7]=0,out[8]=(right+left)*rl,out[9]=(top+bottom)*tb,out[10]=(far+near)*nf,out[11]=-1,out[12]=0,out[13]=0,out[14]=far*near*2*nf,out[15]=0,out},perspective:function(out,fovy,aspect,near,far){var f=1/Math.tan(fovy/2),nf=1/(near-far);return out[0]=f/aspect,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=f,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=(far+near)*nf,out[11]=-1,out[12]=0,out[13]=0,out[14]=2*far*near*nf,out[15]=0,out},perspectiveFromFieldOfView:function(out,fov,near,far){var upTan=Math.tan(fov.upDegrees*Math.PI/180),downTan=Math.tan(fov.downDegrees*Math.PI/180),leftTan=Math.tan(fov.leftDegrees*Math.PI/180),rightTan=Math.tan(fov.rightDegrees*Math.PI/180),xScale=2/(leftTan+rightTan),yScale=2/(upTan+downTan);return out[0]=xScale,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=yScale,out[6]=0,out[7]=0,out[8]=-(leftTan-rightTan)*xScale*.5,out[9]=(upTan-downTan)*yScale*.5,out[10]=far/(near-far),out[11]=-1,out[12]=0,out[13]=0,out[14]=far*near/(near-far),out[15]=0,out},ortho:function(out,left,right,bottom,top,near,far){var lr=1/(left-right),bt=1/(bottom-top),nf=1/(near-far);return out[0]=-2*lr,out[1]=0,out[2]=0,out[3]=0,out[4]=0,out[5]=-2*bt,out[6]=0,out[7]=0,out[8]=0,out[9]=0,out[10]=2*nf,out[11]=0,out[12]=(left+right)*lr,out[13]=(top+bottom)*bt,out[14]=(far+near)*nf,out[15]=1,out},lookAt:lookAt_1,str:function(a){return"mat4("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+", "+a[9]+", "+a[10]+", "+a[11]+", "+a[12]+", "+a[13]+", "+a[14]+", "+a[15]+")"}};const cameraState$1={view:glMat4.identity(new Float32Array(16)),projection:glMat4.identity(new Float32Array(16)),matrix:glMat4.identity(new Float32Array(16)),near:1,far:1300,up:[0,0,1],eye:new Float32Array(3),position:[150,250,200],target:[0,0,0],fov:Math.PI/4,aspect:1,viewport:[0,0,0,0],zoom:1,projectionType:"orthographic"},setProjection$1=(camera,input)=>{const{width:width,height:height}=input,aspect=width/height,viewport=[0,0,width,height],multiplier=camera.zoom,left=-width*multiplier,right=width*multiplier,bottom=-height*multiplier,top=height*multiplier;return{projection:glMat4.ortho([],left,right,bottom,top,camera.near,camera.far),aspect:aspect,viewport:viewport}};var orthographicCamera=Object.freeze({__proto__:null,cameraState:cameraState$1,cameraProps:{},setProjection:setProjection$1});const cameraState={view:glMat4.identity(new Float32Array(16)),projection:glMat4.identity(new Float32Array(16)),matrix:glMat4.identity(new Float32Array(16)),near:1,far:18e3,up:[0,0,1],eye:new Float32Array(3),position:[450,550,700],target:[0,0,0],fov:Math.PI/4,aspect:1,viewport:[0,0,0,0],projectionType:"perspective"},cameraProps={},defaults$1=Object.assign({},cameraState,cameraProps),setProjection=(output,camera,input)=>{const aspect=input.width/input.height,projection=glMat4.perspective(glMat4.identity([]),camera.fov,aspect,camera.near,camera.far),viewport=[0,0,input.width,input.height],out=output||{};return out.projection=projection,out.aspect=aspect,out.viewport=viewport,out};var perspectiveCamera=Object.freeze({__proto__:null,cameraState:cameraState,cameraProps:cameraProps,defaults:defaults$1,setProjection:setProjection,update:(output,camera)=>{camera||(camera=output);const{position:position,target:target,up:up}=camera,offset=glVec3.subtract([],position,target),newPosition=glVec3.add(glVec3.create(),target,offset),newView=glMat4.lookAt(glMat4.create(),newPosition,target,up),out=output||{};return out.position=newPosition,out.view=newView,out}});var camera=Object.freeze({__proto__:null,fromOrthographicToPerspective:orthographicCamera=>{const{near:near,far:far,fov:fov}=orthographicCamera,{viewport:viewport}=orthographicCamera,projection=setProjection(orthographicCamera,{width:viewport[2],height:viewport[3]}),{projectionType:projectionType}=cameraState;return Object.assign({},orthographicCamera,projection,{projectionType:projectionType},{near:near,far:far,fov:fov})},fromPerspectiveToOrthographic:perspectiveCamera=>{const{fov:fov,aspect:aspect}=perspectiveCamera,distance=.3*glVec3.length(glVec3.subtract([],perspectiveCamera.position,perspectiveCamera.target)),width=Math.tan(fov)*distance*aspect,height=Math.tan(fov)*distance,{near:near,far:far,viewport:viewport}=perspectiveCamera,projectionType=cameraState$1.projectionType,projection=setProjection$1({zoom:1,near:near,far:far},{width:width,height:height});return Object.assign({},orthographicCamera,perspectiveCamera,projection,{projectionType:projectionType,viewport:viewport})},toPerspectiveView:({camera:camera})=>{const offsetToTarget=glVec3.distance(camera.position,camera.target),position=[offsetToTarget,offsetToTarget,offsetToTarget];return{view:glMat4.lookAt(glMat4.create(),position,camera.target,camera.up),position:position}},toPresetView:(viewName,{camera:camera})=>{const offsetToTarget=glVec3.distance(camera.position,camera.target),position=glVec3.add(glVec3.create(),{top:[0,-1e-6,1],bottom:[0,0,-1],front:[0,1,0],back:[0,-1,0],left:[-1,0,0],right:[1,0,0],undefined:[0,0,0]}[viewName].map((x=>x*offsetToTarget)),camera.target);return{view:glMat4.lookAt(glMat4.create(),position,camera.target,camera.up),position:position}}}),index$2=Object.freeze({__proto__:null,camera:camera,orthographic:orthographicCamera,perspective:perspectiveCamera});const makeDrawGrid=(regl,params={})=>{const positions=[],defaults={visuals:{color:[0,0,1,1],fadeOut:!1},ticks:1,size:[16,16],centered:!1,lineWidth:2},visuals=Object.assign({},defaults.visuals,params.visuals||{}),{fadeOut:fadeOut,color:color}=visuals,{size:size,ticks:ticks,centered:centered,lineWidth:lineWidth}=Object.assign({},defaults,params),width=size[0],length=size[1];if(centered){const halfWidth=.5*width,halfLength=.5*length,widthStart=-halfWidth+halfWidth%ticks,widthEnd=-widthStart,lengthStart=-halfLength+halfLength%ticks,lengthEnd=-lengthStart,skipEvery=0;for(let i=widthStart,j=0;i<=widthEnd;i+=ticks,j+=1)j%skipEvery!=0&&(positions.push(lengthStart,i,0),positions.push(lengthEnd,i,0),positions.push(lengthStart,i,0));for(let i=lengthStart,j=0;i<=lengthEnd;i+=ticks,j+=1)j%skipEvery!=0&&(positions.push(i,widthStart,0),positions.push(i,widthEnd,0),positions.push(i,widthStart,0))}else{for(let i=.5*-width;i<=.5*width;i+=ticks)positions.push(.5*-length,i,0),positions.push(.5*length,i,0),positions.push(.5*-length,i,0);for(let i=.5*-length;i<=.5*length;i+=ticks)positions.push(i,.5*-width,0),positions.push(i,.5*width,0),positions.push(i,.5*-width,0)}return regl({vert:"precision mediump float;\n\n uniform float camNear, camFar;\n uniform mat4 model, view, projection;\n\n attribute vec3 position;\n varying vec3 fragNormal, fragPosition;\n varying vec4 worldPosition;\n\n void main() {\n fragPosition = position;\n worldPosition = model * vec4(position, 1);\n vec4 glPosition = projection * view * worldPosition;\n gl_Position = glPosition;\n }",frag:"precision mediump float;\n uniform vec4 color;\n varying vec3 fragNormal, fragPosition;\n varying vec4 worldPosition;\n\n uniform vec4 fogColor;\n uniform bool fadeOut;\n void main() {\n float dist = .5;\n if(fadeOut){\n dist = distance( vec2(0.,0.), vec2(worldPosition.x, worldPosition.y));\n dist *= 0.0025;\n dist = sqrt(dist);\n }\n\n gl_FragColor = mix(color, fogColor, dist);\n }\n ",attributes:{position:regl.buffer(positions)},count:positions.length/3,uniforms:{model:(context,props)=>props&&props.model?props.model:glMat4.identity([]),color:(context,props)=>props&&props.color?props.color:color,fogColor:(context,props)=>props&&props.color?[props.color[0],props.color[1],props.color[2],0]:[color[0],color[1],color[2],0],fadeOut:(context,props)=>props&&void 0!==props.fadeOut?props.fadeOut:fadeOut},lineWidth:(context,props)=>Math.min(props&&props.lineWidth?props.lineWidth:lineWidth,regl.limits.lineWidthDims[1]),primitive:"lines",cull:{enable:!0,face:"front"},polygonOffset:{enable:!0,offset:{factor:1,units:10*Math.random()}},blend:{enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}})},meshColor=[0,.6,1,1];var renderDefaults=Object.freeze({__proto__:null,background:[1,1,1,1],meshColor:meshColor,lightColor:[1,1,1,1],lightDirection:[.2,.2,1],lightPosition:[100,200,100],ambientLightAmount:.3,diffuseLightAmount:.89,specularLightAmount:.16,materialShininess:8});var index$1=Object.freeze({__proto__:null,drawGrid:(regl,params)=>{const{size:size,ticks:ticks}=Object.assign({},{size:[50,50],ticks:[10,1]},params),drawMainGrid=makeDrawGrid(regl,{size:size,ticks:ticks[0]}),drawSubGrid=makeDrawGrid(regl,{size:size,ticks:ticks[1]});return props=>{drawMainGrid(props),drawSubGrid({color:props.subColor,fadeOut:props.fadeOut})}},drawAxis:(regl,params)=>{let{size:size,xColor:xColor,yColor:yColor,zColor:zColor,lineWidth:lineWidth,alwaysVisible:alwaysVisible}=Object.assign({},{xColor:[1,0,0,1],yColor:[0,1,0,1],zColor:[0,0,1,1],size:10,lineWidth:3,alwaysVisible:!0},params);lineWidth>regl.limits.lineWidthDims[1]&&(lineWidth=regl.limits.lineWidthDims[1]);const points=[0,0,0,size,0,0],commandParams={frag:"precision mediump float;\n uniform vec4 color;\n void main() {\n gl_FragColor = color;\n }",vert:"\n precision mediump float;\n attribute vec3 position;\n uniform mat4 model, view, projection;\n void main() {\n gl_Position = projection * view * model * vec4(position, 1);\n }",uniforms:{model:(context,props)=>props&&props.model?props.model:glMat4.identity([]),color:(context,props)=>props.color,angle:(contet,props)=>props.angle},attributes:{position:points},count:points.length/3,primitive:"line loop",lineWidth:lineWidth,depth:{enable:!alwaysVisible}},xAxisModel=glMat4.identity([]),yAxisModel=glMat4.rotateZ(glMat4.create(),glMat4.identity([]),Math.PI/2),zAxisModel=glMat4.rotateY(glMat4.create(),glMat4.identity([]),-Math.PI/2),single=regl(commandParams);return props=>{const defaults={model:glMat4.identity([])};return props=Object.assign({},defaults,props),single([{color:xColor,model:glMat4.multiply(glMat4.create(),props.model,xAxisModel)},{color:yColor,model:glMat4.multiply(glMat4.create(),props.model,yAxisModel)},{color:zColor,model:glMat4.multiply(glMat4.create(),props.model,zAxisModel)}])}},drawMesh:(regl,params={extras:{}})=>{const defaults={useVertexColors:!0,dynamicCulling:!0,geometry:void 0,color:meshColor,visuals:{}},{geometry:geometry,dynamicCulling:dynamicCulling,useVertexColors:useVertexColors,color:color,visuals:visuals}=Object.assign({},defaults,params),ambientOcclusion=regl.buffer([]),hasIndices=!!(geometry.indices&&geometry.indices.length>0),hasNormals=!!(geometry.normals&&geometry.normals.length>0),transparent="transparent"in visuals&&visuals.transparent,hasVertexColors=!!(useVertexColors&&geometry.colors&&geometry.colors.length>0),transforms=geometry.transforms||glMat4.create(),flip=glMat4.determinant(transforms)<0,cullFace=dynamicCulling&&flip?"front":"back",vert=hasVertexColors?"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection, unormal;\n\nattribute vec3 position, normal;\nattribute vec4 color;\n\nattribute float ao;\nvarying float ambientAo;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\nvarying vec4 vColor;\n\nvoid main() {\n surfacePosition = (unormal * vec4(position, 1.0)).xyz;\n surfaceNormal = normalize((unormal * vec4(normal, 1.0)).xyz); //vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n //gl_Position = projection * view * worldSpacePosition;\n\n vColor = color;\n\n //ambientAo = (1. - ao) * (0.5 * max(normal.x, 0.) + 0.5);\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n //gl_Position = zBufferAdjust(glPosition, camNear, camFar);\n}\n":"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\n\nvoid main() {\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n",frag=hasVertexColors?"\nprecision mediump float;\nvarying vec3 surfaceNormal, surfacePosition;\n\nuniform float ambientLightAmount;\nuniform float diffuseLightAmount;\nuniform float specularLightAmount;\n\nuniform vec3 lightDirection;\nuniform vec4 lightColor;\nuniform vec3 opacity;\nuniform float uMaterialShininess;\n\nvarying vec4 vColor;\nuniform vec4 ucolor;\nuniform float vColorToggler;\n\nuniform vec2 printableArea;\nvec4 errorColor = vec4(0.15, 0.15, 0.15, 0.3);//vec4(0.15, 0.15, 0.15, 0.3);\nvarying vec4 _worldSpacePosition;\nvarying float ambientAo;\n\nvoid main () {\n vec4 depth = gl_FragCoord;\n vec4 endColor = vColor * vColorToggler + ucolor * (1.0 - vColorToggler);\n\n vec3 ambient = ambientLightAmount * endColor.rgb ; //ambientAo * \n\n float diffuseWeight = dot(surfaceNormal, lightDirection);\n vec3 diffuse = diffuseLightAmount * endColor.rgb * clamp(diffuseWeight , 0.0, 1.0 );\n\n //specular\n \n vec4 specularColor = vec4(lightColor);\n vec3 eyeDirection = normalize(surfacePosition.xyz);\n vec3 reflectionDirection = reflect(-lightDirection, -surfaceNormal);\n float specularLightWeight = pow(max(dot(reflectionDirection, eyeDirection), 0.0), uMaterialShininess);\n vec3 specular = specularColor.rgb * specularLightWeight * specularLightAmount;\n\n gl_FragColor = vec4((ambient + diffuse + specular), endColor.a);\n}\n":"\nprecision mediump float;\nvarying vec3 surfaceNormal;\nuniform float ambientLightAmount;\nuniform float diffuseLightAmount;\nuniform vec4 ucolor;\nuniform vec3 lightDirection;\nuniform vec3 opacity;\n\nvarying vec4 _worldSpacePosition;\n\nuniform vec2 printableArea;\n\nvec4 errorColor = vec4(0.15, 0.15, 0.15, 0.3);\n\nvoid main () {\n vec4 depth = gl_FragCoord;\n\n float v = 0.8; // shadow value\n vec4 endColor = ucolor;\n\n vec3 ambient = ambientLightAmount * endColor.rgb;\n float cosTheta = dot(surfaceNormal, lightDirection);\n vec3 diffuse = diffuseLightAmount * endColor.rgb * clamp(cosTheta , 0.0, 1.0 );\n\n float cosTheta2 = dot(surfaceNormal, vec3(-lightDirection.x, -lightDirection.y, lightDirection.z));\n vec3 diffuse2 = diffuseLightAmount * endColor.rgb * clamp(cosTheta2 , 0.0, 1.0 );\n\n gl_FragColor = vec4((ambient + diffuse + diffuse2 * v), endColor.a);\n}",modelMatrixInv=glMat4.invert(glMat4.create(),transforms);let commandParams={primitive:"triangles",vert:vert,frag:frag,uniforms:{model:(context,props)=>transforms,ucolor:(context,props)=>props&&props.color?props.color:color,vColorToggler:(context,props)=>props&&props.useVertexColors&&!0===props.useVertexColors?1:0,unormal:(context,props)=>{const modelViewMatrix=glMat4.invert(glMat4.create(),props.camera.view);return glMat4.multiply(modelViewMatrix,modelMatrixInv,modelViewMatrix),glMat4.transpose(modelViewMatrix,modelViewMatrix),modelViewMatrix}},attributes:{position:regl.buffer({usage:"static",type:"float",data:geometry.positions}),ao:ambientOcclusion},cull:{enable:!0,face:cullFace}};return transparent&&(commandParams.blend={enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}),geometry.cells?commandParams.elements=geometry.cells:hasIndices?commandParams.elements=regl.elements({usage:"static",type:"uint16",data:geometry.indices}):geometry.triangles?commandParams.elements=geometry.triangles:commandParams.count=geometry.positions.length/3,hasNormals&&(commandParams.attributes.normal=regl.buffer({usage:"static",type:"float",data:geometry.normals})),hasVertexColors&&(commandParams.attributes.color=regl.buffer({usage:"static",type:"float",data:geometry.colors})),commandParams=Object.assign({},commandParams,params.extras),regl(commandParams)},drawLines:(regl,params={})=>{const defaults={color:meshColor,geometry:void 0};let{geometry:geometry,color:color,transparent:transparent}=Object.assign({},defaults,params);"color"in geometry&&(color=geometry.color);const hasIndices=!!(geometry.indices&&geometry.indices.length>0),hasNormals=!!(geometry.normals&&geometry.normals.length>0),hasVertexColors=!!(geometry.colors&&geometry.colors.length>0),commandParams={primitive:"lines",vert:hasVertexColors?"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\nattribute vec4 color;\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\nvarying vec4 vColor;\n\nvoid main() {\n vColor = color;\n\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n":"\nprecision mediump float;\n\nuniform float camNear, camFar;\nuniform mat4 model, view, projection;\n\nattribute vec3 position, normal;\n\n\nvarying vec3 surfaceNormal, surfacePosition;\nvarying vec4 _worldSpacePosition;\n\n\nvoid main() {\n\n\n surfacePosition = position;\n surfaceNormal = normal;\n vec4 worldSpacePosition = model * vec4(position, 1);\n _worldSpacePosition = worldSpacePosition;\n\n vec4 glPosition = projection * view * model * vec4(position, 1);\n gl_Position = glPosition;\n}\n",frag:hasVertexColors?"\nprecision mediump float;\nvarying vec4 vColor;\n\nvoid main () {\n gl_FragColor = vColor;\n}\n":"\nprecision mediump float;\nuniform vec4 ucolor;\n\nvoid main () {\n gl_FragColor = ucolor;\n}\n",uniforms:{model:(context,props)=>props.model||geometry.transforms||glMat4.create(),ucolor:(context,props)=>props&&props.color?props.color:color},attributes:{position:regl.buffer({usage:"static",type:"float",data:geometry.positions})}};return transparent&&(commandParams.blend={enable:!0,func:{src:"src alpha",dst:"one minus src alpha"}}),hasVertexColors&&(commandParams.attributes.color=regl.buffer({usage:"static",type:"float",data:geometry.colors})),hasIndices&&(commandParams.elements=regl.elements({usage:"static",type:"uint16",data:geometry.indices})),hasNormals&&(commandParams.attributes.normal=regl.buffer({usage:"static",type:"float",data:geometry.normals})),regl(commandParams)}}),projectMat4=function(out,vec,m){var x=vec[0],y=vec[1],z=vec[2],a00=m[0],a01=m[1],a02=m[2],a03=m[3],a10=m[4],a11=m[5],a12=m[6],a13=m[7],a20=m[8],a21=m[9],a22=m[10],a23=m[11],a30=m[12],a31=m[13],a32=m[14],a33=m[15],lw=1/(x*a03+y*a13+z*a23+a33);return out[0]=(x*a00+y*a10+z*a20+a30)*lw,out[1]=(x*a01+y*a11+z*a21+a31)*lw,out[2]=(x*a02+y*a12+z*a22+a32)*lw,out};var transform=projectMat4,cameraUnproject=function(out,vec,viewport,invProjectionView){var viewX=viewport[0],viewY=viewport[1],viewWidth=viewport[2],viewHeight=viewport[3],x=vec[0],y=vec[1],z=vec[2];return x-=viewX,y=viewHeight-y-1,y-=viewY,out[0]=2*x/viewWidth-1,out[1]=2*y/viewHeight-1,out[2]=2*z-1,transform(out,out,invProjectionView)}
8
+ /**
9
+ * JSCAD Utility functions for arrays
10
+ * @module @jscad/array-utils
11
+ * @version 3.0.1-alpha.0
12
+ * @license MIT
13
+ */;const flatten=arr=>arr.reduce(((acc,val)=>Array.isArray(val)?acc.concat(flatten(val)):acc.concat(val)),[]),computeBounds=(...geometries)=>{let bbox;(geometries=flatten(geometries)).forEach((geometry=>{let gbbox=(positions=>{if(0===positions.length)return[[0,0,0],[0,0,0]];const nested=Array.isArray(positions)&&Array.isArray(positions[0]),dimensions=nested?positions[0].length:3,min=new Array(dimensions),max=new Array(dimensions);for(let i=0;i<dimensions;i+=1)min[i]=1/0,max[i]=-1/0;if(nested)positions.forEach((position=>{for(let i=0;i<dimensions;i+=1){const _position=nested?position[i]:position;max[i]=_position>max[i]?_position:max[i],min[i]=_position<min[i]?_position:min[i]}}));else for(let j=0;j<positions.length;j+=dimensions)for(let i=0;i<dimensions;i+=1){const _position=positions[i+j];max[i]=_position>max[i]?_position:max[i],min[i]=_position<min[i]?_position:min[i]}return[min,max]})(geometry.positions);gbbox=gbbox.map((bounds=>glVec3.transformMat4(bounds,bounds,geometry.transforms))),bbox?(glVec3.min(bbox[0],bbox[0],gbbox[0]),glVec3.max(bbox[1],bbox[1],gbbox[1])):bbox=gbbox}));const min=glVec3.min(glVec3.create(),bbox[1],bbox[0]),max=glVec3.max(glVec3.create(),bbox[1],bbox[0]),size=glVec3.subtract(glVec3.create(),max,min);let center=glVec3.scale(glVec3.create(),size,.5);center=glVec3.add(center,min,center);return{dia:glVec3.distance(center,max),center:[...center],min:[...min],max:[...max],size:[...size]}},{max:max,min:min,sqrt:sqrt,PI:PI,sin:sin,cos:cos,atan2:atan2}=Math,controlsProps={limits:{minDistance:.01,maxDistance:1e4},drag:.27,EPS:1e-6,zoomToFit:{auto:!0,targets:"all",tightness:1.5},userControl:{zoom:!0,zoomSpeed:1,rotate:!0,rotateSpeed:1,pan:!0,panSpeed:1},autoRotate:{enabled:!1,speed:1},autoAdjustPlanes:!0},controlsState={thetaDelta:0,phiDelta:0,scale:1},defaults=Object.assign({},controlsState,controlsProps);var orbitControls=Object.freeze({__proto__:null,controlsProps:controlsProps,controlsState:controlsState,defaults:defaults,update:({controls:controls,camera:camera},output)=>{const{EPS:EPS,drag:drag}=controls,{position:position,target:target}=camera,up=controls.up?controls.up:camera.up;let curThetaDelta=controls.thetaDelta;const curPhiDelta=controls.phiDelta,curScale=controls.scale,offset=glVec3.subtract([],position,target);let theta,phi;1===up[2]?(theta=atan2(offset[0],offset[1]),phi=atan2(sqrt(offset[0]*offset[0]+offset[1]*offset[1]),offset[2])):(theta=atan2(offset[0],offset[2]),phi=atan2(sqrt(offset[0]*offset[0]+offset[2]*offset[2]),offset[1])),controls.autoRotate.enabled&&controls.userControl.rotate&&(curThetaDelta+=2*Math.PI/60/60*controls.autoRotate.speed),theta+=curThetaDelta,phi+=curPhiDelta,phi=max(EPS,min(PI-EPS,phi));const radius=max(controls.limits.minDistance,min(controls.limits.maxDistance,glVec3.length(offset)*curScale));1===up[2]?(offset[0]=radius*sin(phi)*sin(theta),offset[2]=radius*cos(phi),offset[1]=radius*sin(phi)*cos(theta)):(offset[0]=radius*sin(phi)*sin(theta),offset[1]=radius*cos(phi),offset[2]=radius*sin(phi)*cos(theta));const newPosition=glVec3.add(glVec3.create(),target,offset),newView=glMat4.lookAt(glMat4.create(),newPosition,target,up),dragEffect=1-max(min(drag,1),.01);return{controls:{thetaDelta:curThetaDelta*dragEffect,phiDelta:curPhiDelta*dragEffect,scale:1,changed:glVec3.distance(position,newPosition)>.001},camera:{position:newPosition,view:newView}}},rotate:({controls:controls,camera:camera,speed:speed=1},angle)=>{let{thetaDelta:thetaDelta,phiDelta:phiDelta}=controls;return controls.userControl.rotate&&(thetaDelta+=angle[0]*speed,phiDelta+=angle[1]*speed),{controls:{thetaDelta:thetaDelta,phiDelta:phiDelta},camera:camera}},zoom:({controls:controls,camera:camera,speed:speed=1},zoomDelta=0)=>{let{scale:scale}=controls;if(controls.userControl.zoom&&camera&&void 0!==zoomDelta&&0!==zoomDelta&&!isNaN(zoomDelta)){const newScale=(zoomDelta=zoomDelta/zoomDelta*(0===Math.sign(zoomDelta)?1:Math.sign(zoomDelta))*speed)+controls.scale,newDistance=glVec3.distance(camera.position,camera.target)*newScale;if(newDistance>controls.limits.minDistance&&newDistance<controls.limits.maxDistance&&(scale+=zoomDelta),"orthographic"===camera.projectionType){const distance=.3*glVec3.length(glVec3.subtract([],camera.position,camera.target)),width=Math.tan(camera.fov)*distance*camera.aspect,height=Math.tan(camera.fov)*distance;camera=setProjection$1(camera,{width:width,height:height})}}return{controls:{scale:scale},camera:camera}},pan:({controls:controls,camera:camera,speed:speed=1},delta)=>{const{projection:projection,view:view,viewport:viewport}=camera,combinedProjView=glMat4.multiply([],projection,view),invProjView=glMat4.invert([],combinedProjView),panStart=[viewport[2],viewport[3],0],panEnd=[viewport[2]-delta[0],viewport[3]+delta[1],0],unPanStart=cameraUnproject.unproject([],panStart,viewport,invProjView),unPanEnd=cameraUnproject.unproject([],panEnd,viewport,invProjView),eyeDistance=glVec3.distance(camera.position,camera.eye),offset=glVec3.subtract([],unPanStart,unPanEnd).map((x=>x*speed*eyeDistance*controls.scale));return{controls:controls,camera:{position:glVec3.add(glVec3.create(),camera.position,offset),target:glVec3.add(glVec3.create(),camera.target,offset)}}},zoomToFit:({controls:controls,camera:camera,entities:entities})=>{const{zoomToFit:zoomToFit}=controls;if("all"!==zoomToFit.targets)return{controls:controls,camera:camera};if(0===entities.length)return{controls:controls,camera:camera};const geometries=entities.map((entity=>entity.geometry)),bounds=computeBounds(geometries),{fov:fov,target:target,position:position}=camera,{tightness:tightness}=Object.assign({},zoomToFit,controlsProps.zoomToFit),scaleForIdealDistance=bounds.dia*tightness/Math.tan(fov/2)/glVec3.distance(target,position);return{camera:{target:bounds.center},controls:{scale:scaleForIdealDistance}}},reset:({controls:controls,camera:camera},desiredState)=>({camera:{position:desiredState.camera.position,target:desiredState.camera.target,projection:glMat4.perspective([],camera.fov,camera.aspect,camera.near,camera.far),view:desiredState.camera.view},controls:{thetaDelta:desiredState.controls.thetaDelta,phiDelta:desiredState.controls.phiDelta,scale:desiredState.controls.scale}})}),index=Object.freeze({__proto__:null,orbit:orbitControls});const maxIndex$2=Math.floor(32767.5),polygonColor=(polygon,color)=>{let faceColor=color;return polygon.color&&(faceColor=polygon.color),faceColor&&faceColor.length<4&&faceColor.push(1),faceColor},calculateNormal=polygon=>{if(polygon.plane)return glVec3.clone(polygon.plane);const vertices=polygon.vertices,ba=glVec3.create();glVec3.subtract(ba,vertices[1],vertices[0]);const ca=glVec3.create();glVec3.subtract(ca,vertices[2],vertices[0]);const normal=glVec3.create();return glVec3.cross(normal,ba,ca),glVec3.normalize(normal,normal),normal},maxIndex=Math.floor(32767.5)-2;var reglExports={};!function(module,exports){module.exports=function(){var isTypedArray=function(x){return x instanceof Uint8Array||x instanceof Uint16Array||x instanceof Uint32Array||x instanceof Int8Array||x instanceof Int16Array||x instanceof Int32Array||x instanceof Float32Array||x instanceof Float64Array||x instanceof Uint8ClampedArray},extend=function(base,opts){for(var keys=Object.keys(opts),i=0;i<keys.length;++i)base[keys[i]]=opts[keys[i]];return base},endl="\n";function decodeB64(str){return"undefined"!=typeof atob?atob(str):"base64:"+str}function raise(message){var error=new Error("(regl) "+message);throw console.error(error),error}function check(pred,message){pred||raise(message)}function encolon(message){return message?": "+message:""}function checkParameter(param,possibilities,message){param in possibilities||raise("unknown parameter ("+param+")"+encolon(message)+". possible values: "+Object.keys(possibilities).join())}function checkIsTypedArray(data,message){isTypedArray(data)||raise("invalid parameter type"+encolon(message)+". must be a typed array")}function standardTypeEh(value,type){switch(type){case"number":return"number"==typeof value;case"object":return"object"==typeof value;case"string":return"string"==typeof value;case"boolean":return"boolean"==typeof value;case"function":return"function"==typeof value;case"undefined":return void 0===value;case"symbol":return"symbol"==typeof value}}function checkTypeOf(value,type,message){standardTypeEh(value,type)||raise("invalid parameter type"+encolon(message)+". expected "+type+", got "+typeof value)}function checkNonNegativeInt(value,message){value>=0&&(0|value)===value||raise("invalid parameter type, ("+value+")"+encolon(message)+". must be a nonnegative integer")}function checkOneOf(value,list,message){list.indexOf(value)<0&&raise("invalid value"+encolon(message)+". must be one of: "+list)}var constructorKeys=["gl","canvas","container","attributes","pixelRatio","extensions","optionalExtensions","profile","onDone"];function checkConstructor(obj){Object.keys(obj).forEach((function(key){constructorKeys.indexOf(key)<0&&raise('invalid regl constructor argument "'+key+'". must be one of '+constructorKeys)}))}function leftPad(str,n){for(str+="";str.length<n;)str=" "+str;return str}function ShaderFile(){this.name="unknown",this.lines=[],this.index={},this.hasErrors=!1}function ShaderLine(number,line){this.number=number,this.line=line,this.errors=[]}function ShaderError(fileNumber,lineNumber,message){this.file=fileNumber,this.line=lineNumber,this.message=message}function guessCommand(){var error=new Error,stack=(error.stack||error).toString(),pat=/compileProcedure.*\n\s*at.*\((.*)\)/.exec(stack);if(pat)return pat[1];var pat2=/compileProcedure.*\n\s*at\s+(.*)(\n|$)/.exec(stack);return pat2?pat2[1]:"unknown"}function guessCallSite(){var error=new Error,stack=(error.stack||error).toString(),pat=/at REGLCommand.*\n\s+at.*\((.*)\)/.exec(stack);if(pat)return pat[1];var pat2=/at REGLCommand.*\n\s+at\s+(.*)\n/.exec(stack);return pat2?pat2[1]:"unknown"}function parseSource(source,command){var lines=source.split("\n"),lineNumber=1,fileNumber=0,files={unknown:new ShaderFile,0:new ShaderFile};files.unknown.name=files[0].name=command||guessCommand(),files.unknown.lines.push(new ShaderLine(0,""));for(var i=0;i<lines.length;++i){var line=lines[i],parts=/^\s*#\s*(\w+)\s+(.+)\s*$/.exec(line);if(parts)switch(parts[1]){case"line":var lineNumberInfo=/(\d+)(\s+\d+)?/.exec(parts[2]);lineNumberInfo&&(lineNumber=0|lineNumberInfo[1],lineNumberInfo[2]&&((fileNumber=0|lineNumberInfo[2])in files||(files[fileNumber]=new ShaderFile)));break;case"define":var nameInfo=/SHADER_NAME(_B64)?\s+(.*)$/.exec(parts[2]);nameInfo&&(files[fileNumber].name=nameInfo[1]?decodeB64(nameInfo[2]):nameInfo[2])}files[fileNumber].lines.push(new ShaderLine(lineNumber++,line))}return Object.keys(files).forEach((function(fileNumber){var file=files[fileNumber];file.lines.forEach((function(line){file.index[line.number]=line}))})),files}function parseErrorLog(errLog){var result=[];return errLog.split("\n").forEach((function(errMsg){if(!(errMsg.length<5)){var parts=/^ERROR:\s+(\d+):(\d+):\s*(.*)$/.exec(errMsg);parts?result.push(new ShaderError(0|parts[1],0|parts[2],parts[3].trim())):errMsg.length>0&&result.push(new ShaderError("unknown",0,errMsg))}})),result}function annotateFiles(files,errors){errors.forEach((function(error){var file=files[error.file];if(file){var line=file.index[error.line];if(line)return line.errors.push(error),void(file.hasErrors=!0)}files.unknown.hasErrors=!0,files.unknown.lines[0].errors.push(error)}))}function checkShaderError(gl,shader,source,type,command){if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){var errLog=gl.getShaderInfoLog(shader),typeName=type===gl.FRAGMENT_SHADER?"fragment":"vertex";checkCommandType(source,"string",typeName+" shader source must be a string",command);var files=parseSource(source,command),errors=parseErrorLog(errLog);annotateFiles(files,errors),Object.keys(files).forEach((function(fileNumber){var file=files[fileNumber];if(file.hasErrors){var strings=[""],styles=[""];push("file number "+fileNumber+": "+file.name+"\n","color:red;text-decoration:underline;font-weight:bold"),file.lines.forEach((function(line){if(line.errors.length>0){push(leftPad(line.number,4)+"| ","background-color:yellow; font-weight:bold"),push(line.line+endl,"color:red; background-color:yellow; font-weight:bold");var offset=0;line.errors.forEach((function(error){var message=error.message,token=/^\s*'(.*)'\s*:\s*(.*)$/.exec(message);if(token){var tokenPat=token[1];message=token[2],"assign"===tokenPat&&(tokenPat="="),offset=Math.max(line.line.indexOf(tokenPat,offset),0)}else offset=0;push(leftPad("| ",6)),push(leftPad("^^^",offset+3)+endl,"font-weight:bold"),push(leftPad("| ",6)),push(message+endl,"font-weight:bold")})),push(leftPad("| ",6)+endl)}else push(leftPad(line.number,4)+"| "),push(line.line+endl,"color:red")})),"undefined"==typeof document||window.chrome?console.log(strings.join("")):(styles[0]=strings.join("%c"),console.log.apply(console,styles))}function push(str,style){strings.push(str),styles.push(style||"")}})),check.raise("Error compiling "+typeName+" shader, "+files[0].name)}}function checkLinkError(gl,program,fragShader,vertShader,command){if(!gl.getProgramParameter(program,gl.LINK_STATUS)){var errLog=gl.getProgramInfoLog(program),fragParse=parseSource(fragShader,command),header='Error linking program with vertex shader, "'+parseSource(vertShader,command)[0].name+'", and fragment shader "'+fragParse[0].name+'"';"undefined"!=typeof document?console.log("%c"+header+endl+"%c"+errLog,"color:red;text-decoration:underline;font-weight:bold","color:red"):console.log(header+endl+errLog),check.raise(header)}}function saveCommandRef(object){object._commandRef=guessCommand()}function saveDrawCommandInfo(opts,uniforms,attributes,stringStore){function id(str){return str?stringStore.id(str):0}function addProps(dict,set){Object.keys(set).forEach((function(u){dict[stringStore.id(u)]=!0}))}saveCommandRef(opts),opts._fragId=id(opts.static.frag),opts._vertId=id(opts.static.vert);var uniformSet=opts._uniformSet={};addProps(uniformSet,uniforms.static),addProps(uniformSet,uniforms.dynamic);var attributeSet=opts._attributeSet={};addProps(attributeSet,attributes.static),addProps(attributeSet,attributes.dynamic),opts._hasCount="count"in opts.static||"count"in opts.dynamic||"elements"in opts.static||"elements"in opts.dynamic}function commandRaise(message,command){var callSite=guessCallSite();raise(message+" in command "+(command||guessCommand())+("unknown"===callSite?"":" called from "+callSite))}function checkCommand(pred,message,command){pred||commandRaise(message,command||guessCommand())}function checkParameterCommand(param,possibilities,message,command){param in possibilities||commandRaise("unknown parameter ("+param+")"+encolon(message)+". possible values: "+Object.keys(possibilities).join(),command||guessCommand())}function checkCommandType(value,type,message,command){standardTypeEh(value,type)||commandRaise("invalid parameter type"+encolon(message)+". expected "+type+", got "+typeof value,command||guessCommand())}function checkOptional(block){block()}function checkFramebufferFormat(attachment,texFormats,rbFormats){attachment.texture?checkOneOf(attachment.texture._texture.internalformat,texFormats,"unsupported texture format for attachment"):checkOneOf(attachment.renderbuffer._renderbuffer.format,rbFormats,"unsupported renderbuffer format for attachment")}var GL_CLAMP_TO_EDGE=33071,GL_NEAREST=9728,GL_NEAREST_MIPMAP_NEAREST=9984,GL_LINEAR_MIPMAP_NEAREST=9985,GL_NEAREST_MIPMAP_LINEAR=9986,GL_LINEAR_MIPMAP_LINEAR=9987,GL_UNSIGNED_BYTE=5121,GL_SHORT=5122,GL_UNSIGNED_SHORT=5123,GL_INT=5124,GL_UNSIGNED_INT=5125,GL_FLOAT=5126,GL_UNSIGNED_SHORT_4_4_4_4=32819,GL_UNSIGNED_SHORT_5_5_5_1=32820,GL_UNSIGNED_SHORT_5_6_5=33635,GL_UNSIGNED_INT_24_8_WEBGL=34042,GL_HALF_FLOAT_OES=36193,TYPE_SIZE={};function pixelSize(type,channels){return type===GL_UNSIGNED_SHORT_5_5_5_1||type===GL_UNSIGNED_SHORT_4_4_4_4||type===GL_UNSIGNED_SHORT_5_6_5?2:type===GL_UNSIGNED_INT_24_8_WEBGL?4:TYPE_SIZE[type]*channels}function isPow2(v){return!(v&v-1||!v)}function checkTexture2D(info,mipData,limits){var i,w=mipData.width,h=mipData.height,c=mipData.channels;check(w>0&&w<=limits.maxTextureSize&&h>0&&h<=limits.maxTextureSize,"invalid texture shape"),info.wrapS===GL_CLAMP_TO_EDGE&&info.wrapT===GL_CLAMP_TO_EDGE||check(isPow2(w)&&isPow2(h),"incompatible wrap mode for texture, both width and height must be power of 2"),1===mipData.mipmask?1!==w&&1!==h&&check(info.minFilter!==GL_NEAREST_MIPMAP_NEAREST&&info.minFilter!==GL_NEAREST_MIPMAP_LINEAR&&info.minFilter!==GL_LINEAR_MIPMAP_NEAREST&&info.minFilter!==GL_LINEAR_MIPMAP_LINEAR,"min filter requires mipmap"):(check(isPow2(w)&&isPow2(h),"texture must be a square power of 2 to support mipmapping"),check(mipData.mipmask===(w<<1)-1,"missing or incomplete mipmap data")),mipData.type===GL_FLOAT&&(limits.extensions.indexOf("oes_texture_float_linear")<0&&check(info.minFilter===GL_NEAREST&&info.magFilter===GL_NEAREST,"filter not supported, must enable oes_texture_float_linear"),check(!info.genMipmaps,"mipmap generation not supported with float textures"));var mipimages=mipData.images;for(i=0;i<16;++i)if(mipimages[i]){var mw=w>>i,mh=h>>i;check(mipData.mipmask&1<<i,"missing mipmap data");var img=mipimages[i];if(check(img.width===mw&&img.height===mh,"invalid shape for mip images"),check(img.format===mipData.format&&img.internalformat===mipData.internalformat&&img.type===mipData.type,"incompatible type for mip image"),img.compressed);else if(img.data){var rowSize=Math.ceil(pixelSize(img.type,c)*mw/img.unpackAlignment)*img.unpackAlignment;check(img.data.byteLength===rowSize*mh,"invalid data for image, buffer size is inconsistent with image format")}else img.element||img.copy}else info.genMipmaps||check(0==(mipData.mipmask&1<<i),"extra mipmap data");mipData.compressed&&check(!info.genMipmaps,"mipmap generation for compressed images not supported")}function checkTextureCube(texture,info,faces,limits){var w=texture.width,h=texture.height,c=texture.channels;check(w>0&&w<=limits.maxTextureSize&&h>0&&h<=limits.maxTextureSize,"invalid texture shape"),check(w===h,"cube map must be square"),check(info.wrapS===GL_CLAMP_TO_EDGE&&info.wrapT===GL_CLAMP_TO_EDGE,"wrap mode not supported by cube map");for(var i=0;i<faces.length;++i){var face=faces[i];check(face.width===w&&face.height===h,"inconsistent cube map face shape"),info.genMipmaps&&(check(!face.compressed,"can not generate mipmap for compressed textures"),check(1===face.mipmask,"can not specify mipmaps and generate mipmaps"));for(var mipmaps=face.images,j=0;j<16;++j){var img=mipmaps[j];if(img){var mw=w>>j,mh=h>>j;check(face.mipmask&1<<j,"missing mipmap data"),check(img.width===mw&&img.height===mh,"invalid shape for mip images"),check(img.format===texture.format&&img.internalformat===texture.internalformat&&img.type===texture.type,"incompatible type for mip image"),img.compressed||(img.data?check(img.data.byteLength===mw*mh*Math.max(pixelSize(img.type,c),img.unpackAlignment),"invalid data for image, buffer size is inconsistent with image format"):img.element||img.copy)}}}}TYPE_SIZE[5120]=TYPE_SIZE[GL_UNSIGNED_BYTE]=1,TYPE_SIZE[GL_SHORT]=TYPE_SIZE[GL_UNSIGNED_SHORT]=TYPE_SIZE[GL_HALF_FLOAT_OES]=TYPE_SIZE[GL_UNSIGNED_SHORT_5_6_5]=TYPE_SIZE[GL_UNSIGNED_SHORT_4_4_4_4]=TYPE_SIZE[GL_UNSIGNED_SHORT_5_5_5_1]=2,TYPE_SIZE[GL_INT]=TYPE_SIZE[GL_UNSIGNED_INT]=TYPE_SIZE[GL_FLOAT]=TYPE_SIZE[GL_UNSIGNED_INT_24_8_WEBGL]=4;var check$1=extend(check,{optional:checkOptional,raise:raise,commandRaise:commandRaise,command:checkCommand,parameter:checkParameter,commandParameter:checkParameterCommand,constructor:checkConstructor,type:checkTypeOf,commandType:checkCommandType,isTypedArray:checkIsTypedArray,nni:checkNonNegativeInt,oneOf:checkOneOf,shaderError:checkShaderError,linkError:checkLinkError,callSite:guessCallSite,saveCommandRef:saveCommandRef,saveDrawInfo:saveDrawCommandInfo,framebufferFormat:checkFramebufferFormat,guessCommand:guessCommand,texture2D:checkTexture2D,textureCube:checkTextureCube}),VARIABLE_COUNTER=0,DYN_FUNC=0,DYN_CONSTANT=5,DYN_ARRAY=6;function DynamicVariable(type,data){this.id=VARIABLE_COUNTER++,this.type=type,this.data=data}function escapeStr(str){return str.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function splitParts(str){if(0===str.length)return[];var firstChar=str.charAt(0),lastChar=str.charAt(str.length-1);if(str.length>1&&firstChar===lastChar&&('"'===firstChar||"'"===firstChar))return['"'+escapeStr(str.substr(1,str.length-2))+'"'];var parts=/\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(str);if(parts)return splitParts(str.substr(0,parts.index)).concat(splitParts(parts[1])).concat(splitParts(str.substr(parts.index+parts[0].length)));var subparts=str.split(".");if(1===subparts.length)return['"'+escapeStr(str)+'"'];for(var result=[],i=0;i<subparts.length;++i)result=result.concat(splitParts(subparts[i]));return result}function toAccessorString(str){return"["+splitParts(str).join("][")+"]"}function defineDynamic(type,data){return new DynamicVariable(type,toAccessorString(data+""))}function isDynamic(x){return"function"==typeof x&&!x._reglType||x instanceof DynamicVariable}function unbox(x,path){return"function"==typeof x?new DynamicVariable(DYN_FUNC,x):"number"==typeof x||"boolean"==typeof x?new DynamicVariable(DYN_CONSTANT,x):Array.isArray(x)?new DynamicVariable(DYN_ARRAY,x.map((function(y,i){return unbox(y,path+"["+i+"]")}))):x instanceof DynamicVariable?x:void check$1(!1,"invalid option type in uniform "+path)}var dynamic={DynamicVariable:DynamicVariable,define:defineDynamic,isDynamic:isDynamic,unbox:unbox,accessor:toAccessorString},raf={next:"function"==typeof requestAnimationFrame?function(cb){return requestAnimationFrame(cb)}:function(cb){return setTimeout(cb,16)},cancel:"function"==typeof cancelAnimationFrame?function(raf){return cancelAnimationFrame(raf)}:clearTimeout},clock="undefined"!=typeof performance&&performance.now?function(){return performance.now()}:function(){return+new Date};function createStringStore(){var stringIds={"":0},stringValues=[""];return{id:function(str){var result=stringIds[str];return result||(result=stringIds[str]=stringValues.length,stringValues.push(str),result)},str:function(id){return stringValues[id]}}}function createCanvas(element,onDone,pixelRatio){var resizeObserver,canvas=document.createElement("canvas");function resize(){var w=window.innerWidth,h=window.innerHeight;if(element!==document.body){var bounds=canvas.getBoundingClientRect();w=bounds.right-bounds.left,h=bounds.bottom-bounds.top}canvas.width=pixelRatio*w,canvas.height=pixelRatio*h}function onDestroy(){resizeObserver?resizeObserver.disconnect():window.removeEventListener("resize",resize),element.removeChild(canvas)}return extend(canvas.style,{border:0,margin:0,padding:0,top:0,left:0,width:"100%",height:"100%"}),element.appendChild(canvas),element===document.body&&(canvas.style.position="absolute",extend(element.style,{margin:0,padding:0})),element!==document.body&&"function"==typeof ResizeObserver?(resizeObserver=new ResizeObserver((function(){setTimeout(resize)}))).observe(element):window.addEventListener("resize",resize,!1),resize(),{canvas:canvas,onDestroy:onDestroy}}function createContext(canvas,contextAttributes){function get(name){try{return canvas.getContext(name,contextAttributes)}catch(e){return null}}return get("webgl")||get("experimental-webgl")||get("webgl-experimental")}function isHTMLElement(obj){return"string"==typeof obj.nodeName&&"function"==typeof obj.appendChild&&"function"==typeof obj.getBoundingClientRect}function isWebGLContext(obj){return"function"==typeof obj.drawArrays||"function"==typeof obj.drawElements}function parseExtensions(input){return"string"==typeof input?input.split():(check$1(Array.isArray(input),"invalid extension array"),input)}function getElement(desc){return"string"==typeof desc?(check$1("undefined"!=typeof document,"not supported outside of DOM"),document.querySelector(desc)):desc}function parseArgs(args_){var element,container,canvas,gl,args=args_||{},contextAttributes={},extensions=[],optionalExtensions=[],pixelRatio="undefined"==typeof window?1:window.devicePixelRatio,profile=!1,onDone=function(err){err&&check$1.raise(err)},onDestroy=function(){};if("string"==typeof args?(check$1("undefined"!=typeof document,"selector queries only supported in DOM enviroments"),element=document.querySelector(args),check$1(element,"invalid query string for element")):"object"==typeof args?isHTMLElement(args)?element=args:isWebGLContext(args)?canvas=(gl=args).canvas:(check$1.constructor(args),"gl"in args?gl=args.gl:"canvas"in args?canvas=getElement(args.canvas):"container"in args&&(container=getElement(args.container)),"attributes"in args&&(contextAttributes=args.attributes,check$1.type(contextAttributes,"object","invalid context attributes")),"extensions"in args&&(extensions=parseExtensions(args.extensions)),"optionalExtensions"in args&&(optionalExtensions=parseExtensions(args.optionalExtensions)),"onDone"in args&&(check$1.type(args.onDone,"function","invalid or missing onDone callback"),onDone=args.onDone),"profile"in args&&(profile=!!args.profile),"pixelRatio"in args&&(pixelRatio=+args.pixelRatio,check$1(pixelRatio>0,"invalid pixel ratio"))):check$1.raise("invalid arguments to regl"),element&&("canvas"===element.nodeName.toLowerCase()?canvas=element:container=element),!gl){if(!canvas){check$1("undefined"!=typeof document,"must manually specify webgl context outside of DOM environments");var result=createCanvas(container||document.body,onDone,pixelRatio);if(!result)return null;canvas=result.canvas,onDestroy=result.onDestroy}void 0===contextAttributes.premultipliedAlpha&&(contextAttributes.premultipliedAlpha=!0),gl=createContext(canvas,contextAttributes)}return gl?{gl:gl,canvas:canvas,container:container,extensions:extensions,optionalExtensions:optionalExtensions,pixelRatio:pixelRatio,profile:profile,onDone:onDone,onDestroy:onDestroy}:(onDestroy(),onDone("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"),null)}function createExtensionCache(gl,config){var extensions={};function tryLoadExtension(name_){check$1.type(name_,"string","extension name must be string");var ext,name=name_.toLowerCase();try{ext=extensions[name]=gl.getExtension(name)}catch(e){}return!!ext}for(var i=0;i<config.extensions.length;++i){var name=config.extensions[i];if(!tryLoadExtension(name))return config.onDestroy(),config.onDone('"'+name+'" extension is not supported by the current WebGL context, try upgrading your system or a different browser'),null}return config.optionalExtensions.forEach(tryLoadExtension),{extensions:extensions,restore:function(){Object.keys(extensions).forEach((function(name){if(extensions[name]&&!tryLoadExtension(name))throw new Error("(regl): error restoring extension "+name)}))}}}function loop(n,f){for(var result=Array(n),i=0;i<n;++i)result[i]=f(i);return result}var GL_BYTE$1=5120,GL_UNSIGNED_BYTE$2=5121,GL_SHORT$1=5122,GL_UNSIGNED_SHORT$1=5123,GL_INT$1=5124,GL_UNSIGNED_INT$1=5125,GL_FLOAT$2=5126;function nextPow16(v){for(var i=16;i<=1<<28;i*=16)if(v<=i)return i;return 0}function log2(v){var r,shift;return r=(v>65535)<<4,r|=shift=((v>>>=r)>255)<<3,r|=shift=((v>>>=shift)>15)<<2,(r|=shift=((v>>>=shift)>3)<<1)|(v>>>=shift)>>1}function createPool(){var bufferPool=loop(8,(function(){return[]}));function alloc(n){var sz=nextPow16(n),bin=bufferPool[log2(sz)>>2];return bin.length>0?bin.pop():new ArrayBuffer(sz)}function free(buf){bufferPool[log2(buf.byteLength)>>2].push(buf)}function allocType(type,n){var result=null;switch(type){case GL_BYTE$1:result=new Int8Array(alloc(n),0,n);break;case GL_UNSIGNED_BYTE$2:result=new Uint8Array(alloc(n),0,n);break;case GL_SHORT$1:result=new Int16Array(alloc(2*n),0,n);break;case GL_UNSIGNED_SHORT$1:result=new Uint16Array(alloc(2*n),0,n);break;case GL_INT$1:result=new Int32Array(alloc(4*n),0,n);break;case GL_UNSIGNED_INT$1:result=new Uint32Array(alloc(4*n),0,n);break;case GL_FLOAT$2:result=new Float32Array(alloc(4*n),0,n);break;default:return null}return result.length!==n?result.subarray(0,n):result}function freeType(array){free(array.buffer)}return{alloc:alloc,free:free,allocType:allocType,freeType:freeType}}var pool=createPool();pool.zero=createPool();var GL_SUBPIXEL_BITS=3408,GL_RED_BITS=3410,GL_GREEN_BITS=3411,GL_BLUE_BITS=3412,GL_ALPHA_BITS=3413,GL_DEPTH_BITS=3414,GL_STENCIL_BITS=3415,GL_ALIASED_POINT_SIZE_RANGE=33901,GL_ALIASED_LINE_WIDTH_RANGE=33902,GL_MAX_TEXTURE_SIZE=3379,GL_MAX_VIEWPORT_DIMS=3386,GL_MAX_VERTEX_ATTRIBS=34921,GL_MAX_VERTEX_UNIFORM_VECTORS=36347,GL_MAX_VARYING_VECTORS=36348,GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS=35661,GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS=35660,GL_MAX_TEXTURE_IMAGE_UNITS=34930,GL_MAX_FRAGMENT_UNIFORM_VECTORS=36349,GL_MAX_CUBE_MAP_TEXTURE_SIZE=34076,GL_MAX_RENDERBUFFER_SIZE=34024,GL_VENDOR=7936,GL_RENDERER=7937,GL_VERSION=7938,GL_SHADING_LANGUAGE_VERSION=35724,GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT=34047,GL_MAX_COLOR_ATTACHMENTS_WEBGL=36063,GL_MAX_DRAW_BUFFERS_WEBGL=34852,GL_TEXTURE_2D=3553,GL_TEXTURE_CUBE_MAP=34067,GL_TEXTURE_CUBE_MAP_POSITIVE_X=34069,GL_TEXTURE0=33984,GL_RGBA=6408,GL_FLOAT$1=5126,GL_UNSIGNED_BYTE$1=5121,GL_FRAMEBUFFER=36160,GL_FRAMEBUFFER_COMPLETE=36053,GL_COLOR_ATTACHMENT0=36064,GL_COLOR_BUFFER_BIT$1=16384,wrapLimits=function(gl,extensions){var maxAnisotropic=1;extensions.ext_texture_filter_anisotropic&&(maxAnisotropic=gl.getParameter(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT));var maxDrawbuffers=1,maxColorAttachments=1;extensions.webgl_draw_buffers&&(maxDrawbuffers=gl.getParameter(GL_MAX_DRAW_BUFFERS_WEBGL),maxColorAttachments=gl.getParameter(GL_MAX_COLOR_ATTACHMENTS_WEBGL));var readFloat=!!extensions.oes_texture_float;if(readFloat){var readFloatTexture=gl.createTexture();gl.bindTexture(GL_TEXTURE_2D,readFloatTexture),gl.texImage2D(GL_TEXTURE_2D,0,GL_RGBA,1,1,0,GL_RGBA,GL_FLOAT$1,null);var fbo=gl.createFramebuffer();if(gl.bindFramebuffer(GL_FRAMEBUFFER,fbo),gl.framebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,readFloatTexture,0),gl.bindTexture(GL_TEXTURE_2D,null),gl.checkFramebufferStatus(GL_FRAMEBUFFER)!==GL_FRAMEBUFFER_COMPLETE)readFloat=!1;else{gl.viewport(0,0,1,1),gl.clearColor(1,0,0,1),gl.clear(GL_COLOR_BUFFER_BIT$1);var pixels=pool.allocType(GL_FLOAT$1,4);gl.readPixels(0,0,1,1,GL_RGBA,GL_FLOAT$1,pixels),gl.getError()?readFloat=!1:(gl.deleteFramebuffer(fbo),gl.deleteTexture(readFloatTexture),readFloat=1===pixels[0]),pool.freeType(pixels)}}var npotTextureCube=!0;if("undefined"==typeof navigator||!(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)||/Edge/.test(navigator.userAgent))){var cubeTexture=gl.createTexture(),data=pool.allocType(GL_UNSIGNED_BYTE$1,36);gl.activeTexture(GL_TEXTURE0),gl.bindTexture(GL_TEXTURE_CUBE_MAP,cubeTexture),gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X,0,GL_RGBA,3,3,0,GL_RGBA,GL_UNSIGNED_BYTE$1,data),pool.freeType(data),gl.bindTexture(GL_TEXTURE_CUBE_MAP,null),gl.deleteTexture(cubeTexture),npotTextureCube=!gl.getError()}return{colorBits:[gl.getParameter(GL_RED_BITS),gl.getParameter(GL_GREEN_BITS),gl.getParameter(GL_BLUE_BITS),gl.getParameter(GL_ALPHA_BITS)],depthBits:gl.getParameter(GL_DEPTH_BITS),stencilBits:gl.getParameter(GL_STENCIL_BITS),subpixelBits:gl.getParameter(GL_SUBPIXEL_BITS),extensions:Object.keys(extensions).filter((function(ext){return!!extensions[ext]})),maxAnisotropic:maxAnisotropic,maxDrawbuffers:maxDrawbuffers,maxColorAttachments:maxColorAttachments,pointSizeDims:gl.getParameter(GL_ALIASED_POINT_SIZE_RANGE),lineWidthDims:gl.getParameter(GL_ALIASED_LINE_WIDTH_RANGE),maxViewportDims:gl.getParameter(GL_MAX_VIEWPORT_DIMS),maxCombinedTextureUnits:gl.getParameter(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxCubeMapSize:gl.getParameter(GL_MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderbufferSize:gl.getParameter(GL_MAX_RENDERBUFFER_SIZE),maxTextureUnits:gl.getParameter(GL_MAX_TEXTURE_IMAGE_UNITS),maxTextureSize:gl.getParameter(GL_MAX_TEXTURE_SIZE),maxAttributes:gl.getParameter(GL_MAX_VERTEX_ATTRIBS),maxVertexUniforms:gl.getParameter(GL_MAX_VERTEX_UNIFORM_VECTORS),maxVertexTextureUnits:gl.getParameter(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxVaryingVectors:gl.getParameter(GL_MAX_VARYING_VECTORS),maxFragmentUniforms:gl.getParameter(GL_MAX_FRAGMENT_UNIFORM_VECTORS),glsl:gl.getParameter(GL_SHADING_LANGUAGE_VERSION),renderer:gl.getParameter(GL_RENDERER),vendor:gl.getParameter(GL_VENDOR),version:gl.getParameter(GL_VERSION),readFloat:readFloat,npotTextureCube:npotTextureCube}};function isNDArrayLike(obj){return!!obj&&"object"==typeof obj&&Array.isArray(obj.shape)&&Array.isArray(obj.stride)&&"number"==typeof obj.offset&&obj.shape.length===obj.stride.length&&(Array.isArray(obj.data)||isTypedArray(obj.data))}var values=function(obj){return Object.keys(obj).map((function(key){return obj[key]}))},flattenUtils={shape:arrayShape$1,flatten:flattenArray};function flatten1D(array,nx,out){for(var i=0;i<nx;++i)out[i]=array[i]}function flatten2D(array,nx,ny,out){for(var ptr=0,i=0;i<nx;++i)for(var row=array[i],j=0;j<ny;++j)out[ptr++]=row[j]}function flatten3D(array,nx,ny,nz,out,ptr_){for(var ptr=ptr_,i=0;i<nx;++i)for(var row=array[i],j=0;j<ny;++j)for(var col=row[j],k=0;k<nz;++k)out[ptr++]=col[k]}function flattenRec(array,shape,level,out,ptr){for(var stride=1,i=level+1;i<shape.length;++i)stride*=shape[i];var n=shape[level];if(shape.length-level==4){var nx=shape[level+1],ny=shape[level+2],nz=shape[level+3];for(i=0;i<n;++i)flatten3D(array[i],nx,ny,nz,out,ptr),ptr+=stride}else for(i=0;i<n;++i)flattenRec(array[i],shape,level+1,out,ptr),ptr+=stride}function flattenArray(array,shape,type,out_){var sz=1;if(shape.length)for(var i=0;i<shape.length;++i)sz*=shape[i];else sz=0;var out=out_||pool.allocType(type,sz);switch(shape.length){case 0:break;case 1:flatten1D(array,shape[0],out);break;case 2:flatten2D(array,shape[0],shape[1],out);break;case 3:flatten3D(array,shape[0],shape[1],shape[2],out,0);break;default:flattenRec(array,shape,0,out,0)}return out}function arrayShape$1(array_){for(var shape=[],array=array_;array.length;array=array[0])shape.push(array.length);return shape}var arrayTypes={"[object Int8Array]":5120,"[object Int16Array]":5122,"[object Int32Array]":5124,"[object Uint8Array]":5121,"[object Uint8ClampedArray]":5121,"[object Uint16Array]":5123,"[object Uint32Array]":5125,"[object Float32Array]":5126,"[object Float64Array]":5121,"[object ArrayBuffer]":5121},glTypes={int8:5120,int16:5122,int32:5124,uint8:5121,uint16:5123,uint32:5125,float:5126,float32:5126},usageTypes={dynamic:35048,stream:35040,static:35044},arrayFlatten=flattenUtils.flatten,arrayShape=flattenUtils.shape,GL_STATIC_DRAW=35044,GL_STREAM_DRAW=35040,GL_UNSIGNED_BYTE$3=5121,GL_FLOAT$3=5126,DTYPES_SIZES=[];function typedArrayCode(data){return 0|arrayTypes[Object.prototype.toString.call(data)]}function copyArray(out,inp){for(var i=0;i<inp.length;++i)out[i]=inp[i]}function transpose(result,data,shapeX,shapeY,strideX,strideY,offset){for(var ptr=0,i=0;i<shapeX;++i)for(var j=0;j<shapeY;++j)result[ptr++]=data[strideX*i+strideY*j+offset]}function wrapBufferState(gl,stats,config,destroyBuffer){var bufferCount=0,bufferSet={};function REGLBuffer(type){this.id=bufferCount++,this.buffer=gl.createBuffer(),this.type=type,this.usage=GL_STATIC_DRAW,this.byteLength=0,this.dimension=1,this.dtype=GL_UNSIGNED_BYTE$3,this.persistentData=null,config.profile&&(this.stats={size:0})}REGLBuffer.prototype.bind=function(){gl.bindBuffer(this.type,this.buffer)},REGLBuffer.prototype.destroy=function(){destroy(this)};var streamPool=[];function createStream(type,data){var buffer=streamPool.pop();return buffer||(buffer=new REGLBuffer(type)),buffer.bind(),initBufferFromData(buffer,data,GL_STREAM_DRAW,0,1,!1),buffer}function destroyStream(stream$$1){streamPool.push(stream$$1)}function initBufferFromTypedArray(buffer,data,usage){buffer.byteLength=data.byteLength,gl.bufferData(buffer.type,data,usage)}function initBufferFromData(buffer,data,usage,dtype,dimension,persist){var shape,flatData;if(buffer.usage=usage,Array.isArray(data)){if(buffer.dtype=dtype||GL_FLOAT$3,data.length>0)if(Array.isArray(data[0])){shape=arrayShape(data);for(var dim=1,i=1;i<shape.length;++i)dim*=shape[i];buffer.dimension=dim,initBufferFromTypedArray(buffer,flatData=arrayFlatten(data,shape,buffer.dtype),usage),persist?buffer.persistentData=flatData:pool.freeType(flatData)}else if("number"==typeof data[0]){buffer.dimension=dimension;var typedData=pool.allocType(buffer.dtype,data.length);copyArray(typedData,data),initBufferFromTypedArray(buffer,typedData,usage),persist?buffer.persistentData=typedData:pool.freeType(typedData)}else isTypedArray(data[0])?(buffer.dimension=data[0].length,buffer.dtype=dtype||typedArrayCode(data[0])||GL_FLOAT$3,initBufferFromTypedArray(buffer,flatData=arrayFlatten(data,[data.length,data[0].length],buffer.dtype),usage),persist?buffer.persistentData=flatData:pool.freeType(flatData)):check$1.raise("invalid buffer data")}else if(isTypedArray(data))buffer.dtype=dtype||typedArrayCode(data),buffer.dimension=dimension,initBufferFromTypedArray(buffer,data,usage),persist&&(buffer.persistentData=new Uint8Array(new Uint8Array(data.buffer)));else if(isNDArrayLike(data)){shape=data.shape;var stride=data.stride,offset=data.offset,shapeX=0,shapeY=0,strideX=0,strideY=0;1===shape.length?(shapeX=shape[0],shapeY=1,strideX=stride[0],strideY=0):2===shape.length?(shapeX=shape[0],shapeY=shape[1],strideX=stride[0],strideY=stride[1]):check$1.raise("invalid shape"),buffer.dtype=dtype||typedArrayCode(data.data)||GL_FLOAT$3,buffer.dimension=shapeY;var transposeData=pool.allocType(buffer.dtype,shapeX*shapeY);transpose(transposeData,data.data,shapeX,shapeY,strideX,strideY,offset),initBufferFromTypedArray(buffer,transposeData,usage),persist?buffer.persistentData=transposeData:pool.freeType(transposeData)}else data instanceof ArrayBuffer?(buffer.dtype=GL_UNSIGNED_BYTE$3,buffer.dimension=dimension,initBufferFromTypedArray(buffer,data,usage),persist&&(buffer.persistentData=new Uint8Array(new Uint8Array(data)))):check$1.raise("invalid buffer data")}function destroy(buffer){stats.bufferCount--,destroyBuffer(buffer);var handle=buffer.buffer;check$1(handle,"buffer must not be deleted already"),gl.deleteBuffer(handle),buffer.buffer=null,delete bufferSet[buffer.id]}function createBuffer(options,type,deferInit,persistent){stats.bufferCount++;var buffer=new REGLBuffer(type);function reglBuffer(options){var usage=GL_STATIC_DRAW,data=null,byteLength=0,dtype=0,dimension=1;return Array.isArray(options)||isTypedArray(options)||isNDArrayLike(options)||options instanceof ArrayBuffer?data=options:"number"==typeof options?byteLength=0|options:options&&(check$1.type(options,"object","buffer arguments must be an object, a number or an array"),"data"in options&&(check$1(null===data||Array.isArray(data)||isTypedArray(data)||isNDArrayLike(data),"invalid data for buffer"),data=options.data),"usage"in options&&(check$1.parameter(options.usage,usageTypes,"invalid buffer usage"),usage=usageTypes[options.usage]),"type"in options&&(check$1.parameter(options.type,glTypes,"invalid buffer type"),dtype=glTypes[options.type]),"dimension"in options&&(check$1.type(options.dimension,"number","invalid dimension"),dimension=0|options.dimension),"length"in options&&(check$1.nni(byteLength,"buffer length must be a nonnegative integer"),byteLength=0|options.length)),buffer.bind(),data?initBufferFromData(buffer,data,usage,dtype,dimension,persistent):(byteLength&&gl.bufferData(buffer.type,byteLength,usage),buffer.dtype=dtype||GL_UNSIGNED_BYTE$3,buffer.usage=usage,buffer.dimension=dimension,buffer.byteLength=byteLength),config.profile&&(buffer.stats.size=buffer.byteLength*DTYPES_SIZES[buffer.dtype]),reglBuffer}function setSubData(data,offset){check$1(offset+data.byteLength<=buffer.byteLength,"invalid buffer subdata call, buffer is too small. Can't write data of size "+data.byteLength+" starting from offset "+offset+" to a buffer of size "+buffer.byteLength),gl.bufferSubData(buffer.type,offset,data)}function subdata(data,offset_){var shape,offset=0|(offset_||0);if(buffer.bind(),isTypedArray(data)||data instanceof ArrayBuffer)setSubData(data,offset);else if(Array.isArray(data)){if(data.length>0)if("number"==typeof data[0]){var converted=pool.allocType(buffer.dtype,data.length);copyArray(converted,data),setSubData(converted,offset),pool.freeType(converted)}else if(Array.isArray(data[0])||isTypedArray(data[0])){shape=arrayShape(data);var flatData=arrayFlatten(data,shape,buffer.dtype);setSubData(flatData,offset),pool.freeType(flatData)}else check$1.raise("invalid buffer data")}else if(isNDArrayLike(data)){shape=data.shape;var stride=data.stride,shapeX=0,shapeY=0,strideX=0,strideY=0;1===shape.length?(shapeX=shape[0],shapeY=1,strideX=stride[0],strideY=0):2===shape.length?(shapeX=shape[0],shapeY=shape[1],strideX=stride[0],strideY=stride[1]):check$1.raise("invalid shape");var dtype=Array.isArray(data.data)?buffer.dtype:typedArrayCode(data.data),transposeData=pool.allocType(dtype,shapeX*shapeY);transpose(transposeData,data.data,shapeX,shapeY,strideX,strideY,data.offset),setSubData(transposeData,offset),pool.freeType(transposeData)}else check$1.raise("invalid data for buffer subdata");return reglBuffer}return bufferSet[buffer.id]=buffer,deferInit||reglBuffer(options),reglBuffer._reglType="buffer",reglBuffer._buffer=buffer,reglBuffer.subdata=subdata,config.profile&&(reglBuffer.stats=buffer.stats),reglBuffer.destroy=function(){destroy(buffer)},reglBuffer}function restoreBuffers(){values(bufferSet).forEach((function(buffer){buffer.buffer=gl.createBuffer(),gl.bindBuffer(buffer.type,buffer.buffer),gl.bufferData(buffer.type,buffer.persistentData||buffer.byteLength,buffer.usage)}))}return config.profile&&(stats.getTotalBufferSize=function(){var total=0;return Object.keys(bufferSet).forEach((function(key){total+=bufferSet[key].stats.size})),total}),{create:createBuffer,createStream:createStream,destroyStream:destroyStream,clear:function(){values(bufferSet).forEach(destroy),streamPool.forEach(destroy)},getBuffer:function(wrapper){return wrapper&&wrapper._buffer instanceof REGLBuffer?wrapper._buffer:null},restore:restoreBuffers,_initBuffer:initBufferFromData}}DTYPES_SIZES[5120]=1,DTYPES_SIZES[5122]=2,DTYPES_SIZES[5124]=4,DTYPES_SIZES[5121]=1,DTYPES_SIZES[5123]=2,DTYPES_SIZES[5125]=4,DTYPES_SIZES[5126]=4;var primTypes={points:0,point:0,lines:1,line:1,triangles:4,triangle:4,"line loop":2,"line strip":3,"triangle strip":5,"triangle fan":6},GL_POINTS=0,GL_LINES=1,GL_TRIANGLES=4,GL_BYTE$2=5120,GL_UNSIGNED_BYTE$4=5121,GL_SHORT$2=5122,GL_UNSIGNED_SHORT$2=5123,GL_INT$2=5124,GL_UNSIGNED_INT$2=5125,GL_ELEMENT_ARRAY_BUFFER=34963,GL_STREAM_DRAW$1=35040,GL_STATIC_DRAW$1=35044;function wrapElementsState(gl,extensions,bufferState,stats){var elementSet={},elementCount=0,elementTypes={uint8:GL_UNSIGNED_BYTE$4,uint16:GL_UNSIGNED_SHORT$2};function REGLElementBuffer(buffer){this.id=elementCount++,elementSet[this.id]=this,this.buffer=buffer,this.primType=GL_TRIANGLES,this.vertCount=0,this.type=0}extensions.oes_element_index_uint&&(elementTypes.uint32=GL_UNSIGNED_INT$2),REGLElementBuffer.prototype.bind=function(){this.buffer.bind()};var bufferPool=[];function createElementStream(data){var result=bufferPool.pop();return result||(result=new REGLElementBuffer(bufferState.create(null,GL_ELEMENT_ARRAY_BUFFER,!0,!1)._buffer)),initElements(result,data,GL_STREAM_DRAW$1,-1,-1,0,0),result}function destroyElementStream(elements){bufferPool.push(elements)}function initElements(elements,data,usage,prim,count,byteLength,type){var dtype;if(elements.buffer.bind(),data){var predictedType=type;type||isTypedArray(data)&&(!isNDArrayLike(data)||isTypedArray(data.data))||(predictedType=extensions.oes_element_index_uint?GL_UNSIGNED_INT$2:GL_UNSIGNED_SHORT$2),bufferState._initBuffer(elements.buffer,data,usage,predictedType,3)}else gl.bufferData(GL_ELEMENT_ARRAY_BUFFER,byteLength,usage),elements.buffer.dtype=dtype||GL_UNSIGNED_BYTE$4,elements.buffer.usage=usage,elements.buffer.dimension=3,elements.buffer.byteLength=byteLength;if(dtype=type,!type){switch(elements.buffer.dtype){case GL_UNSIGNED_BYTE$4:case GL_BYTE$2:dtype=GL_UNSIGNED_BYTE$4;break;case GL_UNSIGNED_SHORT$2:case GL_SHORT$2:dtype=GL_UNSIGNED_SHORT$2;break;case GL_UNSIGNED_INT$2:case GL_INT$2:dtype=GL_UNSIGNED_INT$2;break;default:check$1.raise("unsupported type for element array")}elements.buffer.dtype=dtype}elements.type=dtype,check$1(dtype!==GL_UNSIGNED_INT$2||!!extensions.oes_element_index_uint,"32 bit element buffers not supported, enable oes_element_index_uint first");var vertCount=count;vertCount<0&&(vertCount=elements.buffer.byteLength,dtype===GL_UNSIGNED_SHORT$2?vertCount>>=1:dtype===GL_UNSIGNED_INT$2&&(vertCount>>=2)),elements.vertCount=vertCount;var primType=prim;if(prim<0){primType=GL_TRIANGLES;var dimension=elements.buffer.dimension;1===dimension&&(primType=GL_POINTS),2===dimension&&(primType=GL_LINES),3===dimension&&(primType=GL_TRIANGLES)}elements.primType=primType}function destroyElements(elements){stats.elementsCount--,check$1(null!==elements.buffer,"must not double destroy elements"),delete elementSet[elements.id],elements.buffer.destroy(),elements.buffer=null}function createElements(options,persistent){var buffer=bufferState.create(null,GL_ELEMENT_ARRAY_BUFFER,!0),elements=new REGLElementBuffer(buffer._buffer);function reglElements(options){if(options)if("number"==typeof options)buffer(options),elements.primType=GL_TRIANGLES,elements.vertCount=0|options,elements.type=GL_UNSIGNED_BYTE$4;else{var data=null,usage=GL_STATIC_DRAW$1,primType=-1,vertCount=-1,byteLength=0,dtype=0;Array.isArray(options)||isTypedArray(options)||isNDArrayLike(options)?data=options:(check$1.type(options,"object","invalid arguments for elements"),"data"in options&&(data=options.data,check$1(Array.isArray(data)||isTypedArray(data)||isNDArrayLike(data),"invalid data for element buffer")),"usage"in options&&(check$1.parameter(options.usage,usageTypes,"invalid element buffer usage"),usage=usageTypes[options.usage]),"primitive"in options&&(check$1.parameter(options.primitive,primTypes,"invalid element buffer primitive"),primType=primTypes[options.primitive]),"count"in options&&(check$1("number"==typeof options.count&&options.count>=0,"invalid vertex count for elements"),vertCount=0|options.count),"type"in options&&(check$1.parameter(options.type,elementTypes,"invalid buffer type"),dtype=elementTypes[options.type]),"length"in options?byteLength=0|options.length:(byteLength=vertCount,dtype===GL_UNSIGNED_SHORT$2||dtype===GL_SHORT$2?byteLength*=2:dtype!==GL_UNSIGNED_INT$2&&dtype!==GL_INT$2||(byteLength*=4))),initElements(elements,data,usage,primType,vertCount,byteLength,dtype)}else buffer(),elements.primType=GL_TRIANGLES,elements.vertCount=0,elements.type=GL_UNSIGNED_BYTE$4;return reglElements}return stats.elementsCount++,reglElements(options),reglElements._reglType="elements",reglElements._elements=elements,reglElements.subdata=function(data,offset){return buffer.subdata(data,offset),reglElements},reglElements.destroy=function(){destroyElements(elements)},reglElements}return{create:createElements,createStream:createElementStream,destroyStream:destroyElementStream,getElements:function(elements){return"function"==typeof elements&&elements._elements instanceof REGLElementBuffer?elements._elements:null},clear:function(){values(elementSet).forEach(destroyElements)}}}var FLOAT=new Float32Array(1),INT=new Uint32Array(FLOAT.buffer),GL_UNSIGNED_SHORT$4=5123;function convertToHalfFloat(array){for(var ushorts=pool.allocType(GL_UNSIGNED_SHORT$4,array.length),i=0;i<array.length;++i)if(isNaN(array[i]))ushorts[i]=65535;else if(array[i]===1/0)ushorts[i]=31744;else if(array[i]===-1/0)ushorts[i]=64512;else{FLOAT[0]=array[i];var x=INT[0],sgn=x>>>31<<15,exp=(x<<1>>>24)-127,frac=x>>13&1023;if(exp<-24)ushorts[i]=sgn;else if(exp<-14){var s=-14-exp;ushorts[i]=sgn+(frac+1024>>s)}else ushorts[i]=exp>15?sgn+31744:sgn+(exp+15<<10)+frac}return ushorts}function isArrayLike(s){return Array.isArray(s)||isTypedArray(s)}var isPow2$1=function(v){return!(v&v-1||!v)},GL_COMPRESSED_TEXTURE_FORMATS=34467,GL_TEXTURE_2D$1=3553,GL_TEXTURE_CUBE_MAP$1=34067,GL_TEXTURE_CUBE_MAP_POSITIVE_X$1=34069,GL_RGBA$1=6408,GL_ALPHA=6406,GL_RGB=6407,GL_LUMINANCE=6409,GL_LUMINANCE_ALPHA=6410,GL_RGBA4=32854,GL_RGB5_A1=32855,GL_RGB565=36194,GL_UNSIGNED_SHORT_4_4_4_4$1=32819,GL_UNSIGNED_SHORT_5_5_5_1$1=32820,GL_UNSIGNED_SHORT_5_6_5$1=33635,GL_UNSIGNED_INT_24_8_WEBGL$1=34042,GL_DEPTH_COMPONENT=6402,GL_DEPTH_STENCIL=34041,GL_SRGB_EXT=35904,GL_SRGB_ALPHA_EXT=35906,GL_HALF_FLOAT_OES$1=36193,GL_COMPRESSED_RGB_S3TC_DXT1_EXT=33776,GL_COMPRESSED_RGBA_S3TC_DXT1_EXT=33777,GL_COMPRESSED_RGBA_S3TC_DXT3_EXT=33778,GL_COMPRESSED_RGBA_S3TC_DXT5_EXT=33779,GL_COMPRESSED_RGB_ATC_WEBGL=35986,GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=35987,GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=34798,GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840,GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG=35841,GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842,GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=35843,GL_COMPRESSED_RGB_ETC1_WEBGL=36196,GL_UNSIGNED_BYTE$5=5121,GL_UNSIGNED_SHORT$3=5123,GL_UNSIGNED_INT$3=5125,GL_FLOAT$4=5126,GL_TEXTURE_WRAP_S=10242,GL_TEXTURE_WRAP_T=10243,GL_REPEAT=10497,GL_CLAMP_TO_EDGE$1=33071,GL_MIRRORED_REPEAT=33648,GL_TEXTURE_MAG_FILTER=10240,GL_TEXTURE_MIN_FILTER=10241,GL_NEAREST$1=9728,GL_LINEAR=9729,GL_NEAREST_MIPMAP_NEAREST$1=9984,GL_LINEAR_MIPMAP_NEAREST$1=9985,GL_NEAREST_MIPMAP_LINEAR$1=9986,GL_LINEAR_MIPMAP_LINEAR$1=9987,GL_GENERATE_MIPMAP_HINT=33170,GL_DONT_CARE=4352,GL_FASTEST=4353,GL_NICEST=4354,GL_TEXTURE_MAX_ANISOTROPY_EXT=34046,GL_UNPACK_ALIGNMENT=3317,GL_UNPACK_FLIP_Y_WEBGL=37440,GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL=37441,GL_UNPACK_COLORSPACE_CONVERSION_WEBGL=37443,GL_BROWSER_DEFAULT_WEBGL=37444,GL_TEXTURE0$1=33984,MIPMAP_FILTERS=[GL_NEAREST_MIPMAP_NEAREST$1,GL_NEAREST_MIPMAP_LINEAR$1,GL_LINEAR_MIPMAP_NEAREST$1,GL_LINEAR_MIPMAP_LINEAR$1],CHANNELS_FORMAT=[0,GL_LUMINANCE,GL_LUMINANCE_ALPHA,GL_RGB,GL_RGBA$1],FORMAT_CHANNELS={};function objectName(str){return"[object "+str+"]"}FORMAT_CHANNELS[GL_LUMINANCE]=FORMAT_CHANNELS[GL_ALPHA]=FORMAT_CHANNELS[GL_DEPTH_COMPONENT]=1,FORMAT_CHANNELS[GL_DEPTH_STENCIL]=FORMAT_CHANNELS[GL_LUMINANCE_ALPHA]=2,FORMAT_CHANNELS[GL_RGB]=FORMAT_CHANNELS[GL_SRGB_EXT]=3,FORMAT_CHANNELS[GL_RGBA$1]=FORMAT_CHANNELS[GL_SRGB_ALPHA_EXT]=4;var CANVAS_CLASS=objectName("HTMLCanvasElement"),OFFSCREENCANVAS_CLASS=objectName("OffscreenCanvas"),CONTEXT2D_CLASS=objectName("CanvasRenderingContext2D"),BITMAP_CLASS=objectName("ImageBitmap"),IMAGE_CLASS=objectName("HTMLImageElement"),VIDEO_CLASS=objectName("HTMLVideoElement"),PIXEL_CLASSES=Object.keys(arrayTypes).concat([CANVAS_CLASS,OFFSCREENCANVAS_CLASS,CONTEXT2D_CLASS,BITMAP_CLASS,IMAGE_CLASS,VIDEO_CLASS]),TYPE_SIZES=[];TYPE_SIZES[GL_UNSIGNED_BYTE$5]=1,TYPE_SIZES[GL_FLOAT$4]=4,TYPE_SIZES[GL_HALF_FLOAT_OES$1]=2,TYPE_SIZES[GL_UNSIGNED_SHORT$3]=2,TYPE_SIZES[GL_UNSIGNED_INT$3]=4;var FORMAT_SIZES_SPECIAL=[];function isNumericArray(arr){return Array.isArray(arr)&&(0===arr.length||"number"==typeof arr[0])}function isRectArray(arr){return!!Array.isArray(arr)&&!(0===arr.length||!isArrayLike(arr[0]))}function classString(x){return Object.prototype.toString.call(x)}function isCanvasElement(object){return classString(object)===CANVAS_CLASS}function isOffscreenCanvas(object){return classString(object)===OFFSCREENCANVAS_CLASS}function isContext2D(object){return classString(object)===CONTEXT2D_CLASS}function isBitmap(object){return classString(object)===BITMAP_CLASS}function isImageElement(object){return classString(object)===IMAGE_CLASS}function isVideoElement(object){return classString(object)===VIDEO_CLASS}function isPixelData(object){if(!object)return!1;var className=classString(object);return PIXEL_CLASSES.indexOf(className)>=0||isNumericArray(object)||isRectArray(object)||isNDArrayLike(object)}function typedArrayCode$1(data){return 0|arrayTypes[Object.prototype.toString.call(data)]}function convertData(result,data){var n=data.length;switch(result.type){case GL_UNSIGNED_BYTE$5:case GL_UNSIGNED_SHORT$3:case GL_UNSIGNED_INT$3:case GL_FLOAT$4:var converted=pool.allocType(result.type,n);converted.set(data),result.data=converted;break;case GL_HALF_FLOAT_OES$1:result.data=convertToHalfFloat(data);break;default:check$1.raise("unsupported texture type, must specify a typed array")}}function preConvert(image,n){return pool.allocType(image.type===GL_HALF_FLOAT_OES$1?GL_FLOAT$4:image.type,n)}function postConvert(image,data){image.type===GL_HALF_FLOAT_OES$1?(image.data=convertToHalfFloat(data),pool.freeType(data)):image.data=data}function transposeData(image,array,strideX,strideY,strideC,offset){for(var w=image.width,h=image.height,c=image.channels,data=preConvert(image,w*h*c),p=0,i=0;i<h;++i)for(var j=0;j<w;++j)for(var k=0;k<c;++k)data[p++]=array[strideX*j+strideY*i+strideC*k+offset];postConvert(image,data)}function getTextureSize(format,type,width,height,isMipmap,isCube){var s;if(s=void 0!==FORMAT_SIZES_SPECIAL[format]?FORMAT_SIZES_SPECIAL[format]:FORMAT_CHANNELS[format]*TYPE_SIZES[type],isCube&&(s*=6),isMipmap){for(var total=0,w=width;w>=1;)total+=s*w*w,w/=2;return total}return s*width*height}function createTextureSet(gl,extensions,limits,reglPoll,contextState,stats,config){var mipmapHint={"don't care":GL_DONT_CARE,"dont care":GL_DONT_CARE,nice:GL_NICEST,fast:GL_FASTEST},wrapModes={repeat:GL_REPEAT,clamp:GL_CLAMP_TO_EDGE$1,mirror:GL_MIRRORED_REPEAT},magFilters={nearest:GL_NEAREST$1,linear:GL_LINEAR},minFilters=extend({mipmap:GL_LINEAR_MIPMAP_LINEAR$1,"nearest mipmap nearest":GL_NEAREST_MIPMAP_NEAREST$1,"linear mipmap nearest":GL_LINEAR_MIPMAP_NEAREST$1,"nearest mipmap linear":GL_NEAREST_MIPMAP_LINEAR$1,"linear mipmap linear":GL_LINEAR_MIPMAP_LINEAR$1},magFilters),colorSpace={none:0,browser:GL_BROWSER_DEFAULT_WEBGL},textureTypes={uint8:GL_UNSIGNED_BYTE$5,rgba4:GL_UNSIGNED_SHORT_4_4_4_4$1,rgb565:GL_UNSIGNED_SHORT_5_6_5$1,"rgb5 a1":GL_UNSIGNED_SHORT_5_5_5_1$1},textureFormats={alpha:GL_ALPHA,luminance:GL_LUMINANCE,"luminance alpha":GL_LUMINANCE_ALPHA,rgb:GL_RGB,rgba:GL_RGBA$1,rgba4:GL_RGBA4,"rgb5 a1":GL_RGB5_A1,rgb565:GL_RGB565},compressedTextureFormats={};extensions.ext_srgb&&(textureFormats.srgb=GL_SRGB_EXT,textureFormats.srgba=GL_SRGB_ALPHA_EXT),extensions.oes_texture_float&&(textureTypes.float32=textureTypes.float=GL_FLOAT$4),extensions.oes_texture_half_float&&(textureTypes.float16=textureTypes["half float"]=GL_HALF_FLOAT_OES$1),extensions.webgl_depth_texture&&(extend(textureFormats,{depth:GL_DEPTH_COMPONENT,"depth stencil":GL_DEPTH_STENCIL}),extend(textureTypes,{uint16:GL_UNSIGNED_SHORT$3,uint32:GL_UNSIGNED_INT$3,"depth stencil":GL_UNSIGNED_INT_24_8_WEBGL$1})),extensions.webgl_compressed_texture_s3tc&&extend(compressedTextureFormats,{"rgb s3tc dxt1":GL_COMPRESSED_RGB_S3TC_DXT1_EXT,"rgba s3tc dxt1":GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,"rgba s3tc dxt3":GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,"rgba s3tc dxt5":GL_COMPRESSED_RGBA_S3TC_DXT5_EXT}),extensions.webgl_compressed_texture_atc&&extend(compressedTextureFormats,{"rgb atc":GL_COMPRESSED_RGB_ATC_WEBGL,"rgba atc explicit alpha":GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL,"rgba atc interpolated alpha":GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL}),extensions.webgl_compressed_texture_pvrtc&&extend(compressedTextureFormats,{"rgb pvrtc 4bppv1":GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG,"rgb pvrtc 2bppv1":GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG,"rgba pvrtc 4bppv1":GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG,"rgba pvrtc 2bppv1":GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}),extensions.webgl_compressed_texture_etc1&&(compressedTextureFormats["rgb etc1"]=GL_COMPRESSED_RGB_ETC1_WEBGL);var supportedCompressedFormats=Array.prototype.slice.call(gl.getParameter(GL_COMPRESSED_TEXTURE_FORMATS));Object.keys(compressedTextureFormats).forEach((function(name){var format=compressedTextureFormats[name];supportedCompressedFormats.indexOf(format)>=0&&(textureFormats[name]=format)}));var supportedFormats=Object.keys(textureFormats);limits.textureFormats=supportedFormats;var textureFormatsInvert=[];Object.keys(textureFormats).forEach((function(key){var val=textureFormats[key];textureFormatsInvert[val]=key}));var textureTypesInvert=[];Object.keys(textureTypes).forEach((function(key){var val=textureTypes[key];textureTypesInvert[val]=key}));var magFiltersInvert=[];Object.keys(magFilters).forEach((function(key){var val=magFilters[key];magFiltersInvert[val]=key}));var minFiltersInvert=[];Object.keys(minFilters).forEach((function(key){var val=minFilters[key];minFiltersInvert[val]=key}));var wrapModesInvert=[];Object.keys(wrapModes).forEach((function(key){var val=wrapModes[key];wrapModesInvert[val]=key}));var colorFormats=supportedFormats.reduce((function(color,key){var glenum=textureFormats[key];return glenum===GL_LUMINANCE||glenum===GL_ALPHA||glenum===GL_LUMINANCE||glenum===GL_LUMINANCE_ALPHA||glenum===GL_DEPTH_COMPONENT||glenum===GL_DEPTH_STENCIL||extensions.ext_srgb&&(glenum===GL_SRGB_EXT||glenum===GL_SRGB_ALPHA_EXT)?color[glenum]=glenum:glenum===GL_RGB5_A1||key.indexOf("rgba")>=0?color[glenum]=GL_RGBA$1:color[glenum]=GL_RGB,color}),{});function TexFlags(){this.internalformat=GL_RGBA$1,this.format=GL_RGBA$1,this.type=GL_UNSIGNED_BYTE$5,this.compressed=!1,this.premultiplyAlpha=!1,this.flipY=!1,this.unpackAlignment=1,this.colorSpace=GL_BROWSER_DEFAULT_WEBGL,this.width=0,this.height=0,this.channels=0}function copyFlags(result,other){result.internalformat=other.internalformat,result.format=other.format,result.type=other.type,result.compressed=other.compressed,result.premultiplyAlpha=other.premultiplyAlpha,result.flipY=other.flipY,result.unpackAlignment=other.unpackAlignment,result.colorSpace=other.colorSpace,result.width=other.width,result.height=other.height,result.channels=other.channels}function parseFlags(flags,options){if("object"==typeof options&&options){if("premultiplyAlpha"in options&&(check$1.type(options.premultiplyAlpha,"boolean","invalid premultiplyAlpha"),flags.premultiplyAlpha=options.premultiplyAlpha),"flipY"in options&&(check$1.type(options.flipY,"boolean","invalid texture flip"),flags.flipY=options.flipY),"alignment"in options&&(check$1.oneOf(options.alignment,[1,2,4,8],"invalid texture unpack alignment"),flags.unpackAlignment=options.alignment),"colorSpace"in options&&(check$1.parameter(options.colorSpace,colorSpace,"invalid colorSpace"),flags.colorSpace=colorSpace[options.colorSpace]),"type"in options){var type=options.type;check$1(extensions.oes_texture_float||!("float"===type||"float32"===type),"you must enable the OES_texture_float extension in order to use floating point textures."),check$1(extensions.oes_texture_half_float||!("half float"===type||"float16"===type),"you must enable the OES_texture_half_float extension in order to use 16-bit floating point textures."),check$1(extensions.webgl_depth_texture||!("uint16"===type||"uint32"===type||"depth stencil"===type),"you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures."),check$1.parameter(type,textureTypes,"invalid texture type"),flags.type=textureTypes[type]}var w=flags.width,h=flags.height,c=flags.channels,hasChannels=!1;"shape"in options?(check$1(Array.isArray(options.shape)&&options.shape.length>=2,"shape must be an array"),w=options.shape[0],h=options.shape[1],3===options.shape.length&&(c=options.shape[2],check$1(c>0&&c<=4,"invalid number of channels"),hasChannels=!0),check$1(w>=0&&w<=limits.maxTextureSize,"invalid width"),check$1(h>=0&&h<=limits.maxTextureSize,"invalid height")):("radius"in options&&(w=h=options.radius,check$1(w>=0&&w<=limits.maxTextureSize,"invalid radius")),"width"in options&&(w=options.width,check$1(w>=0&&w<=limits.maxTextureSize,"invalid width")),"height"in options&&(h=options.height,check$1(h>=0&&h<=limits.maxTextureSize,"invalid height")),"channels"in options&&(c=options.channels,check$1(c>0&&c<=4,"invalid number of channels"),hasChannels=!0)),flags.width=0|w,flags.height=0|h,flags.channels=0|c;var hasFormat=!1;if("format"in options){var formatStr=options.format;check$1(extensions.webgl_depth_texture||!("depth"===formatStr||"depth stencil"===formatStr),"you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures."),check$1.parameter(formatStr,textureFormats,"invalid texture format");var internalformat=flags.internalformat=textureFormats[formatStr];flags.format=colorFormats[internalformat],formatStr in textureTypes&&("type"in options||(flags.type=textureTypes[formatStr])),formatStr in compressedTextureFormats&&(flags.compressed=!0),hasFormat=!0}!hasChannels&&hasFormat?flags.channels=FORMAT_CHANNELS[flags.format]:hasChannels&&!hasFormat?flags.channels!==CHANNELS_FORMAT[flags.format]&&(flags.format=flags.internalformat=CHANNELS_FORMAT[flags.channels]):hasFormat&&hasChannels&&check$1(flags.channels===FORMAT_CHANNELS[flags.format],"number of channels inconsistent with specified format")}}function setFlags(flags){gl.pixelStorei(GL_UNPACK_FLIP_Y_WEBGL,flags.flipY),gl.pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL,flags.premultiplyAlpha),gl.pixelStorei(GL_UNPACK_COLORSPACE_CONVERSION_WEBGL,flags.colorSpace),gl.pixelStorei(GL_UNPACK_ALIGNMENT,flags.unpackAlignment)}function TexImage(){TexFlags.call(this),this.xOffset=0,this.yOffset=0,this.data=null,this.needsFree=!1,this.element=null,this.needsCopy=!1}function parseImage(image,options){var data=null;if(isPixelData(options)?data=options:options&&(check$1.type(options,"object","invalid pixel data type"),parseFlags(image,options),"x"in options&&(image.xOffset=0|options.x),"y"in options&&(image.yOffset=0|options.y),isPixelData(options.data)&&(data=options.data)),check$1(!image.compressed||data instanceof Uint8Array,"compressed texture data must be stored in a uint8array"),options.copy){check$1(!data,"can not specify copy and data field for the same texture");var viewW=contextState.viewportWidth,viewH=contextState.viewportHeight;image.width=image.width||viewW-image.xOffset,image.height=image.height||viewH-image.yOffset,image.needsCopy=!0,check$1(image.xOffset>=0&&image.xOffset<viewW&&image.yOffset>=0&&image.yOffset<viewH&&image.width>0&&image.width<=viewW&&image.height>0&&image.height<=viewH,"copy texture read out of bounds")}else if(data){if(isTypedArray(data))image.channels=image.channels||4,image.data=data,"type"in options||image.type!==GL_UNSIGNED_BYTE$5||(image.type=typedArrayCode$1(data));else if(isNumericArray(data))image.channels=image.channels||4,convertData(image,data),image.alignment=1,image.needsFree=!0;else if(isNDArrayLike(data)){var array=data.data;Array.isArray(array)||image.type!==GL_UNSIGNED_BYTE$5||(image.type=typedArrayCode$1(array));var shapeX,shapeY,shapeC,strideX,strideY,strideC,shape=data.shape,stride=data.stride;3===shape.length?(shapeC=shape[2],strideC=stride[2]):(check$1(2===shape.length,"invalid ndarray pixel data, must be 2 or 3D"),shapeC=1,strideC=1),shapeX=shape[0],shapeY=shape[1],strideX=stride[0],strideY=stride[1],image.alignment=1,image.width=shapeX,image.height=shapeY,image.channels=shapeC,image.format=image.internalformat=CHANNELS_FORMAT[shapeC],image.needsFree=!0,transposeData(image,array,strideX,strideY,strideC,data.offset)}else if(isCanvasElement(data)||isOffscreenCanvas(data)||isContext2D(data))isCanvasElement(data)||isOffscreenCanvas(data)?image.element=data:image.element=data.canvas,image.width=image.element.width,image.height=image.element.height,image.channels=4;else if(isBitmap(data))image.element=data,image.width=data.width,image.height=data.height,image.channels=4;else if(isImageElement(data))image.element=data,image.width=data.naturalWidth,image.height=data.naturalHeight,image.channels=4;else if(isVideoElement(data))image.element=data,image.width=data.videoWidth,image.height=data.videoHeight,image.channels=4;else if(isRectArray(data)){var w=image.width||data[0].length,h=image.height||data.length,c=image.channels;c=isArrayLike(data[0][0])?c||data[0][0].length:c||1;for(var arrayShape=flattenUtils.shape(data),n=1,dd=0;dd<arrayShape.length;++dd)n*=arrayShape[dd];var allocData=preConvert(image,n);flattenUtils.flatten(data,arrayShape,"",allocData),postConvert(image,allocData),image.alignment=1,image.width=w,image.height=h,image.channels=c,image.format=image.internalformat=CHANNELS_FORMAT[c],image.needsFree=!0}}else image.width=image.width||1,image.height=image.height||1,image.channels=image.channels||4;image.type===GL_FLOAT$4?check$1(limits.extensions.indexOf("oes_texture_float")>=0,"oes_texture_float extension not enabled"):image.type===GL_HALF_FLOAT_OES$1&&check$1(limits.extensions.indexOf("oes_texture_half_float")>=0,"oes_texture_half_float extension not enabled")}function setImage(info,target,miplevel){var element=info.element,data=info.data,internalformat=info.internalformat,format=info.format,type=info.type,width=info.width,height=info.height;setFlags(info),element?gl.texImage2D(target,miplevel,format,format,type,element):info.compressed?gl.compressedTexImage2D(target,miplevel,internalformat,width,height,0,data):info.needsCopy?(reglPoll(),gl.copyTexImage2D(target,miplevel,format,info.xOffset,info.yOffset,width,height,0)):gl.texImage2D(target,miplevel,format,width,height,0,format,type,data||null)}function setSubImage(info,target,x,y,miplevel){var element=info.element,data=info.data,internalformat=info.internalformat,format=info.format,type=info.type,width=info.width,height=info.height;setFlags(info),element?gl.texSubImage2D(target,miplevel,x,y,format,type,element):info.compressed?gl.compressedTexSubImage2D(target,miplevel,x,y,internalformat,width,height,data):info.needsCopy?(reglPoll(),gl.copyTexSubImage2D(target,miplevel,x,y,info.xOffset,info.yOffset,width,height)):gl.texSubImage2D(target,miplevel,x,y,width,height,format,type,data)}var imagePool=[];function allocImage(){return imagePool.pop()||new TexImage}function freeImage(image){image.needsFree&&pool.freeType(image.data),TexImage.call(image),imagePool.push(image)}function MipMap(){TexFlags.call(this),this.genMipmaps=!1,this.mipmapHint=GL_DONT_CARE,this.mipmask=0,this.images=Array(16)}function parseMipMapFromShape(mipmap,width,height){var img=mipmap.images[0]=allocImage();mipmap.mipmask=1,img.width=mipmap.width=width,img.height=mipmap.height=height,img.channels=mipmap.channels=4}function parseMipMapFromObject(mipmap,options){var imgData=null;if(isPixelData(options))copyFlags(imgData=mipmap.images[0]=allocImage(),mipmap),parseImage(imgData,options),mipmap.mipmask=1;else if(parseFlags(mipmap,options),Array.isArray(options.mipmap))for(var mipData=options.mipmap,i=0;i<mipData.length;++i)copyFlags(imgData=mipmap.images[i]=allocImage(),mipmap),imgData.width>>=i,imgData.height>>=i,parseImage(imgData,mipData[i]),mipmap.mipmask|=1<<i;else copyFlags(imgData=mipmap.images[0]=allocImage(),mipmap),parseImage(imgData,options),mipmap.mipmask=1;copyFlags(mipmap,mipmap.images[0]),!mipmap.compressed||mipmap.internalformat!==GL_COMPRESSED_RGB_S3TC_DXT1_EXT&&mipmap.internalformat!==GL_COMPRESSED_RGBA_S3TC_DXT1_EXT&&mipmap.internalformat!==GL_COMPRESSED_RGBA_S3TC_DXT3_EXT&&mipmap.internalformat!==GL_COMPRESSED_RGBA_S3TC_DXT5_EXT||check$1(mipmap.width%4==0&&mipmap.height%4==0,"for compressed texture formats, mipmap level 0 must have width and height that are a multiple of 4")}function setMipMap(mipmap,target){for(var images=mipmap.images,i=0;i<images.length;++i){if(!images[i])return;setImage(images[i],target,i)}}var mipPool=[];function allocMipMap(){var result=mipPool.pop()||new MipMap;TexFlags.call(result),result.mipmask=0;for(var i=0;i<16;++i)result.images[i]=null;return result}function freeMipMap(mipmap){for(var images=mipmap.images,i=0;i<images.length;++i)images[i]&&freeImage(images[i]),images[i]=null;mipPool.push(mipmap)}function TexInfo(){this.minFilter=GL_NEAREST$1,this.magFilter=GL_NEAREST$1,this.wrapS=GL_CLAMP_TO_EDGE$1,this.wrapT=GL_CLAMP_TO_EDGE$1,this.anisotropic=1,this.genMipmaps=!1,this.mipmapHint=GL_DONT_CARE}function parseTexInfo(info,options){if("min"in options){var minFilter=options.min;check$1.parameter(minFilter,minFilters),info.minFilter=minFilters[minFilter],MIPMAP_FILTERS.indexOf(info.minFilter)>=0&&!("faces"in options)&&(info.genMipmaps=!0)}if("mag"in options){var magFilter=options.mag;check$1.parameter(magFilter,magFilters),info.magFilter=magFilters[magFilter]}var wrapS=info.wrapS,wrapT=info.wrapT;if("wrap"in options){var wrap=options.wrap;"string"==typeof wrap?(check$1.parameter(wrap,wrapModes),wrapS=wrapT=wrapModes[wrap]):Array.isArray(wrap)&&(check$1.parameter(wrap[0],wrapModes),check$1.parameter(wrap[1],wrapModes),wrapS=wrapModes[wrap[0]],wrapT=wrapModes[wrap[1]])}else{if("wrapS"in options){var optWrapS=options.wrapS;check$1.parameter(optWrapS,wrapModes),wrapS=wrapModes[optWrapS]}if("wrapT"in options){var optWrapT=options.wrapT;check$1.parameter(optWrapT,wrapModes),wrapT=wrapModes[optWrapT]}}if(info.wrapS=wrapS,info.wrapT=wrapT,"anisotropic"in options){var anisotropic=options.anisotropic;check$1("number"==typeof anisotropic&&anisotropic>=1&&anisotropic<=limits.maxAnisotropic,"aniso samples must be between 1 and "),info.anisotropic=options.anisotropic}if("mipmap"in options){var hasMipMap=!1;switch(typeof options.mipmap){case"string":check$1.parameter(options.mipmap,mipmapHint,"invalid mipmap hint"),info.mipmapHint=mipmapHint[options.mipmap],info.genMipmaps=!0,hasMipMap=!0;break;case"boolean":hasMipMap=info.genMipmaps=options.mipmap;break;case"object":check$1(Array.isArray(options.mipmap),"invalid mipmap type"),info.genMipmaps=!1,hasMipMap=!0;break;default:check$1.raise("invalid mipmap type")}hasMipMap&&!("min"in options)&&(info.minFilter=GL_NEAREST_MIPMAP_NEAREST$1)}}function setTexInfo(info,target){gl.texParameteri(target,GL_TEXTURE_MIN_FILTER,info.minFilter),gl.texParameteri(target,GL_TEXTURE_MAG_FILTER,info.magFilter),gl.texParameteri(target,GL_TEXTURE_WRAP_S,info.wrapS),gl.texParameteri(target,GL_TEXTURE_WRAP_T,info.wrapT),extensions.ext_texture_filter_anisotropic&&gl.texParameteri(target,GL_TEXTURE_MAX_ANISOTROPY_EXT,info.anisotropic),info.genMipmaps&&(gl.hint(GL_GENERATE_MIPMAP_HINT,info.mipmapHint),gl.generateMipmap(target))}var textureCount=0,textureSet={},numTexUnits=limits.maxTextureUnits,textureUnits=Array(numTexUnits).map((function(){return null}));function REGLTexture(target){TexFlags.call(this),this.mipmask=0,this.internalformat=GL_RGBA$1,this.id=textureCount++,this.refCount=1,this.target=target,this.texture=gl.createTexture(),this.unit=-1,this.bindCount=0,this.texInfo=new TexInfo,config.profile&&(this.stats={size:0})}function tempBind(texture){gl.activeTexture(GL_TEXTURE0$1),gl.bindTexture(texture.target,texture.texture)}function tempRestore(){var prev=textureUnits[0];prev?gl.bindTexture(prev.target,prev.texture):gl.bindTexture(GL_TEXTURE_2D$1,null)}function destroy(texture){var handle=texture.texture;check$1(handle,"must not double destroy texture");var unit=texture.unit,target=texture.target;unit>=0&&(gl.activeTexture(GL_TEXTURE0$1+unit),gl.bindTexture(target,null),textureUnits[unit]=null),gl.deleteTexture(handle),texture.texture=null,texture.params=null,texture.pixels=null,texture.refCount=0,delete textureSet[texture.id],stats.textureCount--}function createTexture2D(a,b){var texture=new REGLTexture(GL_TEXTURE_2D$1);function reglTexture2D(a,b){var texInfo=texture.texInfo;TexInfo.call(texInfo);var mipData=allocMipMap();return"number"==typeof a?parseMipMapFromShape(mipData,0|a,"number"==typeof b?0|b:0|a):a?(check$1.type(a,"object","invalid arguments to regl.texture"),parseTexInfo(texInfo,a),parseMipMapFromObject(mipData,a)):parseMipMapFromShape(mipData,1,1),texInfo.genMipmaps&&(mipData.mipmask=(mipData.width<<1)-1),texture.mipmask=mipData.mipmask,copyFlags(texture,mipData),check$1.texture2D(texInfo,mipData,limits),texture.internalformat=mipData.internalformat,reglTexture2D.width=mipData.width,reglTexture2D.height=mipData.height,tempBind(texture),setMipMap(mipData,GL_TEXTURE_2D$1),setTexInfo(texInfo,GL_TEXTURE_2D$1),tempRestore(),freeMipMap(mipData),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,mipData.width,mipData.height,texInfo.genMipmaps,!1)),reglTexture2D.format=textureFormatsInvert[texture.internalformat],reglTexture2D.type=textureTypesInvert[texture.type],reglTexture2D.mag=magFiltersInvert[texInfo.magFilter],reglTexture2D.min=minFiltersInvert[texInfo.minFilter],reglTexture2D.wrapS=wrapModesInvert[texInfo.wrapS],reglTexture2D.wrapT=wrapModesInvert[texInfo.wrapT],reglTexture2D}function subimage(image,x_,y_,level_){check$1(!!image,"must specify image data");var x=0|x_,y=0|y_,level=0|level_,imageData=allocImage();return copyFlags(imageData,texture),imageData.width=0,imageData.height=0,parseImage(imageData,image),imageData.width=imageData.width||(texture.width>>level)-x,imageData.height=imageData.height||(texture.height>>level)-y,check$1(texture.type===imageData.type&&texture.format===imageData.format&&texture.internalformat===imageData.internalformat,"incompatible format for texture.subimage"),check$1(x>=0&&y>=0&&x+imageData.width<=texture.width&&y+imageData.height<=texture.height,"texture.subimage write out of bounds"),check$1(texture.mipmask&1<<level,"missing mipmap data"),check$1(imageData.data||imageData.element||imageData.needsCopy,"missing image data"),tempBind(texture),setSubImage(imageData,GL_TEXTURE_2D$1,x,y,level),tempRestore(),freeImage(imageData),reglTexture2D}function resize(w_,h_){var w=0|w_,h=0|h_||w;if(w===texture.width&&h===texture.height)return reglTexture2D;reglTexture2D.width=texture.width=w,reglTexture2D.height=texture.height=h,tempBind(texture);for(var i=0;texture.mipmask>>i;++i){var _w=w>>i,_h=h>>i;if(!_w||!_h)break;gl.texImage2D(GL_TEXTURE_2D$1,i,texture.format,_w,_h,0,texture.format,texture.type,null)}return tempRestore(),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,w,h,!1,!1)),reglTexture2D}return textureSet[texture.id]=texture,stats.textureCount++,reglTexture2D(a,b),reglTexture2D.subimage=subimage,reglTexture2D.resize=resize,reglTexture2D._reglType="texture2d",reglTexture2D._texture=texture,config.profile&&(reglTexture2D.stats=texture.stats),reglTexture2D.destroy=function(){texture.decRef()},reglTexture2D}function createTextureCube(a0,a1,a2,a3,a4,a5){var texture=new REGLTexture(GL_TEXTURE_CUBE_MAP$1);textureSet[texture.id]=texture,stats.cubeCount++;var faces=new Array(6);function reglTextureCube(a0,a1,a2,a3,a4,a5){var i,texInfo=texture.texInfo;for(TexInfo.call(texInfo),i=0;i<6;++i)faces[i]=allocMipMap();if("number"!=typeof a0&&a0)if("object"==typeof a0)if(a1)parseMipMapFromObject(faces[0],a0),parseMipMapFromObject(faces[1],a1),parseMipMapFromObject(faces[2],a2),parseMipMapFromObject(faces[3],a3),parseMipMapFromObject(faces[4],a4),parseMipMapFromObject(faces[5],a5);else if(parseTexInfo(texInfo,a0),parseFlags(texture,a0),"faces"in a0){var faceInput=a0.faces;for(check$1(Array.isArray(faceInput)&&6===faceInput.length,"cube faces must be a length 6 array"),i=0;i<6;++i)check$1("object"==typeof faceInput[i]&&!!faceInput[i],"invalid input for cube map face"),copyFlags(faces[i],texture),parseMipMapFromObject(faces[i],faceInput[i])}else for(i=0;i<6;++i)parseMipMapFromObject(faces[i],a0);else check$1.raise("invalid arguments to cube map");else{var s=0|a0||1;for(i=0;i<6;++i)parseMipMapFromShape(faces[i],s,s)}for(copyFlags(texture,faces[0]),check$1.optional((function(){limits.npotTextureCube||check$1(isPow2$1(texture.width)&&isPow2$1(texture.height),"your browser does not support non power or two texture dimensions")})),texInfo.genMipmaps?texture.mipmask=(faces[0].width<<1)-1:texture.mipmask=faces[0].mipmask,check$1.textureCube(texture,texInfo,faces,limits),texture.internalformat=faces[0].internalformat,reglTextureCube.width=faces[0].width,reglTextureCube.height=faces[0].height,tempBind(texture),i=0;i<6;++i)setMipMap(faces[i],GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+i);for(setTexInfo(texInfo,GL_TEXTURE_CUBE_MAP$1),tempRestore(),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,reglTextureCube.width,reglTextureCube.height,texInfo.genMipmaps,!0)),reglTextureCube.format=textureFormatsInvert[texture.internalformat],reglTextureCube.type=textureTypesInvert[texture.type],reglTextureCube.mag=magFiltersInvert[texInfo.magFilter],reglTextureCube.min=minFiltersInvert[texInfo.minFilter],reglTextureCube.wrapS=wrapModesInvert[texInfo.wrapS],reglTextureCube.wrapT=wrapModesInvert[texInfo.wrapT],i=0;i<6;++i)freeMipMap(faces[i]);return reglTextureCube}function subimage(face,image,x_,y_,level_){check$1(!!image,"must specify image data"),check$1("number"==typeof face&&face===(0|face)&&face>=0&&face<6,"invalid face");var x=0|x_,y=0|y_,level=0|level_,imageData=allocImage();return copyFlags(imageData,texture),imageData.width=0,imageData.height=0,parseImage(imageData,image),imageData.width=imageData.width||(texture.width>>level)-x,imageData.height=imageData.height||(texture.height>>level)-y,check$1(texture.type===imageData.type&&texture.format===imageData.format&&texture.internalformat===imageData.internalformat,"incompatible format for texture.subimage"),check$1(x>=0&&y>=0&&x+imageData.width<=texture.width&&y+imageData.height<=texture.height,"texture.subimage write out of bounds"),check$1(texture.mipmask&1<<level,"missing mipmap data"),check$1(imageData.data||imageData.element||imageData.needsCopy,"missing image data"),tempBind(texture),setSubImage(imageData,GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+face,x,y,level),tempRestore(),freeImage(imageData),reglTextureCube}function resize(radius_){var radius=0|radius_;if(radius!==texture.width){reglTextureCube.width=texture.width=radius,reglTextureCube.height=texture.height=radius,tempBind(texture);for(var i=0;i<6;++i)for(var j=0;texture.mipmask>>j;++j)gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+i,j,texture.format,radius>>j,radius>>j,0,texture.format,texture.type,null);return tempRestore(),config.profile&&(texture.stats.size=getTextureSize(texture.internalformat,texture.type,reglTextureCube.width,reglTextureCube.height,!1,!0)),reglTextureCube}}return reglTextureCube(a0,a1,a2,a3,a4,a5),reglTextureCube.subimage=subimage,reglTextureCube.resize=resize,reglTextureCube._reglType="textureCube",reglTextureCube._texture=texture,config.profile&&(reglTextureCube.stats=texture.stats),reglTextureCube.destroy=function(){texture.decRef()},reglTextureCube}function destroyTextures(){for(var i=0;i<numTexUnits;++i)gl.activeTexture(GL_TEXTURE0$1+i),gl.bindTexture(GL_TEXTURE_2D$1,null),textureUnits[i]=null;values(textureSet).forEach(destroy),stats.cubeCount=0,stats.textureCount=0}function restoreTextures(){for(var i=0;i<numTexUnits;++i){var tex=textureUnits[i];tex&&(tex.bindCount=0,tex.unit=-1,textureUnits[i]=null)}values(textureSet).forEach((function(texture){texture.texture=gl.createTexture(),gl.bindTexture(texture.target,texture.texture);for(var i=0;i<32;++i)if(0!=(texture.mipmask&1<<i))if(texture.target===GL_TEXTURE_2D$1)gl.texImage2D(GL_TEXTURE_2D$1,i,texture.internalformat,texture.width>>i,texture.height>>i,0,texture.internalformat,texture.type,null);else for(var j=0;j<6;++j)gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+j,i,texture.internalformat,texture.width>>i,texture.height>>i,0,texture.internalformat,texture.type,null);setTexInfo(texture.texInfo,texture.target)}))}function refreshTextures(){for(var i=0;i<numTexUnits;++i){var tex=textureUnits[i];tex&&(tex.bindCount=0,tex.unit=-1,textureUnits[i]=null),gl.activeTexture(GL_TEXTURE0$1+i),gl.bindTexture(GL_TEXTURE_2D$1,null),gl.bindTexture(GL_TEXTURE_CUBE_MAP$1,null)}}return extend(REGLTexture.prototype,{bind:function(){var texture=this;texture.bindCount+=1;var unit=texture.unit;if(unit<0){for(var i=0;i<numTexUnits;++i){var other=textureUnits[i];if(other){if(other.bindCount>0)continue;other.unit=-1}textureUnits[i]=texture,unit=i;break}unit>=numTexUnits&&check$1.raise("insufficient number of texture units"),config.profile&&stats.maxTextureUnits<unit+1&&(stats.maxTextureUnits=unit+1),texture.unit=unit,gl.activeTexture(GL_TEXTURE0$1+unit),gl.bindTexture(texture.target,texture.texture)}return unit},unbind:function(){this.bindCount-=1},decRef:function(){--this.refCount<=0&&destroy(this)}}),config.profile&&(stats.getTotalTextureSize=function(){var total=0;return Object.keys(textureSet).forEach((function(key){total+=textureSet[key].stats.size})),total}),{create2D:createTexture2D,createCube:createTextureCube,clear:destroyTextures,getTexture:function(wrapper){return null},restore:restoreTextures,refresh:refreshTextures}}FORMAT_SIZES_SPECIAL[GL_RGBA4]=2,FORMAT_SIZES_SPECIAL[GL_RGB5_A1]=2,FORMAT_SIZES_SPECIAL[GL_RGB565]=2,FORMAT_SIZES_SPECIAL[GL_DEPTH_STENCIL]=4,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_S3TC_DXT1_EXT]=.5,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT1_EXT]=.5,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT3_EXT]=1,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT5_EXT]=1,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ATC_WEBGL]=.5,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL]=1,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL]=1,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG]=.5,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG]=.25,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG]=.5,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG]=.25,FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ETC1_WEBGL]=.5;var GL_RENDERBUFFER=36161,GL_RGBA4$1=32854,GL_RGB5_A1$1=32855,GL_RGB565$1=36194,GL_DEPTH_COMPONENT16=33189,GL_STENCIL_INDEX8=36168,GL_DEPTH_STENCIL$1=34041,GL_SRGB8_ALPHA8_EXT=35907,GL_RGBA32F_EXT=34836,GL_RGBA16F_EXT=34842,GL_RGB16F_EXT=34843,FORMAT_SIZES=[];function getRenderbufferSize(format,width,height){return FORMAT_SIZES[format]*width*height}FORMAT_SIZES[GL_RGBA4$1]=2,FORMAT_SIZES[GL_RGB5_A1$1]=2,FORMAT_SIZES[GL_RGB565$1]=2,FORMAT_SIZES[GL_DEPTH_COMPONENT16]=2,FORMAT_SIZES[GL_STENCIL_INDEX8]=1,FORMAT_SIZES[GL_DEPTH_STENCIL$1]=4,FORMAT_SIZES[GL_SRGB8_ALPHA8_EXT]=4,FORMAT_SIZES[GL_RGBA32F_EXT]=16,FORMAT_SIZES[GL_RGBA16F_EXT]=8,FORMAT_SIZES[GL_RGB16F_EXT]=6;var wrapRenderbuffers=function(gl,extensions,limits,stats,config){var formatTypes={rgba4:GL_RGBA4$1,rgb565:GL_RGB565$1,"rgb5 a1":GL_RGB5_A1$1,depth:GL_DEPTH_COMPONENT16,stencil:GL_STENCIL_INDEX8,"depth stencil":GL_DEPTH_STENCIL$1};extensions.ext_srgb&&(formatTypes.srgba=GL_SRGB8_ALPHA8_EXT),extensions.ext_color_buffer_half_float&&(formatTypes.rgba16f=GL_RGBA16F_EXT,formatTypes.rgb16f=GL_RGB16F_EXT),extensions.webgl_color_buffer_float&&(formatTypes.rgba32f=GL_RGBA32F_EXT);var formatTypesInvert=[];Object.keys(formatTypes).forEach((function(key){var val=formatTypes[key];formatTypesInvert[val]=key}));var renderbufferCount=0,renderbufferSet={};function REGLRenderbuffer(renderbuffer){this.id=renderbufferCount++,this.refCount=1,this.renderbuffer=renderbuffer,this.format=GL_RGBA4$1,this.width=0,this.height=0,config.profile&&(this.stats={size:0})}function destroy(rb){var handle=rb.renderbuffer;check$1(handle,"must not double destroy renderbuffer"),gl.bindRenderbuffer(GL_RENDERBUFFER,null),gl.deleteRenderbuffer(handle),rb.renderbuffer=null,rb.refCount=0,delete renderbufferSet[rb.id],stats.renderbufferCount--}function createRenderbuffer(a,b){var renderbuffer=new REGLRenderbuffer(gl.createRenderbuffer());function reglRenderbuffer(a,b){var w=0,h=0,format=GL_RGBA4$1;if("object"==typeof a&&a){var options=a;if("shape"in options){var shape=options.shape;check$1(Array.isArray(shape)&&shape.length>=2,"invalid renderbuffer shape"),w=0|shape[0],h=0|shape[1]}else"radius"in options&&(w=h=0|options.radius),"width"in options&&(w=0|options.width),"height"in options&&(h=0|options.height);"format"in options&&(check$1.parameter(options.format,formatTypes,"invalid renderbuffer format"),format=formatTypes[options.format])}else"number"==typeof a?(w=0|a,h="number"==typeof b?0|b:w):a?check$1.raise("invalid arguments to renderbuffer constructor"):w=h=1;if(check$1(w>0&&h>0&&w<=limits.maxRenderbufferSize&&h<=limits.maxRenderbufferSize,"invalid renderbuffer size"),w!==renderbuffer.width||h!==renderbuffer.height||format!==renderbuffer.format)return reglRenderbuffer.width=renderbuffer.width=w,reglRenderbuffer.height=renderbuffer.height=h,renderbuffer.format=format,gl.bindRenderbuffer(GL_RENDERBUFFER,renderbuffer.renderbuffer),gl.renderbufferStorage(GL_RENDERBUFFER,format,w,h),check$1(0===gl.getError(),"invalid render buffer format"),config.profile&&(renderbuffer.stats.size=getRenderbufferSize(renderbuffer.format,renderbuffer.width,renderbuffer.height)),reglRenderbuffer.format=formatTypesInvert[renderbuffer.format],reglRenderbuffer}function resize(w_,h_){var w=0|w_,h=0|h_||w;return w===renderbuffer.width&&h===renderbuffer.height||(check$1(w>0&&h>0&&w<=limits.maxRenderbufferSize&&h<=limits.maxRenderbufferSize,"invalid renderbuffer size"),reglRenderbuffer.width=renderbuffer.width=w,reglRenderbuffer.height=renderbuffer.height=h,gl.bindRenderbuffer(GL_RENDERBUFFER,renderbuffer.renderbuffer),gl.renderbufferStorage(GL_RENDERBUFFER,renderbuffer.format,w,h),check$1(0===gl.getError(),"invalid render buffer format"),config.profile&&(renderbuffer.stats.size=getRenderbufferSize(renderbuffer.format,renderbuffer.width,renderbuffer.height))),reglRenderbuffer}return renderbufferSet[renderbuffer.id]=renderbuffer,stats.renderbufferCount++,reglRenderbuffer(a,b),reglRenderbuffer.resize=resize,reglRenderbuffer._reglType="renderbuffer",reglRenderbuffer._renderbuffer=renderbuffer,config.profile&&(reglRenderbuffer.stats=renderbuffer.stats),reglRenderbuffer.destroy=function(){renderbuffer.decRef()},reglRenderbuffer}function restoreRenderbuffers(){values(renderbufferSet).forEach((function(rb){rb.renderbuffer=gl.createRenderbuffer(),gl.bindRenderbuffer(GL_RENDERBUFFER,rb.renderbuffer),gl.renderbufferStorage(GL_RENDERBUFFER,rb.format,rb.width,rb.height)})),gl.bindRenderbuffer(GL_RENDERBUFFER,null)}return REGLRenderbuffer.prototype.decRef=function(){--this.refCount<=0&&destroy(this)},config.profile&&(stats.getTotalRenderbufferSize=function(){var total=0;return Object.keys(renderbufferSet).forEach((function(key){total+=renderbufferSet[key].stats.size})),total}),{create:createRenderbuffer,clear:function(){values(renderbufferSet).forEach(destroy)},restore:restoreRenderbuffers}},GL_FRAMEBUFFER$1=36160,GL_RENDERBUFFER$1=36161,GL_TEXTURE_2D$2=3553,GL_TEXTURE_CUBE_MAP_POSITIVE_X$2=34069,GL_COLOR_ATTACHMENT0$1=36064,GL_DEPTH_ATTACHMENT=36096,GL_STENCIL_ATTACHMENT=36128,GL_DEPTH_STENCIL_ATTACHMENT=33306,GL_FRAMEBUFFER_COMPLETE$1=36053,GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT=36054,GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT=36055,GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS=36057,GL_FRAMEBUFFER_UNSUPPORTED=36061,GL_HALF_FLOAT_OES$2=36193,GL_UNSIGNED_BYTE$6=5121,GL_FLOAT$5=5126,GL_RGB$1=6407,GL_RGBA$2=6408,GL_DEPTH_COMPONENT$1=6402,colorTextureFormatEnums=[GL_RGB$1,GL_RGBA$2],textureFormatChannels=[];textureFormatChannels[GL_RGBA$2]=4,textureFormatChannels[GL_RGB$1]=3;var textureTypeSizes=[];textureTypeSizes[GL_UNSIGNED_BYTE$6]=1,textureTypeSizes[GL_FLOAT$5]=4,textureTypeSizes[GL_HALF_FLOAT_OES$2]=2;var GL_DEPTH_COMPONENT16$1=33189,GL_STENCIL_INDEX8$1=36168,GL_DEPTH_STENCIL$2=34041,colorRenderbufferFormatEnums=[32854,32855,36194,35907,34842,34843,34836],statusCode={};function wrapFBOState(gl,extensions,limits,textureState,renderbufferState,stats){var framebufferState={cur:null,next:null,dirty:!1,setFBO:null},colorTextureFormats=["rgba"],colorRenderbufferFormats=["rgba4","rgb565","rgb5 a1"];extensions.ext_srgb&&colorRenderbufferFormats.push("srgba"),extensions.ext_color_buffer_half_float&&colorRenderbufferFormats.push("rgba16f","rgb16f"),extensions.webgl_color_buffer_float&&colorRenderbufferFormats.push("rgba32f");var colorTypes=["uint8"];function FramebufferAttachment(target,texture,renderbuffer){this.target=target,this.texture=texture,this.renderbuffer=renderbuffer;var w=0,h=0;texture?(w=texture.width,h=texture.height):renderbuffer&&(w=renderbuffer.width,h=renderbuffer.height),this.width=w,this.height=h}function decRef(attachment){attachment&&(attachment.texture&&attachment.texture._texture.decRef(),attachment.renderbuffer&&attachment.renderbuffer._renderbuffer.decRef())}function incRefAndCheckShape(attachment,width,height){if(attachment)if(attachment.texture){var texture=attachment.texture._texture,tw=Math.max(1,texture.width),th=Math.max(1,texture.height);check$1(tw===width&&th===height,"inconsistent width/height for supplied texture"),texture.refCount+=1}else{var renderbuffer=attachment.renderbuffer._renderbuffer;check$1(renderbuffer.width===width&&renderbuffer.height===height,"inconsistent width/height for renderbuffer"),renderbuffer.refCount+=1}}function attach(location,attachment){attachment&&(attachment.texture?gl.framebufferTexture2D(GL_FRAMEBUFFER$1,location,attachment.target,attachment.texture._texture.texture,0):gl.framebufferRenderbuffer(GL_FRAMEBUFFER$1,location,GL_RENDERBUFFER$1,attachment.renderbuffer._renderbuffer.renderbuffer))}function parseAttachment(attachment){var target=GL_TEXTURE_2D$2,texture=null,renderbuffer=null,data=attachment;"object"==typeof attachment&&(data=attachment.data,"target"in attachment&&(target=0|attachment.target)),check$1.type(data,"function","invalid attachment data");var type=data._reglType;return"texture2d"===type?(texture=data,check$1(target===GL_TEXTURE_2D$2)):"textureCube"===type?(texture=data,check$1(target>=GL_TEXTURE_CUBE_MAP_POSITIVE_X$2&&target<GL_TEXTURE_CUBE_MAP_POSITIVE_X$2+6,"invalid cube map target")):"renderbuffer"===type?(renderbuffer=data,target=GL_RENDERBUFFER$1):check$1.raise("invalid regl object for attachment"),new FramebufferAttachment(target,texture,renderbuffer)}function allocAttachment(width,height,isTexture,format,type){if(isTexture){var texture=textureState.create2D({width:width,height:height,format:format,type:type});return texture._texture.refCount=0,new FramebufferAttachment(GL_TEXTURE_2D$2,texture,null)}var rb=renderbufferState.create({width:width,height:height,format:format});return rb._renderbuffer.refCount=0,new FramebufferAttachment(GL_RENDERBUFFER$1,null,rb)}function unwrapAttachment(attachment){return attachment&&(attachment.texture||attachment.renderbuffer)}function resizeAttachment(attachment,w,h){attachment&&(attachment.texture?attachment.texture.resize(w,h):attachment.renderbuffer&&attachment.renderbuffer.resize(w,h),attachment.width=w,attachment.height=h)}extensions.oes_texture_half_float&&colorTypes.push("half float","float16"),extensions.oes_texture_float&&colorTypes.push("float","float32");var framebufferCount=0,framebufferSet={};function REGLFramebuffer(){this.id=framebufferCount++,framebufferSet[this.id]=this,this.framebuffer=gl.createFramebuffer(),this.width=0,this.height=0,this.colorAttachments=[],this.depthAttachment=null,this.stencilAttachment=null,this.depthStencilAttachment=null}function decFBORefs(framebuffer){framebuffer.colorAttachments.forEach(decRef),decRef(framebuffer.depthAttachment),decRef(framebuffer.stencilAttachment),decRef(framebuffer.depthStencilAttachment)}function destroy(framebuffer){var handle=framebuffer.framebuffer;check$1(handle,"must not double destroy framebuffer"),gl.deleteFramebuffer(handle),framebuffer.framebuffer=null,stats.framebufferCount--,delete framebufferSet[framebuffer.id]}function updateFramebuffer(framebuffer){var i;gl.bindFramebuffer(GL_FRAMEBUFFER$1,framebuffer.framebuffer);var colorAttachments=framebuffer.colorAttachments;for(i=0;i<colorAttachments.length;++i)attach(GL_COLOR_ATTACHMENT0$1+i,colorAttachments[i]);for(i=colorAttachments.length;i<limits.maxColorAttachments;++i)gl.framebufferTexture2D(GL_FRAMEBUFFER$1,GL_COLOR_ATTACHMENT0$1+i,GL_TEXTURE_2D$2,null,0);gl.framebufferTexture2D(GL_FRAMEBUFFER$1,GL_DEPTH_STENCIL_ATTACHMENT,GL_TEXTURE_2D$2,null,0),gl.framebufferTexture2D(GL_FRAMEBUFFER$1,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D$2,null,0),gl.framebufferTexture2D(GL_FRAMEBUFFER$1,GL_STENCIL_ATTACHMENT,GL_TEXTURE_2D$2,null,0),attach(GL_DEPTH_ATTACHMENT,framebuffer.depthAttachment),attach(GL_STENCIL_ATTACHMENT,framebuffer.stencilAttachment),attach(GL_DEPTH_STENCIL_ATTACHMENT,framebuffer.depthStencilAttachment);var status=gl.checkFramebufferStatus(GL_FRAMEBUFFER$1);gl.isContextLost()||status===GL_FRAMEBUFFER_COMPLETE$1||check$1.raise("framebuffer configuration not supported, status = "+statusCode[status]),gl.bindFramebuffer(GL_FRAMEBUFFER$1,framebufferState.next?framebufferState.next.framebuffer:null),framebufferState.cur=framebufferState.next,gl.getError()}function createFBO(a0,a1){var framebuffer=new REGLFramebuffer;function reglFramebuffer(a,b){var i;check$1(framebufferState.next!==framebuffer,"can not update framebuffer which is currently in use");var width=0,height=0,needsDepth=!0,needsStencil=!0,colorBuffer=null,colorTexture=!0,colorFormat="rgba",colorType="uint8",colorCount=1,depthBuffer=null,stencilBuffer=null,depthStencilBuffer=null,depthStencilTexture=!1;if("number"==typeof a)width=0|a,height=0|b||width;else if(a){check$1.type(a,"object","invalid arguments for framebuffer");var options=a;if("shape"in options){var shape=options.shape;check$1(Array.isArray(shape)&&shape.length>=2,"invalid shape for framebuffer"),width=shape[0],height=shape[1]}else"radius"in options&&(width=height=options.radius),"width"in options&&(width=options.width),"height"in options&&(height=options.height);("color"in options||"colors"in options)&&(colorBuffer=options.color||options.colors,Array.isArray(colorBuffer)&&check$1(1===colorBuffer.length||extensions.webgl_draw_buffers,"multiple render targets not supported")),colorBuffer||("colorCount"in options&&(colorCount=0|options.colorCount,check$1(colorCount>0,"invalid color buffer count")),"colorTexture"in options&&(colorTexture=!!options.colorTexture,colorFormat="rgba4"),"colorType"in options&&(colorType=options.colorType,colorTexture?(check$1(extensions.oes_texture_float||!("float"===colorType||"float32"===colorType),"you must enable OES_texture_float in order to use floating point framebuffer objects"),check$1(extensions.oes_texture_half_float||!("half float"===colorType||"float16"===colorType),"you must enable OES_texture_half_float in order to use 16-bit floating point framebuffer objects")):"half float"===colorType||"float16"===colorType?(check$1(extensions.ext_color_buffer_half_float,"you must enable EXT_color_buffer_half_float to use 16-bit render buffers"),colorFormat="rgba16f"):"float"!==colorType&&"float32"!==colorType||(check$1(extensions.webgl_color_buffer_float,"you must enable WEBGL_color_buffer_float in order to use 32-bit floating point renderbuffers"),colorFormat="rgba32f"),check$1.oneOf(colorType,colorTypes,"invalid color type")),"colorFormat"in options&&(colorFormat=options.colorFormat,colorTextureFormats.indexOf(colorFormat)>=0?colorTexture=!0:colorRenderbufferFormats.indexOf(colorFormat)>=0?colorTexture=!1:check$1.optional((function(){colorTexture?check$1.oneOf(options.colorFormat,colorTextureFormats,"invalid color format for texture"):check$1.oneOf(options.colorFormat,colorRenderbufferFormats,"invalid color format for renderbuffer")})))),("depthTexture"in options||"depthStencilTexture"in options)&&(depthStencilTexture=!(!options.depthTexture&&!options.depthStencilTexture),check$1(!depthStencilTexture||extensions.webgl_depth_texture,"webgl_depth_texture extension not supported")),"depth"in options&&("boolean"==typeof options.depth?needsDepth=options.depth:(depthBuffer=options.depth,needsStencil=!1)),"stencil"in options&&("boolean"==typeof options.stencil?needsStencil=options.stencil:(stencilBuffer=options.stencil,needsDepth=!1)),"depthStencil"in options&&("boolean"==typeof options.depthStencil?needsDepth=needsStencil=options.depthStencil:(depthStencilBuffer=options.depthStencil,needsDepth=!1,needsStencil=!1))}else width=height=1;var colorAttachments=null,depthAttachment=null,stencilAttachment=null,depthStencilAttachment=null;if(Array.isArray(colorBuffer))colorAttachments=colorBuffer.map(parseAttachment);else if(colorBuffer)colorAttachments=[parseAttachment(colorBuffer)];else for(colorAttachments=new Array(colorCount),i=0;i<colorCount;++i)colorAttachments[i]=allocAttachment(width,height,colorTexture,colorFormat,colorType);check$1(extensions.webgl_draw_buffers||colorAttachments.length<=1,"you must enable the WEBGL_draw_buffers extension in order to use multiple color buffers."),check$1(colorAttachments.length<=limits.maxColorAttachments,"too many color attachments, not supported"),width=width||colorAttachments[0].width,height=height||colorAttachments[0].height,depthBuffer?depthAttachment=parseAttachment(depthBuffer):needsDepth&&!needsStencil&&(depthAttachment=allocAttachment(width,height,depthStencilTexture,"depth","uint32")),stencilBuffer?stencilAttachment=parseAttachment(stencilBuffer):needsStencil&&!needsDepth&&(stencilAttachment=allocAttachment(width,height,!1,"stencil","uint8")),depthStencilBuffer?depthStencilAttachment=parseAttachment(depthStencilBuffer):!depthBuffer&&!stencilBuffer&&needsStencil&&needsDepth&&(depthStencilAttachment=allocAttachment(width,height,depthStencilTexture,"depth stencil","depth stencil")),check$1(!!depthBuffer+!!stencilBuffer+!!depthStencilBuffer<=1,"invalid framebuffer configuration, can specify exactly one depth/stencil attachment");var commonColorAttachmentSize=null;for(i=0;i<colorAttachments.length;++i)if(incRefAndCheckShape(colorAttachments[i],width,height),check$1(!colorAttachments[i]||colorAttachments[i].texture&&colorTextureFormatEnums.indexOf(colorAttachments[i].texture._texture.format)>=0||colorAttachments[i].renderbuffer&&colorRenderbufferFormatEnums.indexOf(colorAttachments[i].renderbuffer._renderbuffer.format)>=0,"framebuffer color attachment "+i+" is invalid"),colorAttachments[i]&&colorAttachments[i].texture){var colorAttachmentSize=textureFormatChannels[colorAttachments[i].texture._texture.format]*textureTypeSizes[colorAttachments[i].texture._texture.type];null===commonColorAttachmentSize?commonColorAttachmentSize=colorAttachmentSize:check$1(commonColorAttachmentSize===colorAttachmentSize,"all color attachments much have the same number of bits per pixel.")}return incRefAndCheckShape(depthAttachment,width,height),check$1(!depthAttachment||depthAttachment.texture&&depthAttachment.texture._texture.format===GL_DEPTH_COMPONENT$1||depthAttachment.renderbuffer&&depthAttachment.renderbuffer._renderbuffer.format===GL_DEPTH_COMPONENT16$1,"invalid depth attachment for framebuffer object"),incRefAndCheckShape(stencilAttachment,width,height),check$1(!stencilAttachment||stencilAttachment.renderbuffer&&stencilAttachment.renderbuffer._renderbuffer.format===GL_STENCIL_INDEX8$1,"invalid stencil attachment for framebuffer object"),incRefAndCheckShape(depthStencilAttachment,width,height),check$1(!depthStencilAttachment||depthStencilAttachment.texture&&depthStencilAttachment.texture._texture.format===GL_DEPTH_STENCIL$2||depthStencilAttachment.renderbuffer&&depthStencilAttachment.renderbuffer._renderbuffer.format===GL_DEPTH_STENCIL$2,"invalid depth-stencil attachment for framebuffer object"),decFBORefs(framebuffer),framebuffer.width=width,framebuffer.height=height,framebuffer.colorAttachments=colorAttachments,framebuffer.depthAttachment=depthAttachment,framebuffer.stencilAttachment=stencilAttachment,framebuffer.depthStencilAttachment=depthStencilAttachment,reglFramebuffer.color=colorAttachments.map(unwrapAttachment),reglFramebuffer.depth=unwrapAttachment(depthAttachment),reglFramebuffer.stencil=unwrapAttachment(stencilAttachment),reglFramebuffer.depthStencil=unwrapAttachment(depthStencilAttachment),reglFramebuffer.width=framebuffer.width,reglFramebuffer.height=framebuffer.height,updateFramebuffer(framebuffer),reglFramebuffer}function resize(w_,h_){check$1(framebufferState.next!==framebuffer,"can not resize a framebuffer which is currently in use");var w=Math.max(0|w_,1),h=Math.max(0|h_||w,1);if(w===framebuffer.width&&h===framebuffer.height)return reglFramebuffer;for(var colorAttachments=framebuffer.colorAttachments,i=0;i<colorAttachments.length;++i)resizeAttachment(colorAttachments[i],w,h);return resizeAttachment(framebuffer.depthAttachment,w,h),resizeAttachment(framebuffer.stencilAttachment,w,h),resizeAttachment(framebuffer.depthStencilAttachment,w,h),framebuffer.width=reglFramebuffer.width=w,framebuffer.height=reglFramebuffer.height=h,updateFramebuffer(framebuffer),reglFramebuffer}return stats.framebufferCount++,reglFramebuffer(a0,a1),extend(reglFramebuffer,{resize:resize,_reglType:"framebuffer",_framebuffer:framebuffer,destroy:function(){destroy(framebuffer),decFBORefs(framebuffer)},use:function(block){framebufferState.setFBO({framebuffer:reglFramebuffer},block)}})}function createCubeFBO(options){var faces=Array(6);function reglFramebufferCube(a){var i;check$1(faces.indexOf(framebufferState.next)<0,"can not update framebuffer which is currently in use");var colorCubes,params={color:null},radius=0,colorBuffer=null,colorFormat="rgba",colorType="uint8",colorCount=1;if("number"==typeof a)radius=0|a;else if(a){check$1.type(a,"object","invalid arguments for framebuffer");var options=a;if("shape"in options){var shape=options.shape;check$1(Array.isArray(shape)&&shape.length>=2,"invalid shape for framebuffer"),check$1(shape[0]===shape[1],"cube framebuffer must be square"),radius=shape[0]}else"radius"in options&&(radius=0|options.radius),"width"in options?(radius=0|options.width,"height"in options&&check$1(options.height===radius,"must be square")):"height"in options&&(radius=0|options.height);("color"in options||"colors"in options)&&(colorBuffer=options.color||options.colors,Array.isArray(colorBuffer)&&check$1(1===colorBuffer.length||extensions.webgl_draw_buffers,"multiple render targets not supported")),colorBuffer||("colorCount"in options&&(colorCount=0|options.colorCount,check$1(colorCount>0,"invalid color buffer count")),"colorType"in options&&(check$1.oneOf(options.colorType,colorTypes,"invalid color type"),colorType=options.colorType),"colorFormat"in options&&(colorFormat=options.colorFormat,check$1.oneOf(options.colorFormat,colorTextureFormats,"invalid color format for texture"))),"depth"in options&&(params.depth=options.depth),"stencil"in options&&(params.stencil=options.stencil),"depthStencil"in options&&(params.depthStencil=options.depthStencil)}else radius=1;if(colorBuffer)if(Array.isArray(colorBuffer))for(colorCubes=[],i=0;i<colorBuffer.length;++i)colorCubes[i]=colorBuffer[i];else colorCubes=[colorBuffer];else{colorCubes=Array(colorCount);var cubeMapParams={radius:radius,format:colorFormat,type:colorType};for(i=0;i<colorCount;++i)colorCubes[i]=textureState.createCube(cubeMapParams)}for(params.color=Array(colorCubes.length),i=0;i<colorCubes.length;++i){var cube=colorCubes[i];check$1("function"==typeof cube&&"textureCube"===cube._reglType,"invalid cube map"),radius=radius||cube.width,check$1(cube.width===radius&&cube.height===radius,"invalid cube map shape"),params.color[i]={target:GL_TEXTURE_CUBE_MAP_POSITIVE_X$2,data:colorCubes[i]}}for(i=0;i<6;++i){for(var j=0;j<colorCubes.length;++j)params.color[j].target=GL_TEXTURE_CUBE_MAP_POSITIVE_X$2+i;i>0&&(params.depth=faces[0].depth,params.stencil=faces[0].stencil,params.depthStencil=faces[0].depthStencil),faces[i]?faces[i](params):faces[i]=createFBO(params)}return extend(reglFramebufferCube,{width:radius,height:radius,color:colorCubes})}function resize(radius_){var i,radius=0|radius_;if(check$1(radius>0&&radius<=limits.maxCubeMapSize,"invalid radius for cube fbo"),radius===reglFramebufferCube.width)return reglFramebufferCube;var colors=reglFramebufferCube.color;for(i=0;i<colors.length;++i)colors[i].resize(radius);for(i=0;i<6;++i)faces[i].resize(radius);return reglFramebufferCube.width=reglFramebufferCube.height=radius,reglFramebufferCube}return reglFramebufferCube(options),extend(reglFramebufferCube,{faces:faces,resize:resize,_reglType:"framebufferCube",destroy:function(){faces.forEach((function(f){f.destroy()}))}})}function restoreFramebuffers(){framebufferState.cur=null,framebufferState.next=null,framebufferState.dirty=!0,values(framebufferSet).forEach((function(fb){fb.framebuffer=gl.createFramebuffer(),updateFramebuffer(fb)}))}return extend(framebufferState,{getFramebuffer:function(object){if("function"==typeof object&&"framebuffer"===object._reglType){var fbo=object._framebuffer;if(fbo instanceof REGLFramebuffer)return fbo}return null},create:createFBO,createCube:createCubeFBO,clear:function(){values(framebufferSet).forEach(destroy)},restore:restoreFramebuffers})}statusCode[GL_FRAMEBUFFER_COMPLETE$1]="complete",statusCode[GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT]="incomplete attachment",statusCode[GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS]="incomplete dimensions",statusCode[GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT]="incomplete, missing attachment",statusCode[GL_FRAMEBUFFER_UNSUPPORTED]="unsupported";var GL_FLOAT$6=5126,GL_ARRAY_BUFFER$1=34962,GL_ELEMENT_ARRAY_BUFFER$1=34963,VAO_OPTIONS=["attributes","elements","offset","count","primitive","instances"];function AttributeRecord(){this.state=0,this.x=0,this.y=0,this.z=0,this.w=0,this.buffer=null,this.size=0,this.normalized=!1,this.type=GL_FLOAT$6,this.offset=0,this.stride=0,this.divisor=0}function wrapAttributeState(gl,extensions,limits,stats,bufferState,elementState,drawState){for(var NUM_ATTRIBUTES=limits.maxAttributes,attributeBindings=new Array(NUM_ATTRIBUTES),i=0;i<NUM_ATTRIBUTES;++i)attributeBindings[i]=new AttributeRecord;var vaoCount=0,vaoSet={},state={Record:AttributeRecord,scope:{},state:attributeBindings,currentVAO:null,targetVAO:null,restore:extVAO()?restoreVAO:function(){},createVAO:createVAO,getVAO:getVAO,destroyBuffer:destroyBuffer,setVAO:extVAO()?setVAOEXT:setVAOEmulated,clear:extVAO()?destroyVAOEXT:function(){}};function destroyBuffer(buffer){for(var i=0;i<attributeBindings.length;++i){var record=attributeBindings[i];record.buffer===buffer&&(gl.disableVertexAttribArray(i),record.buffer=null)}}function extVAO(){return extensions.oes_vertex_array_object}function extInstanced(){return extensions.angle_instanced_arrays}function getVAO(vao){return"function"==typeof vao&&vao._vao?vao._vao:null}function setVAOEXT(vao){if(vao!==state.currentVAO){var ext=extVAO();vao?ext.bindVertexArrayOES(vao.vao):ext.bindVertexArrayOES(null),state.currentVAO=vao}}function setVAOEmulated(vao){if(vao!==state.currentVAO){if(vao)vao.bindAttrs();else{for(var exti=extInstanced(),i=0;i<attributeBindings.length;++i){var binding=attributeBindings[i];binding.buffer?(gl.enableVertexAttribArray(i),binding.buffer.bind(),gl.vertexAttribPointer(i,binding.size,binding.type,binding.normalized,binding.stride,binding.offfset),exti&&binding.divisor&&exti.vertexAttribDivisorANGLE(i,binding.divisor)):(gl.disableVertexAttribArray(i),gl.vertexAttrib4f(i,binding.x,binding.y,binding.z,binding.w))}drawState.elements?gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1,drawState.elements.buffer.buffer):gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1,null)}state.currentVAO=vao}}function destroyVAOEXT(){values(vaoSet).forEach((function(vao){vao.destroy()}))}function REGLVAO(){this.id=++vaoCount,this.attributes=[],this.elements=null,this.ownsElements=!1,this.count=0,this.offset=0,this.instances=-1,this.primitive=4;var extension=extVAO();this.vao=extension?extension.createVertexArrayOES():null,vaoSet[this.id]=this,this.buffers=[]}function restoreVAO(){extVAO()&&values(vaoSet).forEach((function(vao){vao.refresh()}))}function createVAO(_attr){var vao=new REGLVAO;function updateVAO(options){var attributes;if(Array.isArray(options))attributes=options,vao.elements&&vao.ownsElements&&vao.elements.destroy(),vao.elements=null,vao.ownsElements=!1,vao.offset=0,vao.count=0,vao.instances=-1,vao.primitive=4;else{if(check$1("object"==typeof options,"invalid arguments for create vao"),check$1("attributes"in options,"must specify attributes for vao"),options.elements){var elements=options.elements;vao.ownsElements?"function"==typeof elements&&"elements"===elements._reglType?(vao.elements.destroy(),vao.ownsElements=!1):(vao.elements(elements),vao.ownsElements=!1):elementState.getElements(options.elements)?(vao.elements=options.elements,vao.ownsElements=!1):(vao.elements=elementState.create(options.elements),vao.ownsElements=!0)}else vao.elements=null,vao.ownsElements=!1;attributes=options.attributes,vao.offset=0,vao.count=-1,vao.instances=-1,vao.primitive=4,vao.elements&&(vao.count=vao.elements._elements.vertCount,vao.primitive=vao.elements._elements.primType),"offset"in options&&(vao.offset=0|options.offset),"count"in options&&(vao.count=0|options.count),"instances"in options&&(vao.instances=0|options.instances),"primitive"in options&&(check$1(options.primitive in primTypes,"bad primitive type: "+options.primitive),vao.primitive=primTypes[options.primitive]),check$1.optional((()=>{for(var keys=Object.keys(options),i=0;i<keys.length;++i)check$1(VAO_OPTIONS.indexOf(keys[i])>=0,'invalid option for vao: "'+keys[i]+'" valid options are '+VAO_OPTIONS)})),check$1(Array.isArray(attributes),"attributes must be an array")}check$1(attributes.length<NUM_ATTRIBUTES,"too many attributes"),check$1(attributes.length>0,"must specify at least one attribute");var bufUpdated={},nattributes=vao.attributes;nattributes.length=attributes.length;for(var i=0;i<attributes.length;++i){var buf,spec=attributes[i],rec=nattributes[i]=new AttributeRecord,data=spec.data||spec;Array.isArray(data)||isTypedArray(data)||isNDArrayLike(data)?(vao.buffers[i]&&(buf=vao.buffers[i],isTypedArray(data)&&buf._buffer.byteLength>=data.byteLength?buf.subdata(data):(buf.destroy(),vao.buffers[i]=null)),vao.buffers[i]||(buf=vao.buffers[i]=bufferState.create(spec,GL_ARRAY_BUFFER$1,!1,!0)),rec.buffer=bufferState.getBuffer(buf),rec.size=0|rec.buffer.dimension,rec.normalized=!1,rec.type=rec.buffer.dtype,rec.offset=0,rec.stride=0,rec.divisor=0,rec.state=1,bufUpdated[i]=1):bufferState.getBuffer(spec)?(rec.buffer=bufferState.getBuffer(spec),rec.size=0|rec.buffer.dimension,rec.normalized=!1,rec.type=rec.buffer.dtype,rec.offset=0,rec.stride=0,rec.divisor=0,rec.state=1):bufferState.getBuffer(spec.buffer)?(rec.buffer=bufferState.getBuffer(spec.buffer),rec.size=0|(+spec.size||rec.buffer.dimension),rec.normalized=!!spec.normalized||!1,"type"in spec?(check$1.parameter(spec.type,glTypes,"invalid buffer type"),rec.type=glTypes[spec.type]):rec.type=rec.buffer.dtype,rec.offset=0|(spec.offset||0),rec.stride=0|(spec.stride||0),rec.divisor=0|(spec.divisor||0),rec.state=1,check$1(rec.size>=1&&rec.size<=4,"size must be between 1 and 4"),check$1(rec.offset>=0,"invalid offset"),check$1(rec.stride>=0&&rec.stride<=255,"stride must be between 0 and 255"),check$1(rec.divisor>=0,"divisor must be positive"),check$1(!rec.divisor||!!extensions.angle_instanced_arrays,"ANGLE_instanced_arrays must be enabled to use divisor")):"x"in spec?(check$1(i>0,"first attribute must not be a constant"),rec.x=+spec.x||0,rec.y=+spec.y||0,rec.z=+spec.z||0,rec.w=+spec.w||0,rec.state=2):check$1(!1,"invalid attribute spec for location "+i)}for(var j=0;j<vao.buffers.length;++j)!bufUpdated[j]&&vao.buffers[j]&&(vao.buffers[j].destroy(),vao.buffers[j]=null);return vao.refresh(),updateVAO}return stats.vaoCount+=1,updateVAO.destroy=function(){for(var j=0;j<vao.buffers.length;++j)vao.buffers[j]&&vao.buffers[j].destroy();vao.buffers.length=0,vao.ownsElements&&(vao.elements.destroy(),vao.elements=null,vao.ownsElements=!1),vao.destroy()},updateVAO._vao=vao,updateVAO._reglType="vao",updateVAO(_attr)}return REGLVAO.prototype.bindAttrs=function(){for(var exti=extInstanced(),attributes=this.attributes,i=0;i<attributes.length;++i){var attr=attributes[i];attr.buffer?(gl.enableVertexAttribArray(i),gl.bindBuffer(GL_ARRAY_BUFFER$1,attr.buffer.buffer),gl.vertexAttribPointer(i,attr.size,attr.type,attr.normalized,attr.stride,attr.offset),exti&&attr.divisor&&exti.vertexAttribDivisorANGLE(i,attr.divisor)):(gl.disableVertexAttribArray(i),gl.vertexAttrib4f(i,attr.x,attr.y,attr.z,attr.w))}for(var j=attributes.length;j<NUM_ATTRIBUTES;++j)gl.disableVertexAttribArray(j);var elements=elementState.getElements(this.elements);elements?gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1,elements.buffer.buffer):gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1,null)},REGLVAO.prototype.refresh=function(){var ext=extVAO();ext&&(ext.bindVertexArrayOES(this.vao),this.bindAttrs(),state.currentVAO=null,ext.bindVertexArrayOES(null))},REGLVAO.prototype.destroy=function(){if(this.vao){var extension=extVAO();this===state.currentVAO&&(state.currentVAO=null,extension.bindVertexArrayOES(null)),extension.deleteVertexArrayOES(this.vao),this.vao=null}this.ownsElements&&(this.elements.destroy(),this.elements=null,this.ownsElements=!1),vaoSet[this.id]&&(delete vaoSet[this.id],stats.vaoCount-=1)},state}var GL_FRAGMENT_SHADER=35632,GL_VERTEX_SHADER=35633,GL_ACTIVE_UNIFORMS=35718,GL_ACTIVE_ATTRIBUTES=35721;function wrapShaderState(gl,stringStore,stats,config){var fragShaders={},vertShaders={};function ActiveInfo(name,id,location,info){this.name=name,this.id=id,this.location=location,this.info=info}function insertActiveInfo(list,info){for(var i=0;i<list.length;++i)if(list[i].id===info.id)return void(list[i].location=info.location);list.push(info)}function getShader(type,id,command){var cache=type===GL_FRAGMENT_SHADER?fragShaders:vertShaders,shader=cache[id];if(!shader){var source=stringStore.str(id);shader=gl.createShader(type),gl.shaderSource(shader,source),gl.compileShader(shader),check$1.shaderError(gl,shader,source,type,command),cache[id]=shader}return shader}var programCache={},programList=[],PROGRAM_COUNTER=0;function REGLProgram(fragId,vertId){this.id=PROGRAM_COUNTER++,this.fragId=fragId,this.vertId=vertId,this.program=null,this.uniforms=[],this.attributes=[],this.refCount=1,config.profile&&(this.stats={uniformsCount:0,attributesCount:0})}function linkProgram(desc,command,attributeLocations){var i,info,fragShader=getShader(GL_FRAGMENT_SHADER,desc.fragId),vertShader=getShader(GL_VERTEX_SHADER,desc.vertId),program=desc.program=gl.createProgram();if(gl.attachShader(program,fragShader),gl.attachShader(program,vertShader),attributeLocations)for(i=0;i<attributeLocations.length;++i){var binding=attributeLocations[i];gl.bindAttribLocation(program,binding[0],binding[1])}gl.linkProgram(program),check$1.linkError(gl,program,stringStore.str(desc.fragId),stringStore.str(desc.vertId),command);var numUniforms=gl.getProgramParameter(program,GL_ACTIVE_UNIFORMS);config.profile&&(desc.stats.uniformsCount=numUniforms);var uniforms=desc.uniforms;for(i=0;i<numUniforms;++i)if(info=gl.getActiveUniform(program,i)){if(info.size>1)for(var j=0;j<info.size;++j){var name=info.name.replace("[0]","["+j+"]");insertActiveInfo(uniforms,new ActiveInfo(name,stringStore.id(name),gl.getUniformLocation(program,name),info))}var uniName=info.name;info.size>1&&(uniName=uniName.replace("[0]","")),insertActiveInfo(uniforms,new ActiveInfo(uniName,stringStore.id(uniName),gl.getUniformLocation(program,uniName),info))}var numAttributes=gl.getProgramParameter(program,GL_ACTIVE_ATTRIBUTES);config.profile&&(desc.stats.attributesCount=numAttributes);var attributes=desc.attributes;for(i=0;i<numAttributes;++i)(info=gl.getActiveAttrib(program,i))&&insertActiveInfo(attributes,new ActiveInfo(info.name,stringStore.id(info.name),gl.getAttribLocation(program,info.name),info))}function restoreShaders(){fragShaders={},vertShaders={};for(var i=0;i<programList.length;++i)linkProgram(programList[i],null,programList[i].attributes.map((function(info){return[info.location,info.name]})))}return config.profile&&(stats.getMaxUniformsCount=function(){var m=0;return programList.forEach((function(desc){desc.stats.uniformsCount>m&&(m=desc.stats.uniformsCount)})),m},stats.getMaxAttributesCount=function(){var m=0;return programList.forEach((function(desc){desc.stats.attributesCount>m&&(m=desc.stats.attributesCount)})),m}),{clear:function(){var deleteShader=gl.deleteShader.bind(gl);values(fragShaders).forEach(deleteShader),fragShaders={},values(vertShaders).forEach(deleteShader),vertShaders={},programList.forEach((function(desc){gl.deleteProgram(desc.program)})),programList.length=0,programCache={},stats.shaderCount=0},program:function(vertId,fragId,command,attribLocations){check$1.command(vertId>=0,"missing vertex shader",command),check$1.command(fragId>=0,"missing fragment shader",command);var cache=programCache[fragId];cache||(cache=programCache[fragId]={});var prevProgram=cache[vertId];if(prevProgram&&(prevProgram.refCount++,!attribLocations))return prevProgram;var program=new REGLProgram(fragId,vertId);return stats.shaderCount++,linkProgram(program,command,attribLocations),prevProgram||(cache[vertId]=program),programList.push(program),extend(program,{destroy:function(){if(program.refCount--,program.refCount<=0){gl.deleteProgram(program.program);var idx=programList.indexOf(program);programList.splice(idx,1),stats.shaderCount--}cache[program.vertId].refCount<=0&&(gl.deleteShader(vertShaders[program.vertId]),delete vertShaders[program.vertId],delete programCache[program.fragId][program.vertId]),Object.keys(programCache[program.fragId]).length||(gl.deleteShader(fragShaders[program.fragId]),delete fragShaders[program.fragId],delete programCache[program.fragId])}})},restore:restoreShaders,shader:getShader,frag:-1,vert:-1}}var GL_RGBA$3=6408,GL_UNSIGNED_BYTE$7=5121,GL_PACK_ALIGNMENT=3333,GL_FLOAT$7=5126;function wrapReadPixels(gl,framebufferState,reglPoll,context,glAttributes,extensions,limits){function readPixelsImpl(input){var type;null===framebufferState.next?(check$1(glAttributes.preserveDrawingBuffer,'you must create a webgl context with "preserveDrawingBuffer":true in order to read pixels from the drawing buffer'),type=GL_UNSIGNED_BYTE$7):(check$1(null!==framebufferState.next.colorAttachments[0].texture,"You cannot read from a renderbuffer"),type=framebufferState.next.colorAttachments[0].texture._texture.type,check$1.optional((function(){extensions.oes_texture_float?(check$1(type===GL_UNSIGNED_BYTE$7||type===GL_FLOAT$7,"Reading from a framebuffer is only allowed for the types 'uint8' and 'float'"),type===GL_FLOAT$7&&check$1(limits.readFloat,"Reading 'float' values is not permitted in your browser. For a fallback, please see: https://www.npmjs.com/package/glsl-read-float")):check$1(type===GL_UNSIGNED_BYTE$7,"Reading from a framebuffer is only allowed for the type 'uint8'")})));var x=0,y=0,width=context.framebufferWidth,height=context.framebufferHeight,data=null;isTypedArray(input)?data=input:input&&(check$1.type(input,"object","invalid arguments to regl.read()"),x=0|input.x,y=0|input.y,check$1(x>=0&&x<context.framebufferWidth,"invalid x offset for regl.read"),check$1(y>=0&&y<context.framebufferHeight,"invalid y offset for regl.read"),width=0|(input.width||context.framebufferWidth-x),height=0|(input.height||context.framebufferHeight-y),data=input.data||null),data&&(type===GL_UNSIGNED_BYTE$7?check$1(data instanceof Uint8Array,"buffer must be 'Uint8Array' when reading from a framebuffer of type 'uint8'"):type===GL_FLOAT$7&&check$1(data instanceof Float32Array,"buffer must be 'Float32Array' when reading from a framebuffer of type 'float'")),check$1(width>0&&width+x<=context.framebufferWidth,"invalid width for read pixels"),check$1(height>0&&height+y<=context.framebufferHeight,"invalid height for read pixels"),reglPoll();var size=width*height*4;return data||(type===GL_UNSIGNED_BYTE$7?data=new Uint8Array(size):type===GL_FLOAT$7&&(data=data||new Float32Array(size))),check$1.isTypedArray(data,"data buffer for regl.read() must be a typedarray"),check$1(data.byteLength>=size,"data buffer for regl.read() too small"),gl.pixelStorei(GL_PACK_ALIGNMENT,4),gl.readPixels(x,y,width,height,GL_RGBA$3,type,data),data}function readPixelsFBO(options){var result;return framebufferState.setFBO({framebuffer:options.framebuffer},(function(){result=readPixelsImpl(options)})),result}function readPixels(options){return options&&"framebuffer"in options?readPixelsFBO(options):readPixelsImpl(options)}return readPixels}function slice(x){return Array.prototype.slice.call(x)}function join(x){return slice(x).join("")}function createEnvironment(){var varCounter=0,linkedNames=[],linkedValues=[];function link(value){for(var i=0;i<linkedValues.length;++i)if(linkedValues[i]===value)return linkedNames[i];var name="g"+varCounter++;return linkedNames.push(name),linkedValues.push(value),name}function block(){var code=[];function push(){code.push.apply(code,slice(arguments))}var vars=[];function def(){var name="v"+varCounter++;return vars.push(name),arguments.length>0&&(code.push(name,"="),code.push.apply(code,slice(arguments)),code.push(";")),name}return extend(push,{def:def,toString:function(){return join([vars.length>0?"var "+vars.join(",")+";":"",join(code)])}})}function scope(){var entry=block(),exit=block(),entryToString=entry.toString,exitToString=exit.toString;function save(object,prop){exit(object,prop,"=",entry.def(object,prop),";")}return extend((function(){entry.apply(entry,slice(arguments))}),{def:entry.def,entry:entry,exit:exit,save:save,set:function(object,prop,value){save(object,prop),entry(object,prop,"=",value,";")},toString:function(){return entryToString()+exitToString()}})}function conditional(){var pred=join(arguments),thenBlock=scope(),elseBlock=scope(),thenToString=thenBlock.toString,elseToString=elseBlock.toString;return extend(thenBlock,{then:function(){return thenBlock.apply(thenBlock,slice(arguments)),this},else:function(){return elseBlock.apply(elseBlock,slice(arguments)),this},toString:function(){var elseClause=elseToString();return elseClause&&(elseClause="else{"+elseClause+"}"),join(["if(",pred,"){",thenToString(),"}",elseClause])}})}var globalBlock=block(),procedures={};function proc(name,count){var args=[];function arg(){var name="a"+args.length;return args.push(name),name}count=count||0;for(var i=0;i<count;++i)arg();var body=scope(),bodyToString=body.toString;return procedures[name]=extend(body,{arg:arg,toString:function(){return join(["function(",args.join(),"){",bodyToString(),"}"])}})}function compile(){var code=['"use strict";',globalBlock,"return {"];Object.keys(procedures).forEach((function(name){code.push('"',name,'":',procedures[name].toString(),",")})),code.push("}");var src=join(code).replace(/;/g,";\n").replace(/}/g,"}\n").replace(/{/g,"{\n");return Function.apply(null,linkedNames.concat(src)).apply(null,linkedValues)}return{global:globalBlock,link:link,block:block,proc:proc,scope:scope,cond:conditional,compile:compile}}var CUTE_COMPONENTS="xyzw".split(""),GL_UNSIGNED_BYTE$8=5121,ATTRIB_STATE_POINTER=1,ATTRIB_STATE_CONSTANT=2,DYN_FUNC$1=0,DYN_PROP$1=1,DYN_CONTEXT$1=2,DYN_STATE$1=3,DYN_THUNK=4,DYN_CONSTANT$1=5,DYN_ARRAY$1=6,S_DITHER="dither",S_BLEND_ENABLE="blend.enable",S_BLEND_COLOR="blend.color",S_BLEND_EQUATION="blend.equation",S_BLEND_FUNC="blend.func",S_DEPTH_ENABLE="depth.enable",S_DEPTH_FUNC="depth.func",S_DEPTH_RANGE="depth.range",S_DEPTH_MASK="depth.mask",S_COLOR_MASK="colorMask",S_CULL_ENABLE="cull.enable",S_CULL_FACE="cull.face",S_FRONT_FACE="frontFace",S_LINE_WIDTH="lineWidth",S_POLYGON_OFFSET_ENABLE="polygonOffset.enable",S_POLYGON_OFFSET_OFFSET="polygonOffset.offset",S_SAMPLE_ALPHA="sample.alpha",S_SAMPLE_ENABLE="sample.enable",S_SAMPLE_COVERAGE="sample.coverage",S_STENCIL_ENABLE="stencil.enable",S_STENCIL_MASK="stencil.mask",S_STENCIL_FUNC="stencil.func",S_STENCIL_OPFRONT="stencil.opFront",S_STENCIL_OPBACK="stencil.opBack",S_SCISSOR_ENABLE="scissor.enable",S_SCISSOR_BOX="scissor.box",S_VIEWPORT="viewport",S_PROFILE="profile",S_FRAMEBUFFER="framebuffer",S_VERT="vert",S_FRAG="frag",S_ELEMENTS="elements",S_PRIMITIVE="primitive",S_COUNT="count",S_OFFSET="offset",S_INSTANCES="instances",S_VAO="vao",SUFFIX_WIDTH="Width",SUFFIX_HEIGHT="Height",S_FRAMEBUFFER_WIDTH=S_FRAMEBUFFER+SUFFIX_WIDTH,S_FRAMEBUFFER_HEIGHT=S_FRAMEBUFFER+SUFFIX_HEIGHT,S_VIEWPORT_WIDTH=S_VIEWPORT+SUFFIX_WIDTH,S_VIEWPORT_HEIGHT=S_VIEWPORT+SUFFIX_HEIGHT,S_DRAWINGBUFFER="drawingBuffer",S_DRAWINGBUFFER_WIDTH=S_DRAWINGBUFFER+SUFFIX_WIDTH,S_DRAWINGBUFFER_HEIGHT=S_DRAWINGBUFFER+SUFFIX_HEIGHT,NESTED_OPTIONS=[S_BLEND_FUNC,S_BLEND_EQUATION,S_STENCIL_FUNC,S_STENCIL_OPFRONT,S_STENCIL_OPBACK,S_SAMPLE_COVERAGE,S_VIEWPORT,S_SCISSOR_BOX,S_POLYGON_OFFSET_OFFSET],GL_ARRAY_BUFFER$2=34962,GL_ELEMENT_ARRAY_BUFFER$2=34963,GL_TEXTURE_2D$3=3553,GL_TEXTURE_CUBE_MAP$2=34067,GL_CULL_FACE=2884,GL_BLEND=3042,GL_DITHER=3024,GL_STENCIL_TEST=2960,GL_DEPTH_TEST=2929,GL_SCISSOR_TEST=3089,GL_POLYGON_OFFSET_FILL=32823,GL_SAMPLE_ALPHA_TO_COVERAGE=32926,GL_SAMPLE_COVERAGE=32928,GL_FLOAT$8=5126,GL_FLOAT_VEC2=35664,GL_FLOAT_VEC3=35665,GL_FLOAT_VEC4=35666,GL_INT$3=5124,GL_INT_VEC2=35667,GL_INT_VEC3=35668,GL_INT_VEC4=35669,GL_BOOL=35670,GL_BOOL_VEC2=35671,GL_BOOL_VEC3=35672,GL_BOOL_VEC4=35673,GL_FLOAT_MAT2=35674,GL_FLOAT_MAT3=35675,GL_FLOAT_MAT4=35676,GL_SAMPLER_2D=35678,GL_SAMPLER_CUBE=35680,GL_TRIANGLES$1=4,GL_FRONT=1028,GL_BACK=1029,GL_CW=2304,GL_CCW=2305,GL_MIN_EXT=32775,GL_MAX_EXT=32776,GL_ALWAYS=519,GL_KEEP=7680,GL_ZERO=0,GL_ONE=1,GL_FUNC_ADD=32774,GL_LESS=513,GL_FRAMEBUFFER$2=36160,GL_COLOR_ATTACHMENT0$2=36064,blendFuncs={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,"dst color":774,"one minus dst color":775,"dst alpha":772,"one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771,"one minus constant alpha":32772,"src alpha saturate":776},invalidBlendCombinations=["constant color, constant alpha","one minus constant color, constant alpha","constant color, one minus constant alpha","one minus constant color, one minus constant alpha","constant alpha, constant color","constant alpha, one minus constant color","one minus constant alpha, constant color","one minus constant alpha, one minus constant color"],compareFuncs={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},stencilOps={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},shaderType={frag:35632,vert:35633},orientationType={cw:GL_CW,ccw:GL_CCW};function isBufferArgs(x){return Array.isArray(x)||isTypedArray(x)||isNDArrayLike(x)}function sortState(state){return state.sort((function(a,b){return a===S_VIEWPORT?-1:b===S_VIEWPORT?1:a<b?-1:1}))}function Declaration(thisDep,contextDep,propDep,append){this.thisDep=thisDep,this.contextDep=contextDep,this.propDep=propDep,this.append=append}function isStatic(decl){return decl&&!(decl.thisDep||decl.contextDep||decl.propDep)}function createStaticDecl(append){return new Declaration(!1,!1,!1,append)}function createDynamicDecl(dyn,append){var type=dyn.type;if(type===DYN_FUNC$1){var numArgs=dyn.data.length;return new Declaration(!0,numArgs>=1,numArgs>=2,append)}if(type===DYN_THUNK){var data=dyn.data;return new Declaration(data.thisDep,data.contextDep,data.propDep,append)}if(type===DYN_CONSTANT$1)return new Declaration(!1,!1,!1,append);if(type===DYN_ARRAY$1){for(var thisDep=!1,contextDep=!1,propDep=!1,i=0;i<dyn.data.length;++i){var subDyn=dyn.data[i];if(subDyn.type===DYN_PROP$1)propDep=!0;else if(subDyn.type===DYN_CONTEXT$1)contextDep=!0;else if(subDyn.type===DYN_STATE$1)thisDep=!0;else if(subDyn.type===DYN_FUNC$1){thisDep=!0;var subArgs=subDyn.data;subArgs>=1&&(contextDep=!0),subArgs>=2&&(propDep=!0)}else subDyn.type===DYN_THUNK&&(thisDep=thisDep||subDyn.data.thisDep,contextDep=contextDep||subDyn.data.contextDep,propDep=propDep||subDyn.data.propDep)}return new Declaration(thisDep,contextDep,propDep,append)}return new Declaration(type===DYN_STATE$1,type===DYN_CONTEXT$1,type===DYN_PROP$1,append)}var SCOPE_DECL=new Declaration(!1,!1,!1,(function(){}));function reglCore(gl,stringStore,extensions,limits,bufferState,elementState,textureState,framebufferState,uniformState,attributeState,shaderState,drawState,contextState,timer,config){var AttributeRecord=attributeState.Record,blendEquations={add:32774,subtract:32778,"reverse subtract":32779};extensions.ext_blend_minmax&&(blendEquations.min=GL_MIN_EXT,blendEquations.max=GL_MAX_EXT);var extInstancing=extensions.angle_instanced_arrays,extDrawBuffers=extensions.webgl_draw_buffers,extVertexArrays=extensions.oes_vertex_array_object,currentState={dirty:!0,profile:config.profile},nextState={},GL_STATE_NAMES=[],GL_FLAGS={},GL_VARIABLES={};function propName(name){return name.replace(".","_")}function stateFlag(sname,cap,init){var name=propName(sname);GL_STATE_NAMES.push(sname),nextState[name]=currentState[name]=!!init,GL_FLAGS[name]=cap}function stateVariable(sname,func,init){var name=propName(sname);GL_STATE_NAMES.push(sname),Array.isArray(init)?(currentState[name]=init.slice(),nextState[name]=init.slice()):currentState[name]=nextState[name]=init,GL_VARIABLES[name]=func}stateFlag(S_DITHER,GL_DITHER),stateFlag(S_BLEND_ENABLE,GL_BLEND),stateVariable(S_BLEND_COLOR,"blendColor",[0,0,0,0]),stateVariable(S_BLEND_EQUATION,"blendEquationSeparate",[GL_FUNC_ADD,GL_FUNC_ADD]),stateVariable(S_BLEND_FUNC,"blendFuncSeparate",[GL_ONE,GL_ZERO,GL_ONE,GL_ZERO]),stateFlag(S_DEPTH_ENABLE,GL_DEPTH_TEST,!0),stateVariable(S_DEPTH_FUNC,"depthFunc",GL_LESS),stateVariable(S_DEPTH_RANGE,"depthRange",[0,1]),stateVariable(S_DEPTH_MASK,"depthMask",!0),stateVariable(S_COLOR_MASK,S_COLOR_MASK,[!0,!0,!0,!0]),stateFlag(S_CULL_ENABLE,GL_CULL_FACE),stateVariable(S_CULL_FACE,"cullFace",GL_BACK),stateVariable(S_FRONT_FACE,S_FRONT_FACE,GL_CCW),stateVariable(S_LINE_WIDTH,S_LINE_WIDTH,1),stateFlag(S_POLYGON_OFFSET_ENABLE,GL_POLYGON_OFFSET_FILL),stateVariable(S_POLYGON_OFFSET_OFFSET,"polygonOffset",[0,0]),stateFlag(S_SAMPLE_ALPHA,GL_SAMPLE_ALPHA_TO_COVERAGE),stateFlag(S_SAMPLE_ENABLE,GL_SAMPLE_COVERAGE),stateVariable(S_SAMPLE_COVERAGE,"sampleCoverage",[1,!1]),stateFlag(S_STENCIL_ENABLE,GL_STENCIL_TEST),stateVariable(S_STENCIL_MASK,"stencilMask",-1),stateVariable(S_STENCIL_FUNC,"stencilFunc",[GL_ALWAYS,0,-1]),stateVariable(S_STENCIL_OPFRONT,"stencilOpSeparate",[GL_FRONT,GL_KEEP,GL_KEEP,GL_KEEP]),stateVariable(S_STENCIL_OPBACK,"stencilOpSeparate",[GL_BACK,GL_KEEP,GL_KEEP,GL_KEEP]),stateFlag(S_SCISSOR_ENABLE,GL_SCISSOR_TEST),stateVariable(S_SCISSOR_BOX,"scissor",[0,0,gl.drawingBufferWidth,gl.drawingBufferHeight]),stateVariable(S_VIEWPORT,S_VIEWPORT,[0,0,gl.drawingBufferWidth,gl.drawingBufferHeight]);var sharedState={gl:gl,context:contextState,strings:stringStore,next:nextState,current:currentState,draw:drawState,elements:elementState,buffer:bufferState,shader:shaderState,attributes:attributeState.state,vao:attributeState,uniforms:uniformState,framebuffer:framebufferState,extensions:extensions,timer:timer,isBufferArgs:isBufferArgs},sharedConstants={primTypes:primTypes,compareFuncs:compareFuncs,blendFuncs:blendFuncs,blendEquations:blendEquations,stencilOps:stencilOps,glTypes:glTypes,orientationType:orientationType};check$1.optional((function(){sharedState.isArrayLike=isArrayLike})),extDrawBuffers&&(sharedConstants.backBuffer=[GL_BACK],sharedConstants.drawBuffer=loop(limits.maxDrawbuffers,(function(i){return 0===i?[0]:loop(i,(function(j){return GL_COLOR_ATTACHMENT0$2+j}))})));var drawCallCounter=0;function createREGLEnvironment(){var env=createEnvironment(),link=env.link,global=env.global;env.id=drawCallCounter++,env.batchId="0";var SHARED=link(sharedState),shared=env.shared={props:"a0"};Object.keys(sharedState).forEach((function(prop){shared[prop]=global.def(SHARED,".",prop)})),check$1.optional((function(){env.CHECK=link(check$1),env.commandStr=check$1.guessCommand(),env.command=link(env.commandStr),env.assert=function(block,pred,message){block("if(!(",pred,"))",this.CHECK,".commandRaise(",link(message),",",this.command,");")},sharedConstants.invalidBlendCombinations=invalidBlendCombinations}));var nextVars=env.next={},currentVars=env.current={};Object.keys(GL_VARIABLES).forEach((function(variable){Array.isArray(currentState[variable])&&(nextVars[variable]=global.def(shared.next,".",variable),currentVars[variable]=global.def(shared.current,".",variable))}));var constants=env.constants={};Object.keys(sharedConstants).forEach((function(name){constants[name]=global.def(JSON.stringify(sharedConstants[name]))})),env.invoke=function(block,x){switch(x.type){case DYN_FUNC$1:var argList=["this",shared.context,shared.props,env.batchId];return block.def(link(x.data),".call(",argList.slice(0,Math.max(x.data.length+1,4)),")");case DYN_PROP$1:return block.def(shared.props,x.data);case DYN_CONTEXT$1:return block.def(shared.context,x.data);case DYN_STATE$1:return block.def("this",x.data);case DYN_THUNK:return x.data.append(env,block),x.data.ref;case DYN_CONSTANT$1:return x.data.toString();case DYN_ARRAY$1:return x.data.map((function(y){return env.invoke(block,y)}))}},env.attribCache={};var scopeAttribs={};return env.scopeAttrib=function(name){var id=stringStore.id(name);if(id in scopeAttribs)return scopeAttribs[id];var binding=attributeState.scope[id];return binding||(binding=attributeState.scope[id]=new AttributeRecord),scopeAttribs[id]=link(binding)},env}function parseProfile(options){var profileEnable,staticOptions=options.static,dynamicOptions=options.dynamic;if(S_PROFILE in staticOptions){var value=!!staticOptions[S_PROFILE];(profileEnable=createStaticDecl((function(env,scope){return value}))).enable=value}else if(S_PROFILE in dynamicOptions){var dyn=dynamicOptions[S_PROFILE];profileEnable=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))}return profileEnable}function parseFramebuffer(options,env){var staticOptions=options.static,dynamicOptions=options.dynamic;if(S_FRAMEBUFFER in staticOptions){var framebuffer=staticOptions[S_FRAMEBUFFER];return framebuffer?(framebuffer=framebufferState.getFramebuffer(framebuffer),check$1.command(framebuffer,"invalid framebuffer object"),createStaticDecl((function(env,block){var FRAMEBUFFER=env.link(framebuffer),shared=env.shared;block.set(shared.framebuffer,".next",FRAMEBUFFER);var CONTEXT=shared.context;return block.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,FRAMEBUFFER+".width"),block.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,FRAMEBUFFER+".height"),FRAMEBUFFER}))):createStaticDecl((function(env,scope){var shared=env.shared;scope.set(shared.framebuffer,".next","null");var CONTEXT=shared.context;return scope.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,CONTEXT+"."+S_DRAWINGBUFFER_WIDTH),scope.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,CONTEXT+"."+S_DRAWINGBUFFER_HEIGHT),"null"}))}if(S_FRAMEBUFFER in dynamicOptions){var dyn=dynamicOptions[S_FRAMEBUFFER];return createDynamicDecl(dyn,(function(env,scope){var FRAMEBUFFER_FUNC=env.invoke(scope,dyn),shared=env.shared,FRAMEBUFFER_STATE=shared.framebuffer,FRAMEBUFFER=scope.def(FRAMEBUFFER_STATE,".getFramebuffer(",FRAMEBUFFER_FUNC,")");check$1.optional((function(){env.assert(scope,"!"+FRAMEBUFFER_FUNC+"||"+FRAMEBUFFER,"invalid framebuffer object")})),scope.set(FRAMEBUFFER_STATE,".next",FRAMEBUFFER);var CONTEXT=shared.context;return scope.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,FRAMEBUFFER+"?"+FRAMEBUFFER+".width:"+CONTEXT+"."+S_DRAWINGBUFFER_WIDTH),scope.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,FRAMEBUFFER+"?"+FRAMEBUFFER+".height:"+CONTEXT+"."+S_DRAWINGBUFFER_HEIGHT),FRAMEBUFFER}))}return null}function parseViewportScissor(options,framebuffer,env){var staticOptions=options.static,dynamicOptions=options.dynamic;function parseBox(param){if(param in staticOptions){var box=staticOptions[param];check$1.commandType(box,"object","invalid "+param,env.commandStr);var w,h,isStatic=!0,x=0|box.x,y=0|box.y;return"width"in box?(w=0|box.width,check$1.command(w>=0,"invalid "+param,env.commandStr)):isStatic=!1,"height"in box?(h=0|box.height,check$1.command(h>=0,"invalid "+param,env.commandStr)):isStatic=!1,new Declaration(!isStatic&&framebuffer&&framebuffer.thisDep,!isStatic&&framebuffer&&framebuffer.contextDep,!isStatic&&framebuffer&&framebuffer.propDep,(function(env,scope){var CONTEXT=env.shared.context,BOX_W=w;"width"in box||(BOX_W=scope.def(CONTEXT,".",S_FRAMEBUFFER_WIDTH,"-",x));var BOX_H=h;return"height"in box||(BOX_H=scope.def(CONTEXT,".",S_FRAMEBUFFER_HEIGHT,"-",y)),[x,y,BOX_W,BOX_H]}))}if(param in dynamicOptions){var dynBox=dynamicOptions[param],result=createDynamicDecl(dynBox,(function(env,scope){var BOX=env.invoke(scope,dynBox);check$1.optional((function(){env.assert(scope,BOX+"&&typeof "+BOX+'==="object"',"invalid "+param)}));var CONTEXT=env.shared.context,BOX_X=scope.def(BOX,".x|0"),BOX_Y=scope.def(BOX,".y|0"),BOX_W=scope.def('"width" in ',BOX,"?",BOX,".width|0:","(",CONTEXT,".",S_FRAMEBUFFER_WIDTH,"-",BOX_X,")"),BOX_H=scope.def('"height" in ',BOX,"?",BOX,".height|0:","(",CONTEXT,".",S_FRAMEBUFFER_HEIGHT,"-",BOX_Y,")");return check$1.optional((function(){env.assert(scope,BOX_W+">=0&&"+BOX_H+">=0","invalid "+param)})),[BOX_X,BOX_Y,BOX_W,BOX_H]}));return framebuffer&&(result.thisDep=result.thisDep||framebuffer.thisDep,result.contextDep=result.contextDep||framebuffer.contextDep,result.propDep=result.propDep||framebuffer.propDep),result}return framebuffer?new Declaration(framebuffer.thisDep,framebuffer.contextDep,framebuffer.propDep,(function(env,scope){var CONTEXT=env.shared.context;return[0,0,scope.def(CONTEXT,".",S_FRAMEBUFFER_WIDTH),scope.def(CONTEXT,".",S_FRAMEBUFFER_HEIGHT)]})):null}var viewport=parseBox(S_VIEWPORT);if(viewport){var prevViewport=viewport;viewport=new Declaration(viewport.thisDep,viewport.contextDep,viewport.propDep,(function(env,scope){var VIEWPORT=prevViewport.append(env,scope),CONTEXT=env.shared.context;return scope.set(CONTEXT,"."+S_VIEWPORT_WIDTH,VIEWPORT[2]),scope.set(CONTEXT,"."+S_VIEWPORT_HEIGHT,VIEWPORT[3]),VIEWPORT}))}return{viewport:viewport,scissor_box:parseBox(S_SCISSOR_BOX)}}function parseAttribLocations(options,attributes){var staticOptions=options.static;if("string"==typeof staticOptions[S_FRAG]&&"string"==typeof staticOptions[S_VERT]){if(Object.keys(attributes.dynamic).length>0)return null;var staticAttributes=attributes.static,sAttributes=Object.keys(staticAttributes);if(sAttributes.length>0&&"number"==typeof staticAttributes[sAttributes[0]]){for(var bindings=[],i=0;i<sAttributes.length;++i)check$1("number"==typeof staticAttributes[sAttributes[i]],"must specify all vertex attribute locations when using vaos"),bindings.push([0|staticAttributes[sAttributes[i]],sAttributes[i]]);return bindings}}return null}function parseProgram(options,env,attribLocations){var staticOptions=options.static,dynamicOptions=options.dynamic;function parseShader(name){if(name in staticOptions){var id=stringStore.id(staticOptions[name]);check$1.optional((function(){shaderState.shader(shaderType[name],id,check$1.guessCommand())}));var result=createStaticDecl((function(){return id}));return result.id=id,result}if(name in dynamicOptions){var dyn=dynamicOptions[name];return createDynamicDecl(dyn,(function(env,scope){var str=env.invoke(scope,dyn),id=scope.def(env.shared.strings,".id(",str,")");return check$1.optional((function(){scope(env.shared.shader,".shader(",shaderType[name],",",id,",",env.command,");")})),id}))}return null}var progVar,frag=parseShader(S_FRAG),vert=parseShader(S_VERT),program=null;return isStatic(frag)&&isStatic(vert)?(program=shaderState.program(vert.id,frag.id,null,attribLocations),progVar=createStaticDecl((function(env,scope){return env.link(program)}))):progVar=new Declaration(frag&&frag.thisDep||vert&&vert.thisDep,frag&&frag.contextDep||vert&&vert.contextDep,frag&&frag.propDep||vert&&vert.propDep,(function(env,scope){var fragId,SHADER_STATE=env.shared.shader;fragId=frag?frag.append(env,scope):scope.def(SHADER_STATE,".",S_FRAG);var progDef=SHADER_STATE+".program("+(vert?vert.append(env,scope):scope.def(SHADER_STATE,".",S_VERT))+","+fragId;return check$1.optional((function(){progDef+=","+env.command})),scope.def(progDef+")")})),{frag:frag,vert:vert,progVar:progVar,program:program}}function parseDraw(options,env){var staticOptions=options.static,dynamicOptions=options.dynamic,staticDraw={},vaoActive=!1;function parseVAO(){if(S_VAO in staticOptions){var vao=staticOptions[S_VAO];return null!==vao&&null===attributeState.getVAO(vao)&&(vao=attributeState.createVAO(vao)),vaoActive=!0,staticDraw.vao=vao,createStaticDecl((function(env){var vaoRef=attributeState.getVAO(vao);return vaoRef?env.link(vaoRef):"null"}))}if(S_VAO in dynamicOptions){vaoActive=!0;var dyn=dynamicOptions[S_VAO];return createDynamicDecl(dyn,(function(env,scope){var vaoRef=env.invoke(scope,dyn);return scope.def(env.shared.vao+".getVAO("+vaoRef+")")}))}return null}var vao=parseVAO(),elementsActive=!1;function parseElements(){if(S_ELEMENTS in staticOptions){var elements=staticOptions[S_ELEMENTS];if(staticDraw.elements=elements,isBufferArgs(elements)){var e=staticDraw.elements=elementState.create(elements,!0);elements=elementState.getElements(e),elementsActive=!0}else elements&&(elements=elementState.getElements(elements),elementsActive=!0,check$1.command(elements,"invalid elements",env.commandStr));var result=createStaticDecl((function(env,scope){if(elements){var result=env.link(elements);return env.ELEMENTS=result,result}return env.ELEMENTS=null,null}));return result.value=elements,result}if(S_ELEMENTS in dynamicOptions){elementsActive=!0;var dyn=dynamicOptions[S_ELEMENTS];return createDynamicDecl(dyn,(function(env,scope){var shared=env.shared,IS_BUFFER_ARGS=shared.isBufferArgs,ELEMENT_STATE=shared.elements,elementDefn=env.invoke(scope,dyn),elements=scope.def("null"),elementStream=scope.def(IS_BUFFER_ARGS,"(",elementDefn,")"),ifte=env.cond(elementStream).then(elements,"=",ELEMENT_STATE,".createStream(",elementDefn,");").else(elements,"=",ELEMENT_STATE,".getElements(",elementDefn,");");return check$1.optional((function(){env.assert(ifte.else,"!"+elementDefn+"||"+elements,"invalid elements")})),scope.entry(ifte),scope.exit(env.cond(elementStream).then(ELEMENT_STATE,".destroyStream(",elements,");")),env.ELEMENTS=elements,elements}))}return vaoActive?new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao+".currentVAO?"+env.shared.elements+".getElements("+env.shared.vao+".currentVAO.elements):null")})):null}var elements=parseElements();function parsePrimitive(){if(S_PRIMITIVE in staticOptions){var primitive=staticOptions[S_PRIMITIVE];return staticDraw.primitive=primitive,check$1.commandParameter(primitive,primTypes,"invalid primitve",env.commandStr),createStaticDecl((function(env,scope){return primTypes[primitive]}))}if(S_PRIMITIVE in dynamicOptions){var dynPrimitive=dynamicOptions[S_PRIMITIVE];return createDynamicDecl(dynPrimitive,(function(env,scope){var PRIM_TYPES=env.constants.primTypes,prim=env.invoke(scope,dynPrimitive);return check$1.optional((function(){env.assert(scope,prim+" in "+PRIM_TYPES,"invalid primitive, must be one of "+Object.keys(primTypes))})),scope.def(PRIM_TYPES,"[",prim,"]")}))}return elementsActive?isStatic(elements)?elements.value?createStaticDecl((function(env,scope){return scope.def(env.ELEMENTS,".primType")})):createStaticDecl((function(){return GL_TRIANGLES$1})):new Declaration(elements.thisDep,elements.contextDep,elements.propDep,(function(env,scope){var elements=env.ELEMENTS;return scope.def(elements,"?",elements,".primType:",GL_TRIANGLES$1)})):vaoActive?new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao+".currentVAO?"+env.shared.vao+".currentVAO.primitive:"+GL_TRIANGLES$1)})):null}function parseParam(param,isOffset){if(param in staticOptions){var value=0|staticOptions[param];return isOffset?staticDraw.offset=value:staticDraw.instances=value,check$1.command(!isOffset||value>=0,"invalid "+param,env.commandStr),createStaticDecl((function(env,scope){return isOffset&&(env.OFFSET=value),value}))}if(param in dynamicOptions){var dynValue=dynamicOptions[param];return createDynamicDecl(dynValue,(function(env,scope){var result=env.invoke(scope,dynValue);return isOffset&&(env.OFFSET=result,check$1.optional((function(){env.assert(scope,result+">=0","invalid "+param)}))),result}))}if(isOffset){if(elementsActive)return createStaticDecl((function(env,scope){return env.OFFSET=0,0}));if(vaoActive)return new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao+".currentVAO?"+env.shared.vao+".currentVAO.offset:0")}))}else if(vaoActive)return new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao+".currentVAO?"+env.shared.vao+".currentVAO.instances:-1")}));return null}var OFFSET=parseParam(S_OFFSET,!0);function parseVertCount(){if(S_COUNT in staticOptions){var count=0|staticOptions[S_COUNT];return staticDraw.count=count,check$1.command("number"==typeof count&&count>=0,"invalid vertex count",env.commandStr),createStaticDecl((function(){return count}))}if(S_COUNT in dynamicOptions){var dynCount=dynamicOptions[S_COUNT];return createDynamicDecl(dynCount,(function(env,scope){var result=env.invoke(scope,dynCount);return check$1.optional((function(){env.assert(scope,"typeof "+result+'==="number"&&'+result+">=0&&"+result+"===("+result+"|0)","invalid vertex count")})),result}))}if(elementsActive){if(isStatic(elements)){if(elements)return OFFSET?new Declaration(OFFSET.thisDep,OFFSET.contextDep,OFFSET.propDep,(function(env,scope){var result=scope.def(env.ELEMENTS,".vertCount-",env.OFFSET);return check$1.optional((function(){env.assert(scope,result+">=0","invalid vertex offset/element buffer too small")})),result})):createStaticDecl((function(env,scope){return scope.def(env.ELEMENTS,".vertCount")}));var result=createStaticDecl((function(){return-1}));return check$1.optional((function(){result.MISSING=!0})),result}var variable=new Declaration(elements.thisDep||OFFSET.thisDep,elements.contextDep||OFFSET.contextDep,elements.propDep||OFFSET.propDep,(function(env,scope){var elements=env.ELEMENTS;return env.OFFSET?scope.def(elements,"?",elements,".vertCount-",env.OFFSET,":-1"):scope.def(elements,"?",elements,".vertCount:-1")}));return check$1.optional((function(){variable.DYNAMIC=!0})),variable}if(vaoActive){var countVariable=new Declaration(vao.thisDep,vao.contextDep,vao.propDep,(function(env,scope){return scope.def(env.shared.vao,".currentVAO?",env.shared.vao,".currentVAO.count:-1")}));return countVariable}return null}var primitive=parsePrimitive(),count=parseVertCount(),instances=parseParam(S_INSTANCES,!1);return{elements:elements,primitive:primitive,count:count,instances:instances,offset:OFFSET,vao:vao,vaoActive:vaoActive,elementsActive:elementsActive,static:staticDraw}}function parseGLState(options,env){var staticOptions=options.static,dynamicOptions=options.dynamic,STATE={};return GL_STATE_NAMES.forEach((function(prop){var param=propName(prop);function parseParam(parseStatic,parseDynamic){if(prop in staticOptions){var value=parseStatic(staticOptions[prop]);STATE[param]=createStaticDecl((function(){return value}))}else if(prop in dynamicOptions){var dyn=dynamicOptions[prop];STATE[param]=createDynamicDecl(dyn,(function(env,scope){return parseDynamic(env,scope,env.invoke(scope,dyn))}))}}switch(prop){case S_CULL_ENABLE:case S_BLEND_ENABLE:case S_DITHER:case S_STENCIL_ENABLE:case S_DEPTH_ENABLE:case S_SCISSOR_ENABLE:case S_POLYGON_OFFSET_ENABLE:case S_SAMPLE_ALPHA:case S_SAMPLE_ENABLE:case S_DEPTH_MASK:return parseParam((function(value){return check$1.commandType(value,"boolean",prop,env.commandStr),value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,"typeof "+value+'==="boolean"',"invalid flag "+prop,env.commandStr)})),value}));case S_DEPTH_FUNC:return parseParam((function(value){return check$1.commandParameter(value,compareFuncs,"invalid "+prop,env.commandStr),compareFuncs[value]}),(function(env,scope,value){var COMPARE_FUNCS=env.constants.compareFuncs;return check$1.optional((function(){env.assert(scope,value+" in "+COMPARE_FUNCS,"invalid "+prop+", must be one of "+Object.keys(compareFuncs))})),scope.def(COMPARE_FUNCS,"[",value,"]")}));case S_DEPTH_RANGE:return parseParam((function(value){return check$1.command(isArrayLike(value)&&2===value.length&&"number"==typeof value[0]&&"number"==typeof value[1]&&value[0]<=value[1],"depth range is 2d array",env.commandStr),value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===2&&typeof "+value+'[0]==="number"&&typeof '+value+'[1]==="number"&&'+value+"[0]<="+value+"[1]","depth range must be a 2d array")})),[scope.def("+",value,"[0]"),scope.def("+",value,"[1]")]}));case S_BLEND_FUNC:return parseParam((function(value){check$1.commandType(value,"object","blend.func",env.commandStr);var srcRGB="srcRGB"in value?value.srcRGB:value.src,srcAlpha="srcAlpha"in value?value.srcAlpha:value.src,dstRGB="dstRGB"in value?value.dstRGB:value.dst,dstAlpha="dstAlpha"in value?value.dstAlpha:value.dst;return check$1.commandParameter(srcRGB,blendFuncs,param+".srcRGB",env.commandStr),check$1.commandParameter(srcAlpha,blendFuncs,param+".srcAlpha",env.commandStr),check$1.commandParameter(dstRGB,blendFuncs,param+".dstRGB",env.commandStr),check$1.commandParameter(dstAlpha,blendFuncs,param+".dstAlpha",env.commandStr),check$1.command(-1===invalidBlendCombinations.indexOf(srcRGB+", "+dstRGB),"unallowed blending combination (srcRGB, dstRGB) = ("+srcRGB+", "+dstRGB+")",env.commandStr),[blendFuncs[srcRGB],blendFuncs[dstRGB],blendFuncs[srcAlpha],blendFuncs[dstAlpha]]}),(function(env,scope,value){var BLEND_FUNCS=env.constants.blendFuncs;function read(prefix,suffix){var func=scope.def('"',prefix,suffix,'" in ',value,"?",value,".",prefix,suffix,":",value,".",prefix);return check$1.optional((function(){env.assert(scope,func+" in "+BLEND_FUNCS,"invalid "+prop+"."+prefix+suffix+", must be one of "+Object.keys(blendFuncs))})),func}check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid blend func, must be an object")}));var srcRGB=read("src","RGB"),dstRGB=read("dst","RGB");check$1.optional((function(){var INVALID_BLEND_COMBINATIONS=env.constants.invalidBlendCombinations;env.assert(scope,INVALID_BLEND_COMBINATIONS+".indexOf("+srcRGB+'+", "+'+dstRGB+") === -1 ","unallowed blending combination for (srcRGB, dstRGB)")}));var SRC_RGB=scope.def(BLEND_FUNCS,"[",srcRGB,"]"),SRC_ALPHA=scope.def(BLEND_FUNCS,"[",read("src","Alpha"),"]");return[SRC_RGB,scope.def(BLEND_FUNCS,"[",dstRGB,"]"),SRC_ALPHA,scope.def(BLEND_FUNCS,"[",read("dst","Alpha"),"]")]}));case S_BLEND_EQUATION:return parseParam((function(value){return"string"==typeof value?(check$1.commandParameter(value,blendEquations,"invalid "+prop,env.commandStr),[blendEquations[value],blendEquations[value]]):"object"==typeof value?(check$1.commandParameter(value.rgb,blendEquations,prop+".rgb",env.commandStr),check$1.commandParameter(value.alpha,blendEquations,prop+".alpha",env.commandStr),[blendEquations[value.rgb],blendEquations[value.alpha]]):void check$1.commandRaise("invalid blend.equation",env.commandStr)}),(function(env,scope,value){var BLEND_EQUATIONS=env.constants.blendEquations,RGB=scope.def(),ALPHA=scope.def(),ifte=env.cond("typeof ",value,'==="string"');return check$1.optional((function(){function checkProp(block,name,value){env.assert(block,value+" in "+BLEND_EQUATIONS,"invalid "+name+", must be one of "+Object.keys(blendEquations))}checkProp(ifte.then,prop,value),env.assert(ifte.else,value+"&&typeof "+value+'==="object"',"invalid "+prop),checkProp(ifte.else,prop+".rgb",value+".rgb"),checkProp(ifte.else,prop+".alpha",value+".alpha")})),ifte.then(RGB,"=",ALPHA,"=",BLEND_EQUATIONS,"[",value,"];"),ifte.else(RGB,"=",BLEND_EQUATIONS,"[",value,".rgb];",ALPHA,"=",BLEND_EQUATIONS,"[",value,".alpha];"),scope(ifte),[RGB,ALPHA]}));case S_BLEND_COLOR:return parseParam((function(value){return check$1.command(isArrayLike(value)&&4===value.length,"blend.color must be a 4d array",env.commandStr),loop(4,(function(i){return+value[i]}))}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===4","blend.color must be a 4d array")})),loop(4,(function(i){return scope.def("+",value,"[",i,"]")}))}));case S_STENCIL_MASK:return parseParam((function(value){return check$1.commandType(value,"number",param,env.commandStr),0|value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,"typeof "+value+'==="number"',"invalid stencil.mask")})),scope.def(value,"|0")}));case S_STENCIL_FUNC:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var cmp=value.cmp||"keep",ref=value.ref||0,mask="mask"in value?value.mask:-1;return check$1.commandParameter(cmp,compareFuncs,prop+".cmp",env.commandStr),check$1.commandType(ref,"number",prop+".ref",env.commandStr),check$1.commandType(mask,"number",prop+".mask",env.commandStr),[compareFuncs[cmp],ref,mask]}),(function(env,scope,value){var COMPARE_FUNCS=env.constants.compareFuncs;return check$1.optional((function(){function assert(){env.assert(scope,Array.prototype.join.call(arguments,""),"invalid stencil.func")}assert(value+"&&typeof ",value,'==="object"'),assert('!("cmp" in ',value,")||(",value,".cmp in ",COMPARE_FUNCS,")")})),[scope.def('"cmp" in ',value,"?",COMPARE_FUNCS,"[",value,".cmp]",":",GL_KEEP),scope.def(value,".ref|0"),scope.def('"mask" in ',value,"?",value,".mask|0:-1")]}));case S_STENCIL_OPFRONT:case S_STENCIL_OPBACK:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var fail=value.fail||"keep",zfail=value.zfail||"keep",zpass=value.zpass||"keep";return check$1.commandParameter(fail,stencilOps,prop+".fail",env.commandStr),check$1.commandParameter(zfail,stencilOps,prop+".zfail",env.commandStr),check$1.commandParameter(zpass,stencilOps,prop+".zpass",env.commandStr),[prop===S_STENCIL_OPBACK?GL_BACK:GL_FRONT,stencilOps[fail],stencilOps[zfail],stencilOps[zpass]]}),(function(env,scope,value){var STENCIL_OPS=env.constants.stencilOps;function read(name){return check$1.optional((function(){env.assert(scope,'!("'+name+'" in '+value+")||("+value+"."+name+" in "+STENCIL_OPS+")","invalid "+prop+"."+name+", must be one of "+Object.keys(stencilOps))})),scope.def('"',name,'" in ',value,"?",STENCIL_OPS,"[",value,".",name,"]:",GL_KEEP)}return check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid "+prop)})),[prop===S_STENCIL_OPBACK?GL_BACK:GL_FRONT,read("fail"),read("zfail"),read("zpass")]}));case S_POLYGON_OFFSET_OFFSET:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var factor=0|value.factor,units=0|value.units;return check$1.commandType(factor,"number",param+".factor",env.commandStr),check$1.commandType(units,"number",param+".units",env.commandStr),[factor,units]}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid "+prop)})),[scope.def(value,".factor|0"),scope.def(value,".units|0")]}));case S_CULL_FACE:return parseParam((function(value){var face=0;return"front"===value?face=GL_FRONT:"back"===value&&(face=GL_BACK),check$1.command(!!face,param,env.commandStr),face}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+'==="front"||'+value+'==="back"',"invalid cull.face")})),scope.def(value,'==="front"?',GL_FRONT,":",GL_BACK)}));case S_LINE_WIDTH:return parseParam((function(value){return check$1.command("number"==typeof value&&value>=limits.lineWidthDims[0]&&value<=limits.lineWidthDims[1],"invalid line width, must be a positive number between "+limits.lineWidthDims[0]+" and "+limits.lineWidthDims[1],env.commandStr),value}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,"typeof "+value+'==="number"&&'+value+">="+limits.lineWidthDims[0]+"&&"+value+"<="+limits.lineWidthDims[1],"invalid line width")})),value}));case S_FRONT_FACE:return parseParam((function(value){return check$1.commandParameter(value,orientationType,param,env.commandStr),orientationType[value]}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+'==="cw"||'+value+'==="ccw"',"invalid frontFace, must be one of cw,ccw")})),scope.def(value+'==="cw"?'+GL_CW+":"+GL_CCW)}));case S_COLOR_MASK:return parseParam((function(value){return check$1.command(isArrayLike(value)&&4===value.length,"color.mask must be length 4 array",env.commandStr),value.map((function(v){return!!v}))}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===4","invalid color.mask")})),loop(4,(function(i){return"!!"+value+"["+i+"]"}))}));case S_SAMPLE_COVERAGE:return parseParam((function(value){check$1.command("object"==typeof value&&value,param,env.commandStr);var sampleValue="value"in value?value.value:1,sampleInvert=!!value.invert;return check$1.command("number"==typeof sampleValue&&sampleValue>=0&&sampleValue<=1,"sample.coverage.value must be a number between 0 and 1",env.commandStr),[sampleValue,sampleInvert]}),(function(env,scope,value){return check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid sample.coverage")})),[scope.def('"value" in ',value,"?+",value,".value:1"),scope.def("!!",value,".invert")]}))}})),STATE}function parseUniforms(uniforms,env){var staticUniforms=uniforms.static,dynamicUniforms=uniforms.dynamic,UNIFORMS={};return Object.keys(staticUniforms).forEach((function(name){var result,value=staticUniforms[name];if("number"==typeof value||"boolean"==typeof value)result=createStaticDecl((function(){return value}));else if("function"==typeof value){var reglType=value._reglType;"texture2d"===reglType||"textureCube"===reglType?result=createStaticDecl((function(env){return env.link(value)})):"framebuffer"===reglType||"framebufferCube"===reglType?(check$1.command(value.color.length>0,'missing color attachment for framebuffer sent to uniform "'+name+'"',env.commandStr),result=createStaticDecl((function(env){return env.link(value.color[0])}))):check$1.commandRaise('invalid data for uniform "'+name+'"',env.commandStr)}else isArrayLike(value)?result=createStaticDecl((function(env){return env.global.def("[",loop(value.length,(function(i){return check$1.command("number"==typeof value[i]||"boolean"==typeof value[i],"invalid uniform "+name,env.commandStr),value[i]})),"]")})):check$1.commandRaise('invalid or missing data for uniform "'+name+'"',env.commandStr);result.value=value,UNIFORMS[name]=result})),Object.keys(dynamicUniforms).forEach((function(key){var dyn=dynamicUniforms[key];UNIFORMS[key]=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))})),UNIFORMS}function parseAttributes(attributes,env){var staticAttributes=attributes.static,dynamicAttributes=attributes.dynamic,attributeDefs={};return Object.keys(staticAttributes).forEach((function(attribute){var value=staticAttributes[attribute],id=stringStore.id(attribute),record=new AttributeRecord;if(isBufferArgs(value))record.state=ATTRIB_STATE_POINTER,record.buffer=bufferState.getBuffer(bufferState.create(value,GL_ARRAY_BUFFER$2,!1,!0)),record.type=0;else{var buffer=bufferState.getBuffer(value);if(buffer)record.state=ATTRIB_STATE_POINTER,record.buffer=buffer,record.type=0;else if(check$1.command("object"==typeof value&&value,"invalid data for attribute "+attribute,env.commandStr),"constant"in value){var constant=value.constant;record.buffer="null",record.state=ATTRIB_STATE_CONSTANT,"number"==typeof constant?record.x=constant:(check$1.command(isArrayLike(constant)&&constant.length>0&&constant.length<=4,"invalid constant for attribute "+attribute,env.commandStr),CUTE_COMPONENTS.forEach((function(c,i){i<constant.length&&(record[c]=constant[i])})))}else{buffer=isBufferArgs(value.buffer)?bufferState.getBuffer(bufferState.create(value.buffer,GL_ARRAY_BUFFER$2,!1,!0)):bufferState.getBuffer(value.buffer),check$1.command(!!buffer,'missing buffer for attribute "'+attribute+'"',env.commandStr);var offset=0|value.offset;check$1.command(offset>=0,'invalid offset for attribute "'+attribute+'"',env.commandStr);var stride=0|value.stride;check$1.command(stride>=0&&stride<256,'invalid stride for attribute "'+attribute+'", must be integer betweeen [0, 255]',env.commandStr);var size=0|value.size;check$1.command(!("size"in value)||size>0&&size<=4,'invalid size for attribute "'+attribute+'", must be 1,2,3,4',env.commandStr);var normalized=!!value.normalized,type=0;"type"in value&&(check$1.commandParameter(value.type,glTypes,"invalid type for attribute "+attribute,env.commandStr),type=glTypes[value.type]);var divisor=0|value.divisor;check$1.optional((function(){"divisor"in value&&(check$1.command(0===divisor||extInstancing,'cannot specify divisor for attribute "'+attribute+'", instancing not supported',env.commandStr),check$1.command(divisor>=0,'invalid divisor for attribute "'+attribute+'"',env.commandStr));var command=env.commandStr,VALID_KEYS=["buffer","offset","divisor","normalized","type","size","stride"];Object.keys(value).forEach((function(prop){check$1.command(VALID_KEYS.indexOf(prop)>=0,'unknown parameter "'+prop+'" for attribute pointer "'+attribute+'" (valid parameters are '+VALID_KEYS+")",command)}))})),record.buffer=buffer,record.state=ATTRIB_STATE_POINTER,record.size=size,record.normalized=normalized,record.type=type||buffer.dtype,record.offset=offset,record.stride=stride,record.divisor=divisor}}attributeDefs[attribute]=createStaticDecl((function(env,scope){var cache=env.attribCache;if(id in cache)return cache[id];var result={isStream:!1};return Object.keys(record).forEach((function(key){result[key]=record[key]})),record.buffer&&(result.buffer=env.link(record.buffer),result.type=result.type||result.buffer+".dtype"),cache[id]=result,result}))})),Object.keys(dynamicAttributes).forEach((function(attribute){var dyn=dynamicAttributes[attribute];function appendAttributeCode(env,block){var VALUE=env.invoke(block,dyn),shared=env.shared,constants=env.constants,IS_BUFFER_ARGS=shared.isBufferArgs,BUFFER_STATE=shared.buffer;check$1.optional((function(){env.assert(block,VALUE+"&&(typeof "+VALUE+'==="object"||typeof '+VALUE+'==="function")&&('+IS_BUFFER_ARGS+"("+VALUE+")||"+BUFFER_STATE+".getBuffer("+VALUE+")||"+BUFFER_STATE+".getBuffer("+VALUE+".buffer)||"+IS_BUFFER_ARGS+"("+VALUE+'.buffer)||("constant" in '+VALUE+"&&(typeof "+VALUE+'.constant==="number"||'+shared.isArrayLike+"("+VALUE+".constant))))",'invalid dynamic attribute "'+attribute+'"')}));var result={isStream:block.def(!1)},defaultRecord=new AttributeRecord;defaultRecord.state=ATTRIB_STATE_POINTER,Object.keys(defaultRecord).forEach((function(key){result[key]=block.def(""+defaultRecord[key])}));var BUFFER=result.buffer,TYPE=result.type;function emitReadRecord(name){block(result[name],"=",VALUE,".",name,"|0;")}return block("if(",IS_BUFFER_ARGS,"(",VALUE,")){",result.isStream,"=true;",BUFFER,"=",BUFFER_STATE,".createStream(",GL_ARRAY_BUFFER$2,",",VALUE,");",TYPE,"=",BUFFER,".dtype;","}else{",BUFFER,"=",BUFFER_STATE,".getBuffer(",VALUE,");","if(",BUFFER,"){",TYPE,"=",BUFFER,".dtype;",'}else if("constant" in ',VALUE,"){",result.state,"=",ATTRIB_STATE_CONSTANT,";","if(typeof "+VALUE+'.constant === "number"){',result[CUTE_COMPONENTS[0]],"=",VALUE,".constant;",CUTE_COMPONENTS.slice(1).map((function(n){return result[n]})).join("="),"=0;","}else{",CUTE_COMPONENTS.map((function(name,i){return result[name]+"="+VALUE+".constant.length>"+i+"?"+VALUE+".constant["+i+"]:0;"})).join(""),"}}else{","if(",IS_BUFFER_ARGS,"(",VALUE,".buffer)){",BUFFER,"=",BUFFER_STATE,".createStream(",GL_ARRAY_BUFFER$2,",",VALUE,".buffer);","}else{",BUFFER,"=",BUFFER_STATE,".getBuffer(",VALUE,".buffer);","}",TYPE,'="type" in ',VALUE,"?",constants.glTypes,"[",VALUE,".type]:",BUFFER,".dtype;",result.normalized,"=!!",VALUE,".normalized;"),emitReadRecord("size"),emitReadRecord("offset"),emitReadRecord("stride"),emitReadRecord("divisor"),block("}}"),block.exit("if(",result.isStream,"){",BUFFER_STATE,".destroyStream(",BUFFER,");","}"),result}attributeDefs[attribute]=createDynamicDecl(dyn,appendAttributeCode)})),attributeDefs}function parseContext(context){var staticContext=context.static,dynamicContext=context.dynamic,result={};return Object.keys(staticContext).forEach((function(name){var value=staticContext[name];result[name]=createStaticDecl((function(env,scope){return"number"==typeof value||"boolean"==typeof value?""+value:env.link(value)}))})),Object.keys(dynamicContext).forEach((function(name){var dyn=dynamicContext[name];result[name]=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))})),result}function parseArguments(options,attributes,uniforms,context,env){var staticOptions=options.static,dynamicOptions=options.dynamic;check$1.optional((function(){var KEY_NAMES=[S_FRAMEBUFFER,S_VERT,S_FRAG,S_ELEMENTS,S_PRIMITIVE,S_OFFSET,S_COUNT,S_INSTANCES,S_PROFILE,S_VAO].concat(GL_STATE_NAMES);function checkKeys(dict){Object.keys(dict).forEach((function(key){check$1.command(KEY_NAMES.indexOf(key)>=0,'unknown parameter "'+key+'"',env.commandStr)}))}checkKeys(staticOptions),checkKeys(dynamicOptions)}));var attribLocations=parseAttribLocations(options,attributes),framebuffer=parseFramebuffer(options),viewportAndScissor=parseViewportScissor(options,framebuffer,env),draw=parseDraw(options,env),state=parseGLState(options,env),shader=parseProgram(options,env,attribLocations);function copyBox(name){var defn=viewportAndScissor[name];defn&&(state[name]=defn)}copyBox(S_VIEWPORT),copyBox(propName(S_SCISSOR_BOX));var dirty=Object.keys(state).length>0,result={framebuffer:framebuffer,draw:draw,shader:shader,state:state,dirty:dirty,scopeVAO:null,drawVAO:null,useVAO:!1,attributes:{}};if(result.profile=parseProfile(options),result.uniforms=parseUniforms(uniforms,env),result.drawVAO=result.scopeVAO=draw.vao,!result.drawVAO&&shader.program&&!attribLocations&&extensions.angle_instanced_arrays&&draw.static.elements){var useVAO=!0,staticBindings=shader.program.attributes.map((function(attr){var binding=attributes.static[attr];return useVAO=useVAO&&!!binding,binding}));if(useVAO&&staticBindings.length>0){var vao=attributeState.getVAO(attributeState.createVAO({attributes:staticBindings,elements:draw.static.elements}));result.drawVAO=new Declaration(null,null,null,(function(env,scope){return env.link(vao)})),result.useVAO=!0}}return attribLocations?result.useVAO=!0:result.attributes=parseAttributes(attributes,env),result.context=parseContext(context),result}function emitContext(env,scope,context){var CONTEXT=env.shared.context,contextEnter=env.scope();Object.keys(context).forEach((function(name){scope.save(CONTEXT,"."+name);var value=context[name].append(env,scope);Array.isArray(value)?contextEnter(CONTEXT,".",name,"=[",value.join(),"];"):contextEnter(CONTEXT,".",name,"=",value,";")})),scope(contextEnter)}function emitPollFramebuffer(env,scope,framebuffer,skipCheck){var EXT_DRAW_BUFFERS,shared=env.shared,GL=shared.gl,FRAMEBUFFER_STATE=shared.framebuffer;extDrawBuffers&&(EXT_DRAW_BUFFERS=scope.def(shared.extensions,".webgl_draw_buffers"));var NEXT,constants=env.constants,DRAW_BUFFERS=constants.drawBuffer,BACK_BUFFER=constants.backBuffer;NEXT=framebuffer?framebuffer.append(env,scope):scope.def(FRAMEBUFFER_STATE,".next"),skipCheck||scope("if(",NEXT,"!==",FRAMEBUFFER_STATE,".cur){"),scope("if(",NEXT,"){",GL,".bindFramebuffer(",GL_FRAMEBUFFER$2,",",NEXT,".framebuffer);"),extDrawBuffers&&scope(EXT_DRAW_BUFFERS,".drawBuffersWEBGL(",DRAW_BUFFERS,"[",NEXT,".colorAttachments.length]);"),scope("}else{",GL,".bindFramebuffer(",GL_FRAMEBUFFER$2,",null);"),extDrawBuffers&&scope(EXT_DRAW_BUFFERS,".drawBuffersWEBGL(",BACK_BUFFER,");"),scope("}",FRAMEBUFFER_STATE,".cur=",NEXT,";"),skipCheck||scope("}")}function emitPollState(env,scope,args){var shared=env.shared,GL=shared.gl,CURRENT_VARS=env.current,NEXT_VARS=env.next,CURRENT_STATE=shared.current,NEXT_STATE=shared.next,block=env.cond(CURRENT_STATE,".dirty");GL_STATE_NAMES.forEach((function(prop){var NEXT,CURRENT,param=propName(prop);if(!(param in args.state))if(param in NEXT_VARS){NEXT=NEXT_VARS[param],CURRENT=CURRENT_VARS[param];var parts=loop(currentState[param].length,(function(i){return block.def(NEXT,"[",i,"]")}));block(env.cond(parts.map((function(p,i){return p+"!=="+CURRENT+"["+i+"]"})).join("||")).then(GL,".",GL_VARIABLES[param],"(",parts,");",parts.map((function(p,i){return CURRENT+"["+i+"]="+p})).join(";"),";"))}else{NEXT=block.def(NEXT_STATE,".",param);var ifte=env.cond(NEXT,"!==",CURRENT_STATE,".",param);block(ifte),param in GL_FLAGS?ifte(env.cond(NEXT).then(GL,".enable(",GL_FLAGS[param],");").else(GL,".disable(",GL_FLAGS[param],");"),CURRENT_STATE,".",param,"=",NEXT,";"):ifte(GL,".",GL_VARIABLES[param],"(",NEXT,");",CURRENT_STATE,".",param,"=",NEXT,";")}})),0===Object.keys(args.state).length&&block(CURRENT_STATE,".dirty=false;"),scope(block)}function emitSetOptions(env,scope,options,filter){var shared=env.shared,CURRENT_VARS=env.current,CURRENT_STATE=shared.current,GL=shared.gl;sortState(Object.keys(options)).forEach((function(param){var defn=options[param];if(!filter||filter(defn)){var variable=defn.append(env,scope);if(GL_FLAGS[param]){var flag=GL_FLAGS[param];isStatic(defn)?scope(GL,variable?".enable(":".disable(",flag,");"):scope(env.cond(variable).then(GL,".enable(",flag,");").else(GL,".disable(",flag,");")),scope(CURRENT_STATE,".",param,"=",variable,";")}else if(isArrayLike(variable)){var CURRENT=CURRENT_VARS[param];scope(GL,".",GL_VARIABLES[param],"(",variable,");",variable.map((function(v,i){return CURRENT+"["+i+"]="+v})).join(";"),";")}else scope(GL,".",GL_VARIABLES[param],"(",variable,");",CURRENT_STATE,".",param,"=",variable,";")}}))}function injectExtensions(env,scope){extInstancing&&(env.instancing=scope.def(env.shared.extensions,".angle_instanced_arrays"))}function emitProfile(env,scope,args,useScope,incrementCounter){var CPU_START,QUERY_COUNTER,USE_PROFILE,shared=env.shared,STATS=env.stats,CURRENT_STATE=shared.current,TIMER=shared.timer,profileArg=args.profile;function perfCounter(){return"undefined"==typeof performance?"Date.now()":"performance.now()"}function emitProfileStart(block){block(CPU_START=scope.def(),"=",perfCounter(),";"),"string"==typeof incrementCounter?block(STATS,".count+=",incrementCounter,";"):block(STATS,".count++;"),timer&&(useScope?block(QUERY_COUNTER=scope.def(),"=",TIMER,".getNumPendingQueries();"):block(TIMER,".beginQuery(",STATS,");"))}function emitProfileEnd(block){block(STATS,".cpuTime+=",perfCounter(),"-",CPU_START,";"),timer&&(useScope?block(TIMER,".pushScopeStats(",QUERY_COUNTER,",",TIMER,".getNumPendingQueries(),",STATS,");"):block(TIMER,".endQuery();"))}function scopeProfile(value){var prev=scope.def(CURRENT_STATE,".profile");scope(CURRENT_STATE,".profile=",value,";"),scope.exit(CURRENT_STATE,".profile=",prev,";")}if(profileArg){if(isStatic(profileArg))return void(profileArg.enable?(emitProfileStart(scope),emitProfileEnd(scope.exit),scopeProfile("true")):scopeProfile("false"));scopeProfile(USE_PROFILE=profileArg.append(env,scope))}else USE_PROFILE=scope.def(CURRENT_STATE,".profile");var start=env.block();emitProfileStart(start),scope("if(",USE_PROFILE,"){",start,"}");var end=env.block();emitProfileEnd(end),scope.exit("if(",USE_PROFILE,"){",end,"}")}function emitAttributes(env,scope,args,attributes,filter){var shared=env.shared;function typeLength(x){switch(x){case GL_FLOAT_VEC2:case GL_INT_VEC2:case GL_BOOL_VEC2:return 2;case GL_FLOAT_VEC3:case GL_INT_VEC3:case GL_BOOL_VEC3:return 3;case GL_FLOAT_VEC4:case GL_INT_VEC4:case GL_BOOL_VEC4:return 4;default:return 1}}function emitBindAttribute(ATTRIBUTE,size,record){var GL=shared.gl,LOCATION=scope.def(ATTRIBUTE,".location"),BINDING=scope.def(shared.attributes,"[",LOCATION,"]"),STATE=record.state,BUFFER=record.buffer,CONST_COMPONENTS=[record.x,record.y,record.z,record.w],COMMON_KEYS=["buffer","normalized","offset","stride"];function emitBuffer(){scope("if(!",BINDING,".buffer){",GL,".enableVertexAttribArray(",LOCATION,");}");var SIZE,TYPE=record.type;if(SIZE=record.size?scope.def(record.size,"||",size):size,scope("if(",BINDING,".type!==",TYPE,"||",BINDING,".size!==",SIZE,"||",COMMON_KEYS.map((function(key){return BINDING+"."+key+"!=="+record[key]})).join("||"),"){",GL,".bindBuffer(",GL_ARRAY_BUFFER$2,",",BUFFER,".buffer);",GL,".vertexAttribPointer(",[LOCATION,SIZE,TYPE,record.normalized,record.stride,record.offset],");",BINDING,".type=",TYPE,";",BINDING,".size=",SIZE,";",COMMON_KEYS.map((function(key){return BINDING+"."+key+"="+record[key]+";"})).join(""),"}"),extInstancing){var DIVISOR=record.divisor;scope("if(",BINDING,".divisor!==",DIVISOR,"){",env.instancing,".vertexAttribDivisorANGLE(",[LOCATION,DIVISOR],");",BINDING,".divisor=",DIVISOR,";}")}}function emitConstant(){scope("if(",BINDING,".buffer){",GL,".disableVertexAttribArray(",LOCATION,");",BINDING,".buffer=null;","}if(",CUTE_COMPONENTS.map((function(c,i){return BINDING+"."+c+"!=="+CONST_COMPONENTS[i]})).join("||"),"){",GL,".vertexAttrib4f(",LOCATION,",",CONST_COMPONENTS,");",CUTE_COMPONENTS.map((function(c,i){return BINDING+"."+c+"="+CONST_COMPONENTS[i]+";"})).join(""),"}")}STATE===ATTRIB_STATE_POINTER?emitBuffer():STATE===ATTRIB_STATE_CONSTANT?emitConstant():(scope("if(",STATE,"===",ATTRIB_STATE_POINTER,"){"),emitBuffer(),scope("}else{"),emitConstant(),scope("}"))}attributes.forEach((function(attribute){var record,name=attribute.name,arg=args.attributes[name];if(arg){if(!filter(arg))return;record=arg.append(env,scope)}else{if(!filter(SCOPE_DECL))return;var scopeAttrib=env.scopeAttrib(name);check$1.optional((function(){env.assert(scope,scopeAttrib+".state","missing attribute "+name)})),record={},Object.keys(new AttributeRecord).forEach((function(key){record[key]=scope.def(scopeAttrib,".",key)}))}emitBindAttribute(env.link(attribute),typeLength(attribute.info.type),record)}))}function emitUniforms(env,scope,args,uniforms,filter,isBatchInnerLoop){for(var infix,shared=env.shared,GL=shared.gl,definedArrUniforms={},i=0;i<uniforms.length;++i){var uniform=uniforms[i],name=uniform.name,type=uniform.info.type,size=uniform.info.size,arg=args.uniforms[name];if(size>1){if(!arg)continue;var arrUniformName=name.replace("[0]","");if(definedArrUniforms[arrUniformName])continue;definedArrUniforms[arrUniformName]=1}var VALUE,LOCATION=env.link(uniform)+".location";if(arg){if(!filter(arg))continue;if(isStatic(arg)){var value=arg.value;if(check$1.command(null!=value,'missing uniform "'+name+'"',env.commandStr),type===GL_SAMPLER_2D||type===GL_SAMPLER_CUBE){check$1.command("function"==typeof value&&(type===GL_SAMPLER_2D&&("texture2d"===value._reglType||"framebuffer"===value._reglType)||type===GL_SAMPLER_CUBE&&("textureCube"===value._reglType||"framebufferCube"===value._reglType)),"invalid texture for uniform "+name,env.commandStr);var TEX_VALUE=env.link(value._texture||value.color[0]._texture);scope(GL,".uniform1i(",LOCATION,",",TEX_VALUE+".bind());"),scope.exit(TEX_VALUE,".unbind();")}else if(type===GL_FLOAT_MAT2||type===GL_FLOAT_MAT3||type===GL_FLOAT_MAT4){check$1.optional((function(){check$1.command(isArrayLike(value),"invalid matrix for uniform "+name,env.commandStr),check$1.command(type===GL_FLOAT_MAT2&&4===value.length||type===GL_FLOAT_MAT3&&9===value.length||type===GL_FLOAT_MAT4&&16===value.length,"invalid length for matrix uniform "+name,env.commandStr)}));var MAT_VALUE=env.global.def("new Float32Array(["+Array.prototype.slice.call(value)+"])"),dim=2;type===GL_FLOAT_MAT3?dim=3:type===GL_FLOAT_MAT4&&(dim=4),scope(GL,".uniformMatrix",dim,"fv(",LOCATION,",false,",MAT_VALUE,");")}else{switch(type){case GL_FLOAT$8:1===size?check$1.commandType(value,"number","uniform "+name,env.commandStr):check$1.command(isArrayLike(value)&&value.length===size,"uniform "+name,env.commandStr),infix="1f";break;case GL_FLOAT_VEC2:check$1.command(isArrayLike(value)&&value.length&&value.length%2==0&&value.length<=2*size,"uniform "+name,env.commandStr),infix="2f";break;case GL_FLOAT_VEC3:check$1.command(isArrayLike(value)&&value.length&&value.length%3==0&&value.length<=3*size,"uniform "+name,env.commandStr),infix="3f";break;case GL_FLOAT_VEC4:check$1.command(isArrayLike(value)&&value.length&&value.length%4==0&&value.length<=4*size,"uniform "+name,env.commandStr),infix="4f";break;case GL_BOOL:1===size?check$1.commandType(value,"boolean","uniform "+name,env.commandStr):check$1.command(isArrayLike(value)&&value.length===size,"uniform "+name,env.commandStr),infix="1i";break;case GL_INT$3:1===size?check$1.commandType(value,"number","uniform "+name,env.commandStr):check$1.command(isArrayLike(value)&&value.length===size,"uniform "+name,env.commandStr),infix="1i";break;case GL_BOOL_VEC2:case GL_INT_VEC2:check$1.command(isArrayLike(value)&&value.length&&value.length%2==0&&value.length<=2*size,"uniform "+name,env.commandStr),infix="2i";break;case GL_BOOL_VEC3:case GL_INT_VEC3:check$1.command(isArrayLike(value)&&value.length&&value.length%3==0&&value.length<=3*size,"uniform "+name,env.commandStr),infix="3i";break;case GL_BOOL_VEC4:case GL_INT_VEC4:check$1.command(isArrayLike(value)&&value.length&&value.length%4==0&&value.length<=4*size,"uniform "+name,env.commandStr),infix="4i"}size>1?(infix+="v",value=env.global.def("["+Array.prototype.slice.call(value)+"]")):value=isArrayLike(value)?Array.prototype.slice.call(value):value,scope(GL,".uniform",infix,"(",LOCATION,",",value,");")}continue}VALUE=arg.append(env,scope)}else{if(!filter(SCOPE_DECL))continue;VALUE=scope.def(shared.uniforms,"[",stringStore.id(name),"]")}type===GL_SAMPLER_2D?(check$1(!Array.isArray(VALUE),"must specify a scalar prop for textures"),scope("if(",VALUE,"&&",VALUE,'._reglType==="framebuffer"){',VALUE,"=",VALUE,".color[0];","}")):type===GL_SAMPLER_CUBE&&(check$1(!Array.isArray(VALUE),"must specify a scalar prop for cube maps"),scope("if(",VALUE,"&&",VALUE,'._reglType==="framebufferCube"){',VALUE,"=",VALUE,".color[0];","}")),check$1.optional((function(){function emitCheck(pred,message){env.assert(scope,pred,'bad data or missing for uniform "'+name+'". '+message)}function checkType(type,size){1===size&&check$1(!Array.isArray(VALUE),"must not specify an array type for uniform"),emitCheck("Array.isArray("+VALUE+") && typeof "+VALUE+'[0]===" '+type+'" || typeof '+VALUE+'==="'+type+'"',"invalid type, expected "+type)}function checkVector(n,type,size){Array.isArray(VALUE)?check$1(VALUE.length&&VALUE.length%n==0&&VALUE.length<=n*size,"must have length of "+(1===size?"":"n * ")+n):emitCheck(shared.isArrayLike+"("+VALUE+")&&"+VALUE+".length && "+VALUE+".length % "+n+" === 0 && "+VALUE+".length<="+n*size,"invalid vector, should have length of "+(1===size?"":"n * ")+n,env.commandStr)}function checkTexture(target){check$1(!Array.isArray(VALUE),"must not specify a value type"),emitCheck("typeof "+VALUE+'==="function"&&'+VALUE+'._reglType==="texture'+(target===GL_TEXTURE_2D$3?"2d":"Cube")+'"',"invalid texture type",env.commandStr)}switch(type){case GL_INT$3:checkType("number",size);break;case GL_INT_VEC2:checkVector(2,"number",size);break;case GL_INT_VEC3:checkVector(3,"number",size);break;case GL_INT_VEC4:checkVector(4,"number",size);break;case GL_FLOAT$8:checkType("number",size);break;case GL_FLOAT_VEC2:checkVector(2,"number",size);break;case GL_FLOAT_VEC3:checkVector(3,"number",size);break;case GL_FLOAT_VEC4:checkVector(4,"number",size);break;case GL_BOOL:checkType("boolean",size);break;case GL_BOOL_VEC2:checkVector(2,"boolean",size);break;case GL_BOOL_VEC3:checkVector(3,"boolean",size);break;case GL_BOOL_VEC4:checkVector(4,"boolean",size);break;case GL_FLOAT_MAT2:checkVector(4,"number",size);break;case GL_FLOAT_MAT3:checkVector(9,"number",size);break;case GL_FLOAT_MAT4:checkVector(16,"number",size);break;case GL_SAMPLER_2D:checkTexture(GL_TEXTURE_2D$3);break;case GL_SAMPLER_CUBE:checkTexture(GL_TEXTURE_CUBE_MAP$2)}}));var unroll=1;switch(type){case GL_SAMPLER_2D:case GL_SAMPLER_CUBE:var TEX=scope.def(VALUE,"._texture");scope(GL,".uniform1i(",LOCATION,",",TEX,".bind());"),scope.exit(TEX,".unbind();");continue;case GL_INT$3:case GL_BOOL:infix="1i";break;case GL_INT_VEC2:case GL_BOOL_VEC2:infix="2i",unroll=2;break;case GL_INT_VEC3:case GL_BOOL_VEC3:infix="3i",unroll=3;break;case GL_INT_VEC4:case GL_BOOL_VEC4:infix="4i",unroll=4;break;case GL_FLOAT$8:infix="1f";break;case GL_FLOAT_VEC2:infix="2f",unroll=2;break;case GL_FLOAT_VEC3:infix="3f",unroll=3;break;case GL_FLOAT_VEC4:infix="4f",unroll=4;break;case GL_FLOAT_MAT2:infix="Matrix2fv";break;case GL_FLOAT_MAT3:infix="Matrix3fv";break;case GL_FLOAT_MAT4:infix="Matrix4fv"}if(-1===infix.indexOf("Matrix")&&size>1&&(infix+="v",unroll=1),"M"===infix.charAt(0)){scope(GL,".uniform",infix,"(",LOCATION,",");var matSize=Math.pow(type-GL_FLOAT_MAT2+2,2),STORAGE=env.global.def("new Float32Array(",matSize,")");Array.isArray(VALUE)?scope("false,(",loop(matSize,(function(i){return STORAGE+"["+i+"]="+VALUE[i]})),",",STORAGE,")"):scope("false,(Array.isArray(",VALUE,")||",VALUE," instanceof Float32Array)?",VALUE,":(",loop(matSize,(function(i){return STORAGE+"["+i+"]="+VALUE+"["+i+"]"})),",",STORAGE,")"),scope(");")}else if(unroll>1){for(var prev=[],cur=[],j=0;j<unroll;++j)Array.isArray(VALUE)?cur.push(VALUE[j]):cur.push(scope.def(VALUE+"["+j+"]")),isBatchInnerLoop&&prev.push(scope.def());isBatchInnerLoop&&scope("if(!",env.batchId,"||",prev.map((function(p,i){return p+"!=="+cur[i]})).join("||"),"){",prev.map((function(p,i){return p+"="+cur[i]+";"})).join("")),scope(GL,".uniform",infix,"(",LOCATION,",",cur.join(","),");"),isBatchInnerLoop&&scope("}")}else{if(check$1(!Array.isArray(VALUE),"uniform value must not be an array"),isBatchInnerLoop){var prevS=scope.def();scope("if(!",env.batchId,"||",prevS,"!==",VALUE,"){",prevS,"=",VALUE,";")}scope(GL,".uniform",infix,"(",LOCATION,",",VALUE,");"),isBatchInnerLoop&&scope("}")}}}function emitDraw(env,outer,inner,args){var shared=env.shared,GL=shared.gl,DRAW_STATE=shared.draw,drawOptions=args.draw;function emitElements(){var ELEMENTS,defn=drawOptions.elements,scope=outer;return defn?((defn.contextDep&&args.contextDynamic||defn.propDep)&&(scope=inner),ELEMENTS=defn.append(env,scope),drawOptions.elementsActive&&scope("if("+ELEMENTS+")"+GL+".bindBuffer("+GL_ELEMENT_ARRAY_BUFFER$2+","+ELEMENTS+".buffer.buffer);")):(ELEMENTS=scope.def(),scope(ELEMENTS,"=",DRAW_STATE,".",S_ELEMENTS,";","if(",ELEMENTS,"){",GL,".bindBuffer(",GL_ELEMENT_ARRAY_BUFFER$2,",",ELEMENTS,".buffer.buffer);}","else if(",shared.vao,".currentVAO){",ELEMENTS,"=",env.shared.elements+".getElements("+shared.vao,".currentVAO.elements);",extVertexArrays?"":"if("+ELEMENTS+")"+GL+".bindBuffer("+GL_ELEMENT_ARRAY_BUFFER$2+","+ELEMENTS+".buffer.buffer);","}")),ELEMENTS}function emitCount(){var COUNT,defn=drawOptions.count,scope=outer;return defn?((defn.contextDep&&args.contextDynamic||defn.propDep)&&(scope=inner),COUNT=defn.append(env,scope),check$1.optional((function(){defn.MISSING&&env.assert(outer,"false","missing vertex count"),defn.DYNAMIC&&env.assert(scope,COUNT+">=0","missing vertex count")}))):(COUNT=scope.def(DRAW_STATE,".",S_COUNT),check$1.optional((function(){env.assert(scope,COUNT+">=0","missing vertex count")}))),COUNT}var ELEMENTS=emitElements();function emitValue(name){var defn=drawOptions[name];return defn?defn.contextDep&&args.contextDynamic||defn.propDep?defn.append(env,inner):defn.append(env,outer):outer.def(DRAW_STATE,".",name)}var INSTANCES,EXT_INSTANCING,PRIMITIVE=emitValue(S_PRIMITIVE),OFFSET=emitValue(S_OFFSET),COUNT=emitCount();if("number"==typeof COUNT){if(0===COUNT)return}else inner("if(",COUNT,"){"),inner.exit("}");extInstancing&&(INSTANCES=emitValue(S_INSTANCES),EXT_INSTANCING=env.instancing);var ELEMENT_TYPE=ELEMENTS+".type",elementsStatic=drawOptions.elements&&isStatic(drawOptions.elements)&&!drawOptions.vaoActive;function emitInstancing(){function drawElements(){inner(EXT_INSTANCING,".drawElementsInstancedANGLE(",[PRIMITIVE,COUNT,ELEMENT_TYPE,OFFSET+"<<(("+ELEMENT_TYPE+"-"+GL_UNSIGNED_BYTE$8+")>>1)",INSTANCES],");")}function drawArrays(){inner(EXT_INSTANCING,".drawArraysInstancedANGLE(",[PRIMITIVE,OFFSET,COUNT,INSTANCES],");")}ELEMENTS&&"null"!==ELEMENTS?elementsStatic?drawElements():(inner("if(",ELEMENTS,"){"),drawElements(),inner("}else{"),drawArrays(),inner("}")):drawArrays()}function emitRegular(){function drawElements(){inner(GL+".drawElements("+[PRIMITIVE,COUNT,ELEMENT_TYPE,OFFSET+"<<(("+ELEMENT_TYPE+"-"+GL_UNSIGNED_BYTE$8+")>>1)"]+");")}function drawArrays(){inner(GL+".drawArrays("+[PRIMITIVE,OFFSET,COUNT]+");")}ELEMENTS&&"null"!==ELEMENTS?elementsStatic?drawElements():(inner("if(",ELEMENTS,"){"),drawElements(),inner("}else{"),drawArrays(),inner("}")):drawArrays()}extInstancing&&("number"!=typeof INSTANCES||INSTANCES>=0)?"string"==typeof INSTANCES?(inner("if(",INSTANCES,">0){"),emitInstancing(),inner("}else if(",INSTANCES,"<0){"),emitRegular(),inner("}")):emitInstancing():emitRegular()}function createBody(emitBody,parentEnv,args,program,count){var env=createREGLEnvironment(),scope=env.proc("body",count);return check$1.optional((function(){env.commandStr=parentEnv.commandStr,env.command=env.link(parentEnv.commandStr)})),extInstancing&&(env.instancing=scope.def(env.shared.extensions,".angle_instanced_arrays")),emitBody(env,scope,args,program),env.compile().body}function emitDrawBody(env,draw,args,program){injectExtensions(env,draw),args.useVAO?args.drawVAO?draw(env.shared.vao,".setVAO(",args.drawVAO.append(env,draw),");"):draw(env.shared.vao,".setVAO(",env.shared.vao,".targetVAO);"):(draw(env.shared.vao,".setVAO(null);"),emitAttributes(env,draw,args,program.attributes,(function(){return!0}))),emitUniforms(env,draw,args,program.uniforms,(function(){return!0}),!1),emitDraw(env,draw,draw,args)}function emitDrawProc(env,args){var draw=env.proc("draw",1);injectExtensions(env,draw),emitContext(env,draw,args.context),emitPollFramebuffer(env,draw,args.framebuffer),emitPollState(env,draw,args),emitSetOptions(env,draw,args.state),emitProfile(env,draw,args,!1,!0);var program=args.shader.progVar.append(env,draw);if(draw(env.shared.gl,".useProgram(",program,".program);"),args.shader.program)emitDrawBody(env,draw,args,args.shader.program);else{draw(env.shared.vao,".setVAO(null);");var drawCache=env.global.def("{}"),PROG_ID=draw.def(program,".id"),CACHED_PROC=draw.def(drawCache,"[",PROG_ID,"]");draw(env.cond(CACHED_PROC).then(CACHED_PROC,".call(this,a0);").else(CACHED_PROC,"=",drawCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitDrawBody,env,args,program,1)})),"(",program,");",CACHED_PROC,".call(this,a0);"))}Object.keys(args.state).length>0&&draw(env.shared.current,".dirty=true;"),env.shared.vao&&draw(env.shared.vao,".setVAO(null);")}function emitBatchDynamicShaderBody(env,scope,args,program){function all(){return!0}env.batchId="a1",injectExtensions(env,scope),emitAttributes(env,scope,args,program.attributes,all),emitUniforms(env,scope,args,program.uniforms,all,!1),emitDraw(env,scope,scope,args)}function emitBatchBody(env,scope,args,program){injectExtensions(env,scope);var contextDynamic=args.contextDep,BATCH_ID=scope.def(),PROP_LIST="a0",NUM_PROPS="a1",PROPS=scope.def();env.shared.props=PROPS,env.batchId=BATCH_ID;var outer=env.scope(),inner=env.scope();function isInnerDefn(defn){return defn.contextDep&&contextDynamic||defn.propDep}function isOuterDefn(defn){return!isInnerDefn(defn)}if(scope(outer.entry,"for(",BATCH_ID,"=0;",BATCH_ID,"<",NUM_PROPS,";++",BATCH_ID,"){",PROPS,"=",PROP_LIST,"[",BATCH_ID,"];",inner,"}",outer.exit),args.needsContext&&emitContext(env,inner,args.context),args.needsFramebuffer&&emitPollFramebuffer(env,inner,args.framebuffer),emitSetOptions(env,inner,args.state,isInnerDefn),args.profile&&isInnerDefn(args.profile)&&emitProfile(env,inner,args,!1,!0),program)args.useVAO?args.drawVAO?isInnerDefn(args.drawVAO)?inner(env.shared.vao,".setVAO(",args.drawVAO.append(env,inner),");"):outer(env.shared.vao,".setVAO(",args.drawVAO.append(env,outer),");"):outer(env.shared.vao,".setVAO(",env.shared.vao,".targetVAO);"):(outer(env.shared.vao,".setVAO(null);"),emitAttributes(env,outer,args,program.attributes,isOuterDefn),emitAttributes(env,inner,args,program.attributes,isInnerDefn)),emitUniforms(env,outer,args,program.uniforms,isOuterDefn,!1),emitUniforms(env,inner,args,program.uniforms,isInnerDefn,!0),emitDraw(env,outer,inner,args);else{var progCache=env.global.def("{}"),PROGRAM=args.shader.progVar.append(env,inner),PROG_ID=inner.def(PROGRAM,".id"),CACHED_PROC=inner.def(progCache,"[",PROG_ID,"]");inner(env.shared.gl,".useProgram(",PROGRAM,".program);","if(!",CACHED_PROC,"){",CACHED_PROC,"=",progCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitBatchDynamicShaderBody,env,args,program,2)})),"(",PROGRAM,");}",CACHED_PROC,".call(this,a0[",BATCH_ID,"],",BATCH_ID,");")}}function emitBatchProc(env,args){var batch=env.proc("batch",2);env.batchId="0",injectExtensions(env,batch);var contextDynamic=!1,needsContext=!0;Object.keys(args.context).forEach((function(name){contextDynamic=contextDynamic||args.context[name].propDep})),contextDynamic||(emitContext(env,batch,args.context),needsContext=!1);var framebuffer=args.framebuffer,needsFramebuffer=!1;function isInnerDefn(defn){return defn.contextDep&&contextDynamic||defn.propDep}framebuffer?(framebuffer.propDep?contextDynamic=needsFramebuffer=!0:framebuffer.contextDep&&contextDynamic&&(needsFramebuffer=!0),needsFramebuffer||emitPollFramebuffer(env,batch,framebuffer)):emitPollFramebuffer(env,batch,null),args.state.viewport&&args.state.viewport.propDep&&(contextDynamic=!0),emitPollState(env,batch,args),emitSetOptions(env,batch,args.state,(function(defn){return!isInnerDefn(defn)})),args.profile&&isInnerDefn(args.profile)||emitProfile(env,batch,args,!1,"a1"),args.contextDep=contextDynamic,args.needsContext=needsContext,args.needsFramebuffer=needsFramebuffer;var progDefn=args.shader.progVar;if(progDefn.contextDep&&contextDynamic||progDefn.propDep)emitBatchBody(env,batch,args,null);else{var PROGRAM=progDefn.append(env,batch);if(batch(env.shared.gl,".useProgram(",PROGRAM,".program);"),args.shader.program)emitBatchBody(env,batch,args,args.shader.program);else{batch(env.shared.vao,".setVAO(null);");var batchCache=env.global.def("{}"),PROG_ID=batch.def(PROGRAM,".id"),CACHED_PROC=batch.def(batchCache,"[",PROG_ID,"]");batch(env.cond(CACHED_PROC).then(CACHED_PROC,".call(this,a0,a1);").else(CACHED_PROC,"=",batchCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitBatchBody,env,args,program,2)})),"(",PROGRAM,");",CACHED_PROC,".call(this,a0,a1);"))}}Object.keys(args.state).length>0&&batch(env.shared.current,".dirty=true;"),env.shared.vao&&batch(env.shared.vao,".setVAO(null);")}function emitScopeProc(env,args){var scope=env.proc("scope",3);env.batchId="a2";var shared=env.shared,CURRENT_STATE=shared.current;function saveShader(name){var shader=args.shader[name];shader&&scope.set(shared.shader,"."+name,shader.append(env,scope))}emitContext(env,scope,args.context),args.framebuffer&&args.framebuffer.append(env,scope),sortState(Object.keys(args.state)).forEach((function(name){var value=args.state[name].append(env,scope);isArrayLike(value)?value.forEach((function(v,i){scope.set(env.next[name],"["+i+"]",v)})):scope.set(shared.next,"."+name,value)})),emitProfile(env,scope,args,!0,!0),[S_ELEMENTS,S_OFFSET,S_COUNT,S_INSTANCES,S_PRIMITIVE].forEach((function(opt){var variable=args.draw[opt];variable&&scope.set(shared.draw,"."+opt,""+variable.append(env,scope))})),Object.keys(args.uniforms).forEach((function(opt){var value=args.uniforms[opt].append(env,scope);Array.isArray(value)&&(value="["+value.join()+"]"),scope.set(shared.uniforms,"["+stringStore.id(opt)+"]",value)})),Object.keys(args.attributes).forEach((function(name){var record=args.attributes[name].append(env,scope),scopeAttrib=env.scopeAttrib(name);Object.keys(new AttributeRecord).forEach((function(prop){scope.set(scopeAttrib,"."+prop,record[prop])}))})),args.scopeVAO&&scope.set(shared.vao,".targetVAO",args.scopeVAO.append(env,scope)),saveShader(S_VERT),saveShader(S_FRAG),Object.keys(args.state).length>0&&(scope(CURRENT_STATE,".dirty=true;"),scope.exit(CURRENT_STATE,".dirty=true;")),scope("a1(",env.shared.context,",a0,",env.batchId,");")}function isDynamicObject(object){if("object"==typeof object&&!isArrayLike(object)){for(var props=Object.keys(object),i=0;i<props.length;++i)if(dynamic.isDynamic(object[props[i]]))return!0;return!1}}function splatObject(env,options,name){var object=options.static[name];if(object&&isDynamicObject(object)){var globals=env.global,keys=Object.keys(object),thisDep=!1,contextDep=!1,propDep=!1,objectRef=env.global.def("{}");keys.forEach((function(key){var value=object[key];if(dynamic.isDynamic(value)){"function"==typeof value&&(value=object[key]=dynamic.unbox(value));var deps=createDynamicDecl(value,null);thisDep=thisDep||deps.thisDep,propDep=propDep||deps.propDep,contextDep=contextDep||deps.contextDep}else{switch(globals(objectRef,".",key,"="),typeof value){case"number":globals(value);break;case"string":globals('"',value,'"');break;case"object":Array.isArray(value)&&globals("[",value.join(),"]");break;default:globals(env.link(value))}globals(";")}})),options.dynamic[name]=new dynamic.DynamicVariable(DYN_THUNK,{thisDep:thisDep,contextDep:contextDep,propDep:propDep,ref:objectRef,append:appendBlock}),delete options.static[name]}function appendBlock(env,block){keys.forEach((function(key){var value=object[key];if(dynamic.isDynamic(value)){var ref=env.invoke(block,value);block(objectRef,".",key,"=",ref,";")}}))}}function compileCommand(options,attributes,uniforms,context,stats){var env=createREGLEnvironment();env.stats=env.link(stats),Object.keys(attributes.static).forEach((function(key){splatObject(env,attributes,key)})),NESTED_OPTIONS.forEach((function(name){splatObject(env,options,name)}));var args=parseArguments(options,attributes,uniforms,context,env);return emitDrawProc(env,args),emitScopeProc(env,args),emitBatchProc(env,args),extend(env.compile(),{destroy:function(){args.shader.program.destroy()}})}return{next:nextState,current:currentState,procs:function(){var env=createREGLEnvironment(),poll=env.proc("poll"),refresh=env.proc("refresh"),common=env.block();poll(common),refresh(common);var INSTANCING,shared=env.shared,GL=shared.gl,NEXT_STATE=shared.next,CURRENT_STATE=shared.current;common(CURRENT_STATE,".dirty=false;"),emitPollFramebuffer(env,poll),emitPollFramebuffer(env,refresh,null,!0),extInstancing&&(INSTANCING=env.link(extInstancing)),extensions.oes_vertex_array_object&&refresh(env.link(extensions.oes_vertex_array_object),".bindVertexArrayOES(null);");for(var i=0;i<limits.maxAttributes;++i){var BINDING=refresh.def(shared.attributes,"[",i,"]"),ifte=env.cond(BINDING,".buffer");ifte.then(GL,".enableVertexAttribArray(",i,");",GL,".bindBuffer(",GL_ARRAY_BUFFER$2,",",BINDING,".buffer.buffer);",GL,".vertexAttribPointer(",i,",",BINDING,".size,",BINDING,".type,",BINDING,".normalized,",BINDING,".stride,",BINDING,".offset);").else(GL,".disableVertexAttribArray(",i,");",GL,".vertexAttrib4f(",i,",",BINDING,".x,",BINDING,".y,",BINDING,".z,",BINDING,".w);",BINDING,".buffer=null;"),refresh(ifte),extInstancing&&refresh(INSTANCING,".vertexAttribDivisorANGLE(",i,",",BINDING,".divisor);")}return refresh(env.shared.vao,".currentVAO=null;",env.shared.vao,".setVAO(",env.shared.vao,".targetVAO);"),Object.keys(GL_FLAGS).forEach((function(flag){var cap=GL_FLAGS[flag],NEXT=common.def(NEXT_STATE,".",flag),block=env.block();block("if(",NEXT,"){",GL,".enable(",cap,")}else{",GL,".disable(",cap,")}",CURRENT_STATE,".",flag,"=",NEXT,";"),refresh(block),poll("if(",NEXT,"!==",CURRENT_STATE,".",flag,"){",block,"}")})),Object.keys(GL_VARIABLES).forEach((function(name){var NEXT,CURRENT,func=GL_VARIABLES[name],init=currentState[name],block=env.block();if(block(GL,".",func,"("),isArrayLike(init)){var n=init.length;NEXT=env.global.def(NEXT_STATE,".",name),CURRENT=env.global.def(CURRENT_STATE,".",name),block(loop(n,(function(i){return NEXT+"["+i+"]"})),");",loop(n,(function(i){return CURRENT+"["+i+"]="+NEXT+"["+i+"];"})).join("")),poll("if(",loop(n,(function(i){return NEXT+"["+i+"]!=="+CURRENT+"["+i+"]"})).join("||"),"){",block,"}")}else NEXT=common.def(NEXT_STATE,".",name),CURRENT=common.def(CURRENT_STATE,".",name),block(NEXT,");",CURRENT_STATE,".",name,"=",NEXT,";"),poll("if(",NEXT,"!==",CURRENT,"){",block,"}");refresh(block)})),env.compile()}(),compile:compileCommand}}function stats(){return{vaoCount:0,bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,cubeCount:0,renderbufferCount:0,maxTextureUnits:0}}var GL_QUERY_RESULT_EXT=34918,GL_QUERY_RESULT_AVAILABLE_EXT=34919,GL_TIME_ELAPSED_EXT=35007,createTimer=function(gl,extensions){if(!extensions.ext_disjoint_timer_query)return null;var queryPool=[];function allocQuery(){return queryPool.pop()||extensions.ext_disjoint_timer_query.createQueryEXT()}function freeQuery(query){queryPool.push(query)}var pendingQueries=[];function beginQuery(stats){var query=allocQuery();extensions.ext_disjoint_timer_query.beginQueryEXT(GL_TIME_ELAPSED_EXT,query),pendingQueries.push(query),pushScopeStats(pendingQueries.length-1,pendingQueries.length,stats)}function endQuery(){extensions.ext_disjoint_timer_query.endQueryEXT(GL_TIME_ELAPSED_EXT)}function PendingStats(){this.startQueryIndex=-1,this.endQueryIndex=-1,this.sum=0,this.stats=null}var pendingStatsPool=[];function allocPendingStats(){return pendingStatsPool.pop()||new PendingStats}function freePendingStats(pendingStats){pendingStatsPool.push(pendingStats)}var pendingStats=[];function pushScopeStats(start,end,stats){var ps=allocPendingStats();ps.startQueryIndex=start,ps.endQueryIndex=end,ps.sum=0,ps.stats=stats,pendingStats.push(ps)}var timeSum=[],queryPtr=[];function update(){var ptr,i,n=pendingQueries.length;if(0!==n){queryPtr.length=Math.max(queryPtr.length,n+1),timeSum.length=Math.max(timeSum.length,n+1),timeSum[0]=0,queryPtr[0]=0;var queryTime=0;for(ptr=0,i=0;i<pendingQueries.length;++i){var query=pendingQueries[i];extensions.ext_disjoint_timer_query.getQueryObjectEXT(query,GL_QUERY_RESULT_AVAILABLE_EXT)?(queryTime+=extensions.ext_disjoint_timer_query.getQueryObjectEXT(query,GL_QUERY_RESULT_EXT),freeQuery(query)):pendingQueries[ptr++]=query,timeSum[i+1]=queryTime,queryPtr[i+1]=ptr}for(pendingQueries.length=ptr,ptr=0,i=0;i<pendingStats.length;++i){var stats=pendingStats[i],start=stats.startQueryIndex,end=stats.endQueryIndex;stats.sum+=timeSum[end]-timeSum[start];var startPtr=queryPtr[start],endPtr=queryPtr[end];endPtr===startPtr?(stats.stats.gpuTime+=stats.sum/1e6,freePendingStats(stats)):(stats.startQueryIndex=startPtr,stats.endQueryIndex=endPtr,pendingStats[ptr++]=stats)}pendingStats.length=ptr}}return{beginQuery:beginQuery,endQuery:endQuery,pushScopeStats:pushScopeStats,update:update,getNumPendingQueries:function(){return pendingQueries.length},clear:function(){queryPool.push.apply(queryPool,pendingQueries);for(var i=0;i<queryPool.length;i++)extensions.ext_disjoint_timer_query.deleteQueryEXT(queryPool[i]);pendingQueries.length=0,queryPool.length=0},restore:function(){pendingQueries.length=0,queryPool.length=0}}},GL_COLOR_BUFFER_BIT=16384,GL_DEPTH_BUFFER_BIT=256,GL_STENCIL_BUFFER_BIT=1024,GL_ARRAY_BUFFER=34962,CONTEXT_LOST_EVENT="webglcontextlost",CONTEXT_RESTORED_EVENT="webglcontextrestored",DYN_PROP=1,DYN_CONTEXT=2,DYN_STATE=3;function find(haystack,needle){for(var i=0;i<haystack.length;++i)if(haystack[i]===needle)return i;return-1}function wrapREGL(args){var config=parseArgs(args);if(!config)return null;var gl=config.gl,glAttributes=gl.getContextAttributes(),contextLost=gl.isContextLost(),extensionState=createExtensionCache(gl,config);if(!extensionState)return null;var stringStore=createStringStore(),stats$$1=stats(),extensions=extensionState.extensions,timer=createTimer(gl,extensions),START_TIME=clock(),WIDTH=gl.drawingBufferWidth,HEIGHT=gl.drawingBufferHeight,contextState={tick:0,time:0,viewportWidth:WIDTH,viewportHeight:HEIGHT,framebufferWidth:WIDTH,framebufferHeight:HEIGHT,drawingBufferWidth:WIDTH,drawingBufferHeight:HEIGHT,pixelRatio:config.pixelRatio},uniformState={},drawState={elements:null,primitive:4,count:-1,offset:0,instances:-1},limits=wrapLimits(gl,extensions),bufferState=wrapBufferState(gl,stats$$1,config,destroyBuffer),elementState=wrapElementsState(gl,extensions,bufferState,stats$$1),attributeState=wrapAttributeState(gl,extensions,limits,stats$$1,bufferState,elementState,drawState);function destroyBuffer(buffer){return attributeState.destroyBuffer(buffer)}var shaderState=wrapShaderState(gl,stringStore,stats$$1,config),textureState=createTextureSet(gl,extensions,limits,(function(){core.procs.poll()}),contextState,stats$$1,config),renderbufferState=wrapRenderbuffers(gl,extensions,limits,stats$$1,config),framebufferState=wrapFBOState(gl,extensions,limits,textureState,renderbufferState,stats$$1),core=reglCore(gl,stringStore,extensions,limits,bufferState,elementState,textureState,framebufferState,uniformState,attributeState,shaderState,drawState,contextState,timer,config),readPixels=wrapReadPixels(gl,framebufferState,core.procs.poll,contextState,glAttributes,extensions,limits),nextState=core.next,canvas=gl.canvas,rafCallbacks=[],lossCallbacks=[],restoreCallbacks=[],destroyCallbacks=[config.onDestroy],activeRAF=null;function handleRAF(){if(0===rafCallbacks.length)return timer&&timer.update(),void(activeRAF=null);activeRAF=raf.next(handleRAF),poll();for(var i=rafCallbacks.length-1;i>=0;--i){var cb=rafCallbacks[i];cb&&cb(contextState,null,0)}gl.flush(),timer&&timer.update()}function startRAF(){!activeRAF&&rafCallbacks.length>0&&(activeRAF=raf.next(handleRAF))}function stopRAF(){activeRAF&&(raf.cancel(handleRAF),activeRAF=null)}function handleContextLoss(event){event.preventDefault(),contextLost=!0,stopRAF(),lossCallbacks.forEach((function(cb){cb()}))}function handleContextRestored(event){gl.getError(),contextLost=!1,extensionState.restore(),shaderState.restore(),bufferState.restore(),textureState.restore(),renderbufferState.restore(),framebufferState.restore(),attributeState.restore(),timer&&timer.restore(),core.procs.refresh(),startRAF(),restoreCallbacks.forEach((function(cb){cb()}))}function destroy(){rafCallbacks.length=0,stopRAF(),canvas&&(canvas.removeEventListener(CONTEXT_LOST_EVENT,handleContextLoss),canvas.removeEventListener(CONTEXT_RESTORED_EVENT,handleContextRestored)),shaderState.clear(),framebufferState.clear(),renderbufferState.clear(),attributeState.clear(),textureState.clear(),elementState.clear(),bufferState.clear(),timer&&timer.clear(),destroyCallbacks.forEach((function(cb){cb()}))}function compileProcedure(options){function flattenNestedOptions(options){var result=extend({},options);function merge(name){if(name in result){var child=result[name];delete result[name],Object.keys(child).forEach((function(prop){result[name+"."+prop]=child[prop]}))}}return delete result.uniforms,delete result.attributes,delete result.context,delete result.vao,"stencil"in result&&result.stencil.op&&(result.stencil.opBack=result.stencil.opFront=result.stencil.op,delete result.stencil.op),merge("blend"),merge("depth"),merge("cull"),merge("stencil"),merge("polygonOffset"),merge("scissor"),merge("sample"),"vao"in options&&(result.vao=options.vao),result}function separateDynamic(object,useArrays){var staticItems={},dynamicItems={};return Object.keys(object).forEach((function(option){var value=object[option];if(dynamic.isDynamic(value))dynamicItems[option]=dynamic.unbox(value,option);else{if(useArrays&&Array.isArray(value))for(var i=0;i<value.length;++i)if(dynamic.isDynamic(value[i]))return void(dynamicItems[option]=dynamic.unbox(value,option));staticItems[option]=value}})),{dynamic:dynamicItems,static:staticItems}}check$1(!!options,"invalid args to regl({...})"),check$1.type(options,"object","invalid args to regl({...})");var context=separateDynamic(options.context||{},!0),uniforms=separateDynamic(options.uniforms||{},!0),attributes=separateDynamic(options.attributes||{},!1),opts=separateDynamic(flattenNestedOptions(options),!1),stats$$1={gpuTime:0,cpuTime:0,count:0},compiled=core.compile(opts,attributes,uniforms,context,stats$$1),draw=compiled.draw,batch=compiled.batch,scope=compiled.scope,EMPTY_ARRAY=[];function reserve(count){for(;EMPTY_ARRAY.length<count;)EMPTY_ARRAY.push(null);return EMPTY_ARRAY}function REGLCommand(args,body){var i;if(contextLost&&check$1.raise("context lost"),"function"==typeof args)return scope.call(this,null,args,0);if("function"==typeof body)if("number"==typeof args)for(i=0;i<args;++i)scope.call(this,null,body,i);else{if(!Array.isArray(args))return scope.call(this,args,body,0);for(i=0;i<args.length;++i)scope.call(this,args[i],body,i)}else if("number"==typeof args){if(args>0)return batch.call(this,reserve(0|args),0|args)}else{if(!Array.isArray(args))return draw.call(this,args);if(args.length)return batch.call(this,args,args.length)}}return extend(REGLCommand,{stats:stats$$1,destroy:function(){compiled.destroy()}})}canvas&&(canvas.addEventListener(CONTEXT_LOST_EVENT,handleContextLoss,!1),canvas.addEventListener(CONTEXT_RESTORED_EVENT,handleContextRestored,!1));var setFBO=framebufferState.setFBO=compileProcedure({framebuffer:dynamic.define.call(null,DYN_PROP,"framebuffer")});function clearImpl(_,options){var clearFlags=0;core.procs.poll();var c=options.color;c&&(gl.clearColor(+c[0]||0,+c[1]||0,+c[2]||0,+c[3]||0),clearFlags|=GL_COLOR_BUFFER_BIT),"depth"in options&&(gl.clearDepth(+options.depth),clearFlags|=GL_DEPTH_BUFFER_BIT),"stencil"in options&&(gl.clearStencil(0|options.stencil),clearFlags|=GL_STENCIL_BUFFER_BIT),check$1(!!clearFlags,"called regl.clear with no buffer specified"),gl.clear(clearFlags)}function clear(options){if(check$1("object"==typeof options&&options,"regl.clear() takes an object as input"),"framebuffer"in options)if(options.framebuffer&&"framebufferCube"===options.framebuffer_reglType)for(var i=0;i<6;++i)setFBO(extend({framebuffer:options.framebuffer.faces[i]},options),clearImpl);else setFBO(options,clearImpl);else clearImpl(null,options)}function frame(cb){function cancel(){var i=find(rafCallbacks,cb);function pendingCancel(){var index=find(rafCallbacks,pendingCancel);rafCallbacks[index]=rafCallbacks[rafCallbacks.length-1],rafCallbacks.length-=1,rafCallbacks.length<=0&&stopRAF()}check$1(i>=0,"cannot cancel a frame twice"),rafCallbacks[i]=pendingCancel}return check$1.type(cb,"function","regl.frame() callback must be a function"),rafCallbacks.push(cb),startRAF(),{cancel:cancel}}function pollViewport(){var viewport=nextState.viewport,scissorBox=nextState.scissor_box;viewport[0]=viewport[1]=scissorBox[0]=scissorBox[1]=0,contextState.viewportWidth=contextState.framebufferWidth=contextState.drawingBufferWidth=viewport[2]=scissorBox[2]=gl.drawingBufferWidth,contextState.viewportHeight=contextState.framebufferHeight=contextState.drawingBufferHeight=viewport[3]=scissorBox[3]=gl.drawingBufferHeight}function poll(){contextState.tick+=1,contextState.time=now(),pollViewport(),core.procs.poll()}function refresh(){textureState.refresh(),pollViewport(),core.procs.refresh(),timer&&timer.update()}function now(){return(clock()-START_TIME)/1e3}function addListener(event,callback){var callbacks;switch(check$1.type(callback,"function","listener callback must be a function"),event){case"frame":return frame(callback);case"lost":callbacks=lossCallbacks;break;case"restore":callbacks=restoreCallbacks;break;case"destroy":callbacks=destroyCallbacks;break;default:check$1.raise("invalid event, must be one of frame,lost,restore,destroy")}return callbacks.push(callback),{cancel:function(){for(var i=0;i<callbacks.length;++i)if(callbacks[i]===callback)return callbacks[i]=callbacks[callbacks.length-1],void callbacks.pop()}}}refresh();var regl=extend(compileProcedure,{clear:clear,prop:dynamic.define.bind(null,DYN_PROP),context:dynamic.define.bind(null,DYN_CONTEXT),this:dynamic.define.bind(null,DYN_STATE),draw:compileProcedure({}),buffer:function(options){return bufferState.create(options,GL_ARRAY_BUFFER,!1,!1)},elements:function(options){return elementState.create(options,!1)},texture:textureState.create2D,cube:textureState.createCube,renderbuffer:renderbufferState.create,framebuffer:framebufferState.create,framebufferCube:framebufferState.createCube,vao:attributeState.createVAO,attributes:glAttributes,frame:frame,on:addListener,limits:limits,hasExtension:function(name){return limits.extensions.indexOf(name.toLowerCase())>=0},read:readPixels,destroy:destroy,_gl:gl,_refresh:refresh,poll:function(){poll(),timer&&timer.update()},now:now,stats:stats$$1});return config.onDone(null,regl),regl}return wrapREGL}()}({get exports(){return reglExports},set exports(v){reglExports=v}});var regl=reglExports;exports.cameras=index$2,exports.commands=index$1,exports.controls=index,exports.entitiesFromSolids=(options,...solids)=>{const defaults={color:meshColor,smoothNormals:!0},{color:color,smoothNormals:smoothNormals}=Object.assign({},defaults,options);var array;solids=(solids=flatten((array=solids,Array.isArray(array)?array:null==array?[]:[array]))).filter((solid=>solid&&solid instanceof Object));const entities=[];return solids.forEach((solid=>{let geometries=[];"outlines"in solid?geometries=((options,solid)=>{let{color:color}=options;const outlines=solid.outlines;if(0===outlines.length)return[];"color"in solid&&(color=solid.color);const isTransparent=color[3]<1,geometries=[];for(let i=0;i<outlines.length;i++){const points=outlines[i],numgeometries=Math.floor(points.length/maxIndex$2)+1;for(let g=0;g<numgeometries;g++){const offset=g*maxIndex$2,endset=Math.min(offset+maxIndex$2,points.length),positions=[];let prevvertice;for(let j=offset;j<endset;j++){const point=points[j];prevvertice&&(positions.push([prevvertice[0],prevvertice[1],0]),positions.push([point[0],point[1],0])),prevvertice=point}if(g+1===numgeometries&&prevvertice){const point=points[0];positions.push([prevvertice[0],prevvertice[1],0]),positions.push([point[0],point[1],0])}const normal=[0,0,-1],normals=positions.map((x=>normal)),indices=positions.map(((x,i)=>i)),transforms=solid.transforms?glMat4.clone(solid.transforms):glMat4.create();geometries.push({type:"2d",positions:positions,normals:normals,indices:indices,transforms:transforms,color:color,isTransparent:isTransparent})}}return geometries})({color:color},solid):"points"in solid?geometries=((options,solid)=>{let{color:color}=options;const points=solid.points;if(0===points.length)return[];"color"in solid&&(color=solid.color);const isTransparent=color[3]<1,numgeometries=Math.floor(points.length/maxIndex)+1,geometries=[];for(let g=0;g<numgeometries;g++){const offset=g*maxIndex,endset=Math.min(offset+maxIndex,points.length),positions=[];let prevvertice;for(let i=offset;i<endset;i++){const point=points[i];prevvertice&&(positions.push([prevvertice[0],prevvertice[1],0]),positions.push([point[0],point[1],0])),prevvertice=point}if(g+1===numgeometries&&solid.isClosed&&prevvertice){const point=points[0];positions.push([prevvertice[0],prevvertice[1],0]),positions.push([point[0],point[1],0])}const normal=[0,0,-1],normals=positions.map((x=>normal)),indices=positions.map(((x,i)=>i)),transforms=solid.transforms?glMat4.clone(solid.transforms):glMat4.create();geometries.push({type:"2d",positions:positions,normals:normals,indices:indices,transforms:transforms,color:color,isTransparent:isTransparent})}return geometries})({color:color},solid):"polygons"in solid&&(geometries=((options,solid)=>{let{color:color,smoothLighting:smoothLighting}=options;"color"in solid&&(color=solid.color);const polygons=solid.polygons,transforms=solid.transforms?glMat4.clone(solid.transforms):glMat4.create(),geometries=[];let setstart=0;for(;setstart<polygons.length;){let vcount=0,setend=setstart;for(let i=setstart;i<polygons.length&&(vcount+=polygons[i].vertices.length,!(vcount>65535));i++)setend++;const positions=[],normals=[],indices=[],colors=[],isTransparent=color[3]<1;for(let i=setstart;i<setend;i++){const polygon=polygons[i],vertices=polygon.vertices,normal=calculateNormal(polygon),faceColor=polygonColor(polygon,color),polygonIndices=[];for(let j=0;j<vertices.length;j++){const position=vertices[j];positions.push(position),normals.push(normal),colors.push(faceColor);const index=positions.length-1;polygonIndices.push(index)}for(let j=2;j<polygonIndices.length;j++)indices.push([polygonIndices[0],polygonIndices[j-1],polygonIndices[j]])}const geometry={type:"3d",positions:positions,normals:normals,indices:indices,colors:colors,transforms:transforms,isTransparent:isTransparent};geometries.push(geometry),setstart=setend}return geometries})({smoothLighting:smoothNormals,normalThreshold:.3,color:color},solid)),entities.push(...(geometries=>geometries.map((geometry=>({geometry:geometry,visuals:{drawCmd:"2d"===geometry.type?"drawLines":"drawMesh",show:!0,transparent:geometry.isTransparent,useVertexColors:!0}}))))(geometries))})),entities},exports.prepareRender=params=>{const options=Object.assign({},{},params.glOptions,{onDone:(err,callback)=>{if(err)throw err}}),base=regl(options),drawCache2=new Map,command=props=>{props.rendering=Object.assign({},renderDefaults,props.rendering),((regl,params={})=>{const{fbo:fbo}=params,commandParams={cull:{enable:!0},context:{lightDirection:[.2,.2,1]},uniforms:{view:(context,props)=>props.camera.view,eye:(context,props)=>props.camera.position,projection:(context,props)=>props.camera.projection,camNear:(context,props)=>props.camera.near,camFar:(context,props)=>props.camera.far,invertedView:(context,props)=>glMat4.invert([],props.camera.view),lightPosition:(context,props)=>props&&props.rendering&&props.rendering.lightPosition?props.rendering.lightPosition:[100,200,100],lightDirection:(context,props)=>props&&props.rendering&&props.rendering.lightDirection?props.rendering.lightDirection:context.lightDirection||[0,0,0],lightView:context=>glMat4.lookAt([],context.lightDirection,[0,0,0],[0,0,1]),lightProjection:glMat4.ortho([],-25,-25,-20,20,-25,25),lightColor:(context,props)=>props&&props.rendering&&props.rendering.lightColor?props.rendering.lightColor:[1,.8,0],ambientLightAmount:(context,props)=>props&&props.rendering&&props.rendering.ambientLightAmount?props.rendering.ambientLightAmount:.3,diffuseLightAmount:(context,props)=>props&&props.rendering&&props.rendering.diffuseLightAmount?props&&props.rendering&&props.rendering.diffuseLightAmount:.89,specularLightAmount:(context,props)=>props&&props.rendering&&props.rendering.specularLightAmount?props.rendering.specularLightAmount:.16,uMaterialShininess:(context,props)=>props&&props.rendering&&props.rendering.materialShininess?props.rendering.materialShininess:8,materialAmbient:[.5,.8,.3],materialDiffuse:[.5,.8,.3],materialSpecular:[.5,.8,.3]},framebuffer:fbo};return regl(Object.assign({},commandParams,params.extras))})(base)(props,(context=>{base.clear({color:props.rendering.background,depth:1}),props.entities&&props.entities.sort(((a,b)=>{const aTransparent="transparent"in a.visuals&&a.visuals.transparent;return aTransparent===("transparent"in b.visuals&&b.visuals.transparent)?0:aTransparent?1:-1})).forEach((entity=>{const{visuals:visuals}=entity;if((!("show"in visuals)||visuals.show)&&visuals.drawCmd&&props.drawCommands[visuals.drawCmd]){let drawCmd;visuals.cacheId?drawCmd=drawCache2.get(visuals.cacheId):(visuals.cacheId=drawCache2.size,drawCmd=props.drawCommands[visuals.drawCmd](base,entity),drawCache2.set(visuals.cacheId,drawCmd));drawCmd({...entity,...visuals,camera:props.camera})}}))}))};return function(data){base.poll(),command(data)}},Object.defineProperty(exports,"__esModule",{value:!0})}));